[IoTivity Simulator] Handling resource interfaces.
[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 = 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 String[] convertListToStringArray(List<String> valueList) {
355             String[] strArr;
356             if (null != valueList && valueList.size() > 0) {
357                 strArr = valueList.toArray(new String[1]);
358             } else {
359                 strArr = new String[1];
360             }
361             return strArr;
362         }
363
364         public void updateAttributeValue(SimulatorResourceAttribute att,
365                 AttributeValue value) {
366             IStructuredSelection selection = (IStructuredSelection) viewer
367                     .getSelection();
368             if (null == selection) {
369                 return;
370             }
371
372             Object obj = selection.getFirstElement();
373             if (null == obj) {
374                 return;
375             }
376
377             Tree t = viewer.getTree();
378             TreeItem item = t.getSelection()[0];
379             if (null == item) {
380                 return;
381             }
382
383             if (item.getData() instanceof AttributeElement) {
384                 AttributeElement attributeElement = (AttributeElement) item
385                         .getData();
386                 attributeElement.getSimulatorResourceAttribute()
387                         .setValue(value);
388
389                 TreeItem parent = item.getParentItem();
390                 if (null != parent) {
391                     Object data = parent.getData();
392                     try {
393                         ((AttributeElement) data).deepSetChildValue(att);
394                     } catch (InvalidArgsException e) {
395                         e.printStackTrace();
396                     }
397                 }
398             }
399         }
400
401         public SimulatorResourceAttribute getResultantAttribute() {
402             IStructuredSelection selection = (IStructuredSelection) viewer
403                     .getSelection();
404             if (null == selection) {
405                 return null;
406             }
407
408             Object obj = selection.getFirstElement();
409             if (null == obj) {
410                 return null;
411             }
412
413             Tree t = viewer.getTree();
414             TreeItem item = t.getSelection()[0];
415             if (null == item) {
416                 return null;
417             }
418
419             SimulatorResourceAttribute result = null;
420             TreeItem parent = item.getParentItem();
421             if (null == parent) {
422                 Object data = item.getData();
423                 result = ((AttributeElement) data)
424                         .getSimulatorResourceAttribute();
425             } else {
426                 while (parent.getParentItem() != null) {
427                     parent = parent.getParentItem();
428                 }
429
430                 // Parent will point to the top-level attribute of type
431                 Object data = parent.getData();
432                 result = ((AttributeElement) data)
433                         .getSimulatorResourceAttribute();
434             }
435
436             return result;
437         }
438     }
439
440     class AutomationEditor extends EditingSupport {
441
442         private final TreeViewer viewer;
443
444         public AutomationEditor(TreeViewer viewer) {
445             super(viewer);
446             this.viewer = viewer;
447         }
448
449         @Override
450         protected boolean canEdit(Object arg0) {
451             return true;
452         }
453
454         @Override
455         protected CellEditor getCellEditor(Object element) {
456             // CellEditor is not required as the automation is in progress.
457             ResourceManager resourceManager = Activator.getDefault()
458                     .getResourceManager();
459             Resource resource = resourceManager.getCurrentResourceInSelection();
460
461             if (null == resource) {
462                 return null;
463             }
464
465             if (!(resource instanceof SingleResource)) {
466                 return null;
467             }
468             if (((SingleResource) resource).isResourceAutomationInProgress()) {
469                 return null;
470             }
471
472             SimulatorResourceAttribute att = null;
473             if (element instanceof AttributeElement) {
474                 att = ((AttributeElement) element)
475                         .getSimulatorResourceAttribute();
476             }
477
478             if (null == att) {
479                 return null;
480             }
481
482             AttributeValue val = att.value();
483             if (null == val) {
484                 return null;
485             }
486
487             TypeInfo type = val.typeInfo();
488
489             if (type.mType == ValueType.RESOURCEMODEL
490                     || type.mType == ValueType.ARRAY) {
491                 return null;
492             }
493
494             Object parent = ((AttributeElement) element).getParent();
495             if (null != parent && !(parent instanceof ResourceRepresentation)) {
496                 return null;
497             }
498
499             if (((AttributeElement) element).isReadOnly()) {
500                 return null;
501             }
502
503             return new CheckboxCellEditor(null, SWT.CHECK | SWT.READ_ONLY);
504         }
505
506         @Override
507         protected Object getValue(Object element) {
508             if (element instanceof AttributeElement) {
509                 return ((AttributeElement) element).isAutoUpdateInProgress();
510             }
511
512             return false;
513         }
514
515         @Override
516         protected void setValue(Object element, Object value) {
517             if (!(element instanceof AttributeElement)) {
518                 return;
519             }
520
521             ResourceManager resourceManager = Activator.getDefault()
522                     .getResourceManager();
523             // As automation depends on the current resource in selection, its
524             // presence is being checked.
525             Resource resource = resourceManager.getCurrentResourceInSelection();
526             if (null == resource) {
527                 return;
528             }
529
530             AttributeElement att = (AttributeElement) element;
531             boolean checked = (Boolean) value;
532             if (checked) {
533                 // Start the automation
534                 // Fetch the settings data
535                 List<AutomationSettingHelper> automationSettings;
536                 automationSettings = AutomationSettingHelper
537                         .getAutomationSettings(att);
538
539                 // Open the settings dialog
540                 AutomationSettingDialog dialog = new AutomationSettingDialog(
541                         viewer.getTree().getShell(), automationSettings);
542                 dialog.create();
543                 if (dialog.open() == Window.OK) {
544                     String automationType = dialog.getAutomationType();
545                     String updateFreq = dialog.getUpdateFrequency();
546
547                     AutoUpdateType autoType = AutoUpdateType
548                             .valueOf(automationType);
549                     int updFreq = Utility
550                             .getUpdateIntervalFromString(updateFreq);
551                     int autoId = resourceManager.startAutomation(
552                             (SingleResource) resource, att, autoType, updFreq);
553                     if (autoId == -1) {
554                         MessageDialog.openInformation(Display.getDefault()
555                                 .getActiveShell(), "Automation Status",
556                                 "Automation start failed!!");
557                     }
558                 }
559             } else {
560                 // Stop the automation
561                 resourceManager.stopAutomation((SingleResource) resource, att,
562                         att.getAutoUpdateId());
563             }
564         }
565     }
566 }