4b956cfd682f95b5207bd49596c03368441a18eb
[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
182             // required.
183             if (!(res instanceof SingleResource)) {
184                 return null;
185             }
186
187             final SimulatorResourceAttribute attribute;
188             if (!(element instanceof AttributeElement)) {
189                 return null;
190             }
191
192             final AttributeElement attributeElement = ((AttributeElement) element);
193             attribute = attributeElement.getSimulatorResourceAttribute();
194             if (null == attribute) {
195                 return null;
196             }
197
198             // CellEditor is not required as the automation is in progress.
199             if (attributeElement.isAutoUpdateInProgress()) {
200                 return null;
201             }
202
203             final AttributeValue val = attribute.value();
204             if (null == val) {
205                 return null;
206             }
207
208             final TypeInfo type = val.typeInfo();
209             if (type.mBaseType == ValueType.RESOURCEMODEL) {
210                 return null;
211             }
212
213             AttributeProperty prop = attribute.property();
214             if (null == prop) {
215                 return null;
216             }
217
218             if (!resourceManager.isAttHasRangeOrAllowedValues(attribute)) {
219                 return null;
220             }
221
222             String values[] = null;
223             List<String> valueSet = resourceManager
224                     .getAllValuesOfAttribute(attribute);
225             values = convertListToStringArray(valueSet);
226
227             ComboBoxCellEditor comboEditor;
228             if (type.mType == ValueType.ARRAY) {
229                 comboEditor = new ComboBoxCellEditor(viewer.getTree(), values);
230             } else {
231                 comboEditor = new ComboBoxCellEditor(viewer.getTree(), values,
232                         SWT.READ_ONLY);
233             }
234             comboBox = (CCombo) comboEditor.getControl();
235             comboBox.addModifyListener(new ModifyListener() {
236
237                 @Override
238                 public void modifyText(ModifyEvent event) {
239                     if (type.mType == ValueType.ARRAY) {
240                         return;
241                     }
242                     String oldValue = String.valueOf(Utility
243                             .getAttributeValueAsString(val));
244                     String newValue = comboBox.getText();
245
246                     attributeElement.setEditLock(true);
247                     compareAndUpdateAttribute(oldValue, newValue, element,
248                             attribute, type);
249                     attributeElement.setEditLock(false);
250
251                     comboBox.setVisible(false);
252                 }
253             });
254             return comboEditor;
255         }
256
257         @Override
258         protected Object getValue(Object element) {
259             int indexOfItem = 0;
260             SimulatorResourceAttribute att = null;
261
262             if (element instanceof AttributeElement) {
263                 att = ((AttributeElement) element)
264                         .getSimulatorResourceAttribute();
265             }
266
267             if (att == null) {
268                 return 0;
269             }
270
271             String valueString = Utility.getAttributeValueAsString(att.value());
272             List<String> valueSet = Activator.getDefault().getResourceManager()
273                     .getAllValuesOfAttribute(att);
274             if (null != valueSet) {
275                 indexOfItem = valueSet.indexOf(valueString);
276             }
277             if (indexOfItem == -1) {
278                 indexOfItem = 0;
279             }
280             return indexOfItem;
281         }
282
283         @Override
284         protected void setValue(Object element, Object value) {
285         }
286
287         public void compareAndUpdateAttribute(String oldValue, String newValue,
288                 Object element, SimulatorResourceAttribute att, TypeInfo type) {
289             if (null == oldValue || null == newValue || null == element
290                     || null == att || null == type) {
291                 return;
292             }
293             if (!oldValue.equals(newValue)) {
294                 // Get the AttriuteValue from the string
295                 AttributeValue attValue = AttributeValueBuilder.build(newValue,
296                         type.mBaseType);
297                 boolean invalid = false;
298                 if (null == attValue) {
299                     invalid = true;
300                 } else {
301                     TypeInfo resTypeInfo = attValue.typeInfo();
302                     if (type.mDepth != resTypeInfo.mDepth
303                             || type.mType != resTypeInfo.mType
304                             || type.mBaseType != resTypeInfo.mBaseType) {
305                         invalid = true;
306                     }
307                 }
308                 if (invalid) {
309                     MessageBox dialog = new MessageBox(viewer.getTree()
310                             .getShell(), SWT.ICON_ERROR | SWT.OK);
311                     dialog.setText("Invalid Value");
312                     dialog.setMessage("Given value is invalid");
313                     dialog.open();
314                 } else {
315                     MessageBox dialog = new MessageBox(viewer.getTree()
316                             .getShell(), SWT.ICON_QUESTION | SWT.OK
317                             | SWT.CANCEL);
318                     dialog.setText("Confirm action");
319                     dialog.setMessage("Do you want to modify the value?");
320                     int retval = dialog.open();
321                     if (retval != SWT.OK) {
322                         attValue = AttributeValueBuilder.build(oldValue,
323                                 type.mBaseType);
324                         updateAttributeValue(att, attValue);
325                     } else {
326                         updateAttributeValue(att, attValue);
327
328                         ResourceManager resourceManager;
329                         resourceManager = Activator.getDefault()
330                                 .getResourceManager();
331
332                         Resource resource = resourceManager
333                                 .getCurrentResourceInSelection();
334
335                         SimulatorResourceAttribute result = getResultantAttribute();
336
337                         boolean updated = resourceManager
338                                 .attributeValueUpdated(
339                                         (SingleResource) resource,
340                                         result.name(), result.value());
341                         if (!updated) {
342                             attValue = AttributeValueBuilder.build(oldValue,
343                                     type.mBaseType);
344                             updateAttributeValue(att, attValue);
345                             MessageDialog.openInformation(Display.getDefault()
346                                     .getActiveShell(), "Operation failed",
347                                     "Failed to update the attribute value.");
348                         }
349                     }
350                 }
351             }
352             viewer.update(element, null);
353         }
354
355         public String[] convertListToStringArray(List<String> valueList) {
356             String[] strArr;
357             if (null != valueList && valueList.size() > 0) {
358                 strArr = valueList.toArray(new String[1]);
359             } else {
360                 strArr = new String[1];
361             }
362             return strArr;
363         }
364
365         public void updateAttributeValue(SimulatorResourceAttribute att,
366                 AttributeValue value) {
367             IStructuredSelection selection = (IStructuredSelection) viewer
368                     .getSelection();
369             if (null == selection) {
370                 return;
371             }
372
373             Object obj = selection.getFirstElement();
374             if (null == obj) {
375                 return;
376             }
377
378             Tree t = viewer.getTree();
379             TreeItem item = t.getSelection()[0];
380             if (null == item) {
381                 return;
382             }
383
384             if (item.getData() instanceof AttributeElement) {
385                 AttributeElement attributeElement = (AttributeElement) item
386                         .getData();
387                 attributeElement.getSimulatorResourceAttribute()
388                         .setValue(value);
389
390                 TreeItem parent = item.getParentItem();
391                 if (null != parent) {
392                     Object data = parent.getData();
393                     try {
394                         ((AttributeElement) data).deepSetChildValue(att);
395                     } catch (InvalidArgsException e) {
396                         e.printStackTrace();
397                     }
398                 }
399             }
400         }
401
402         public SimulatorResourceAttribute getResultantAttribute() {
403             IStructuredSelection selection = (IStructuredSelection) viewer
404                     .getSelection();
405             if (null == selection) {
406                 return null;
407             }
408
409             Object obj = selection.getFirstElement();
410             if (null == obj) {
411                 return null;
412             }
413
414             Tree t = viewer.getTree();
415             TreeItem item = t.getSelection()[0];
416             if (null == item) {
417                 return null;
418             }
419
420             SimulatorResourceAttribute result = null;
421             TreeItem parent = item.getParentItem();
422             if (null == parent) {
423                 Object data = item.getData();
424                 result = ((AttributeElement) data)
425                         .getSimulatorResourceAttribute();
426             } else {
427                 while (parent.getParentItem() != null) {
428                     parent = parent.getParentItem();
429                 }
430
431                 // Parent will point to the top-level attribute of type
432                 Object data = parent.getData();
433                 result = ((AttributeElement) data)
434                         .getSimulatorResourceAttribute();
435             }
436
437             return result;
438         }
439     }
440
441     class AutomationEditor extends EditingSupport {
442
443         private final TreeViewer viewer;
444
445         public AutomationEditor(TreeViewer viewer) {
446             super(viewer);
447             this.viewer = viewer;
448         }
449
450         @Override
451         protected boolean canEdit(Object arg0) {
452             return true;
453         }
454
455         @Override
456         protected CellEditor getCellEditor(Object element) {
457             // CellEditor is not required as the automation is in progress.
458             ResourceManager resourceManager = Activator.getDefault()
459                     .getResourceManager();
460             Resource resource = resourceManager.getCurrentResourceInSelection();
461
462             if (null == resource) {
463                 return null;
464             }
465
466             if (!(resource instanceof SingleResource)) {
467                 return null;
468             }
469             if (((SingleResource) resource).isResourceAutomationInProgress()) {
470                 return null;
471             }
472
473             SimulatorResourceAttribute att = null;
474             if (element instanceof AttributeElement) {
475                 att = ((AttributeElement) element)
476                         .getSimulatorResourceAttribute();
477             }
478
479             if (null == att) {
480                 return null;
481             }
482
483             AttributeValue val = att.value();
484             if (null == val) {
485                 return null;
486             }
487
488             TypeInfo type = val.typeInfo();
489
490             if (type.mType == ValueType.RESOURCEMODEL
491                     || type.mType == ValueType.ARRAY) {
492                 return null;
493             }
494
495             Object parent = ((AttributeElement) element).getParent();
496             if (null != parent && !(parent instanceof ResourceRepresentation)) {
497                 return null;
498             }
499
500             if (((AttributeElement) element).isReadOnly()) {
501                 return null;
502             }
503
504             return new CheckboxCellEditor(null, SWT.CHECK | SWT.READ_ONLY);
505         }
506
507         @Override
508         protected Object getValue(Object element) {
509             if (element instanceof AttributeElement) {
510                 return ((AttributeElement) element).isAutoUpdateInProgress();
511             }
512
513             return false;
514         }
515
516         @Override
517         protected void setValue(Object element, Object value) {
518             if (!(element instanceof AttributeElement)) {
519                 return;
520             }
521
522             ResourceManager resourceManager = Activator.getDefault()
523                     .getResourceManager();
524             // As automation depends on the current resource in selection, its
525             // presence is being checked.
526             Resource resource = resourceManager.getCurrentResourceInSelection();
527             if (null == resource) {
528                 return;
529             }
530
531             AttributeElement att = (AttributeElement) element;
532             boolean checked = (Boolean) value;
533             if (checked) {
534                 // Start the automation
535                 // Fetch the settings data
536                 List<AutomationSettingHelper> automationSettings;
537                 automationSettings = AutomationSettingHelper
538                         .getAutomationSettings(att);
539
540                 // Open the settings dialog
541                 AutomationSettingDialog dialog = new AutomationSettingDialog(
542                         viewer.getTree().getShell(), automationSettings);
543                 dialog.create();
544                 if (dialog.open() == Window.OK) {
545                     String automationType = dialog.getAutomationType();
546                     String updateFreq = dialog.getUpdateFrequency();
547
548                     AutoUpdateType autoType = AutoUpdateType
549                             .valueOf(automationType);
550                     int updFreq = Utility
551                             .getUpdateIntervalFromString(updateFreq);
552                     int autoId = resourceManager.startAutomation(
553                             (SingleResource) resource, att, autoType, updFreq);
554                     if (autoId == -1) {
555                         MessageDialog.openInformation(Display.getDefault()
556                                 .getActiveShell(), "Automation Status",
557                                 "Automation start failed!!");
558                     }
559                 }
560             } else {
561                 // Stop the automation
562                 resourceManager.stopAutomation((SingleResource) resource, att,
563                         att.getAutoUpdateId());
564                 MessageDialog.openInformation(Display.getDefault()
565                         .getActiveShell(), "Automation Status",
566                         "Automation stopped.");
567             }
568         }
569     }
570 }