Updated the order of imports in the source files of simulator plugins.
[platform/upstream/iotivity.git] / service / simulator / java / eclipse-plugin / ServiceProviderPlugin / src / oic / simulator / serviceprovider / view / MetaPropertiesView.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 org.eclipse.jface.dialogs.MessageDialog;
20 import org.eclipse.jface.viewers.CellEditor;
21 import org.eclipse.jface.viewers.EditingSupport;
22 import org.eclipse.jface.viewers.IStructuredContentProvider;
23 import org.eclipse.jface.viewers.StyledCellLabelProvider;
24 import org.eclipse.jface.viewers.TableViewer;
25 import org.eclipse.jface.viewers.TableViewerColumn;
26 import org.eclipse.jface.viewers.TextCellEditor;
27 import org.eclipse.jface.viewers.Viewer;
28 import org.eclipse.jface.viewers.ViewerCell;
29 import org.eclipse.jface.window.Window;
30 import org.eclipse.swt.SWT;
31 import org.eclipse.swt.events.ModifyEvent;
32 import org.eclipse.swt.events.ModifyListener;
33 import org.eclipse.swt.events.SelectionAdapter;
34 import org.eclipse.swt.events.SelectionEvent;
35 import org.eclipse.swt.layout.GridData;
36 import org.eclipse.swt.layout.GridLayout;
37 import org.eclipse.swt.widgets.Button;
38 import org.eclipse.swt.widgets.Composite;
39 import org.eclipse.swt.widgets.Display;
40 import org.eclipse.swt.widgets.Table;
41 import org.eclipse.swt.widgets.Text;
42 import org.eclipse.ui.part.ViewPart;
43
44 import java.util.HashMap;
45 import java.util.Iterator;
46 import java.util.List;
47 import java.util.Map;
48 import java.util.Set;
49
50 import org.oic.simulator.SimulatorException;
51
52 import oic.simulator.serviceprovider.Activator;
53 import oic.simulator.serviceprovider.listener.ISelectionChangedListener;
54 import oic.simulator.serviceprovider.manager.ResourceManager;
55 import oic.simulator.serviceprovider.manager.UiListenerHandler;
56 import oic.simulator.serviceprovider.model.MetaProperty;
57 import oic.simulator.serviceprovider.model.Resource;
58 import oic.simulator.serviceprovider.model.SingleResource;
59 import oic.simulator.serviceprovider.utils.Constants;
60 import oic.simulator.serviceprovider.utils.Utility;
61 import oic.simulator.serviceprovider.view.dialogs.UpdateResourceInterfaceDialog;
62
63 /**
64  * This class manages and shows the meta properties view in the perspective.
65  */
66 public class MetaPropertiesView extends ViewPart {
67
68     public static final String        VIEW_ID       = "oic.simulator.serviceprovider.view.metaproperties";
69
70     private TableViewer               tableViewer;
71
72     private final String[]            columnHeaders = { "Property", "Value" };
73
74     private final Integer[]           columnWidth   = { 150, 150 };
75
76     private ISelectionChangedListener resourceSelectionChangedListener;
77
78     private ResourceManager           resourceManagerRef;
79
80     private Set<String>               updatedIfSet;
81
82     private List<MetaProperty>        properties;
83
84     private boolean                   enable_edit;
85     private Button                    editBtn;
86     private Button                    cancelBtn;
87
88     private Map<String, String>       ifTypes;
89
90     public MetaPropertiesView() {
91
92         resourceManagerRef = Activator.getDefault().getResourceManager();
93
94         resourceSelectionChangedListener = new ISelectionChangedListener() {
95
96             @Override
97             public void onResourceSelectionChange(final Resource resource) {
98                 Display.getDefault().asyncExec(new Runnable() {
99
100                     @Override
101                     public void run() {
102                         if (null != tableViewer) {
103                             properties = getData(resource);
104                             updateViewer(properties);
105                         }
106                         updateEditControls(resource);
107                     }
108                 });
109             }
110         };
111     }
112
113     @Override
114     public void createPartControl(final Composite parent) {
115         parent.setLayout(new GridLayout(2, false));
116
117         tableViewer = new TableViewer(parent, SWT.SINGLE | SWT.H_SCROLL
118                 | SWT.V_SCROLL | SWT.FULL_SELECTION | SWT.BORDER);
119
120         createColumns(tableViewer);
121
122         // Make lines and header visible
123         final Table table = tableViewer.getTable();
124         GridData gd = new GridData(SWT.FILL, SWT.FILL, true, true);
125         gd.horizontalSpan = 2;
126         table.setLayoutData(gd);
127         table.setHeaderVisible(true);
128         table.setLinesVisible(true);
129
130         tableViewer.setContentProvider(new PropertycontentProvider());
131
132         editBtn = new Button(parent, SWT.PUSH);
133         editBtn.setText("Edit");
134         gd = new GridData();
135         gd.widthHint = 50;
136         editBtn.setLayoutData(gd);
137         editBtn.addSelectionListener(new SelectionAdapter() {
138             @Override
139             public void widgetSelected(SelectionEvent e) {
140                 if (editBtn.getText().equals("Edit")) {
141                     cancelBtn.setEnabled(true);
142                     editBtn.setText("Save");
143                     setEnableEdit(true);
144
145                     Resource resource = resourceManagerRef
146                             .getCurrentResourceInSelection();
147                     if (null != resource) {
148                         updatedIfSet = resource.getResourceInterfaces();
149                     }
150                 } else {
151                     boolean result = false;
152                     Resource resourceInSelection = resourceManagerRef
153                             .getCurrentResourceInSelection();
154                     if (null != resourceInSelection) {
155
156                         // Null Check
157                         result = resourceManagerRef.isPropertyValueInvalid(
158                                 resourceInSelection, properties,
159                                 Constants.RESOURCE_URI);
160                         if (result) {
161                             MessageDialog.openError(parent.getShell(),
162                                     "Invalid Resource URI.",
163                                     Constants.INVALID_URI_MESSAGE);
164                             return;
165                         }
166
167                         result = resourceManagerRef.isPropertyValueInvalid(
168                                 resourceInSelection, properties,
169                                 Constants.RESOURCE_NAME);
170                         if (result) {
171                             MessageDialog.openError(parent.getShell(),
172                                     "Invalid Input",
173                                     "Resource Name is invalid.");
174                             return;
175                         }
176
177                         boolean update = false;
178                         boolean uriChange = false;
179                         boolean nameChange = false;
180                         boolean interfaceChange = false;
181
182                         if (resourceManagerRef.isPropValueChanged(
183                                 resourceInSelection, properties,
184                                 Constants.RESOURCE_NAME)) {
185                             update = true;
186                             nameChange = true;
187                         }
188                         if (resourceManagerRef.isPropValueChanged(
189                                 resourceInSelection, properties,
190                                 Constants.RESOURCE_URI)) {
191                             // Check whether the new URI is unique.
192                             if (!resourceManagerRef.isUriUnique(properties)) {
193                                 MessageDialog.openError(parent.getShell(),
194                                         "Resource URI in use",
195                                         "Resource URI is in use. Please try a different URI.");
196                                 return;
197                             }
198
199                             if (resourceManagerRef
200                                     .isResourceStarted(resourceInSelection)) {
201                                 update = MessageDialog.openQuestion(
202                                         parent.getShell(), "Save Details",
203                                         "Resource will be restarted to take the changes."
204                                                 + " Do you want to continue?");
205                                 if (!update) {
206                                     return;
207                                 }
208                             }
209
210                             update = true;
211                             uriChange = true;
212                         }
213                         // Checking whether any changes made in resource
214                         // interfaces by
215                         // comparing the current interface set and updated
216                         // interface set.
217                         if (null != updatedIfSet) {
218                             Set<String> curIfSet = resourceInSelection
219                                     .getResourceInterfaces();
220                             if (curIfSet.size() != updatedIfSet.size()) {
221                                 update = true;
222                                 interfaceChange = true;
223                             } else {
224                                 Iterator<String> itr = updatedIfSet.iterator();
225                                 while (itr.hasNext()) {
226                                     if (!curIfSet.contains(itr.next())) {
227                                         update = true;
228                                         interfaceChange = true;
229                                         break;
230                                     }
231                                 }
232                             }
233                         }
234                         if (update) {
235                             try {
236                                 if (uriChange || nameChange)
237                                     result = Activator
238                                             .getDefault()
239                                             .getResourceManager()
240                                             .updateResourceProperties(
241                                                     resourceManagerRef
242                                                             .getCurrentResourceInSelection(),
243                                                     properties, uriChange,
244                                                     nameChange);
245                                 if (interfaceChange)
246                                     result = Activator
247                                             .getDefault()
248                                             .getResourceManager()
249                                             .updateResourceInterfaces(
250                                                     resourceInSelection,
251                                                     updatedIfSet);
252
253                             } catch (SimulatorException ex) {
254                                 result = false;
255                             }
256                             if (result) {
257                                 MessageDialog.openInformation(
258                                         parent.getShell(), "Operation status",
259                                         "Resource properties updated.");
260                             } else {
261                                 MessageDialog.openInformation(
262                                         parent.getShell(), "Operation status",
263                                         "Failed to update the resource properties.");
264
265                                 // Reset the old property values.
266                                 properties = getData(resourceManagerRef
267                                         .getCurrentResourceInSelection());
268                                 updateViewer(properties);
269                             }
270                         }
271                     }
272                     cancelBtn.setEnabled(false);
273                     editBtn.setText("Edit");
274                     setEnableEdit(false);
275                 }
276             }
277         });
278
279         cancelBtn = new Button(parent, SWT.PUSH);
280         cancelBtn.setText("Cancel");
281         cancelBtn.setEnabled(false);
282         gd = new GridData();
283         gd.widthHint = 70;
284         cancelBtn.setLayoutData(gd);
285         cancelBtn.addSelectionListener(new SelectionAdapter() {
286             @Override
287             public void widgetSelected(SelectionEvent e) {
288                 Resource res = resourceManagerRef
289                         .getCurrentResourceInSelection();
290                 if (null != res) {
291                     properties = getData(res);
292                 }
293                 updateViewer(properties);
294
295                 cancelBtn.setEnabled(false);
296                 editBtn.setText("Edit");
297                 setEnableEdit(false);
298                 if (null != updatedIfSet)
299                     updatedIfSet.clear();
300             }
301         });
302
303         // Get the supported interfaces.
304         Map<String, String> ifTypesSupported = Utility
305                 .getResourceInterfaces(SingleResource.class);
306         if (null != ifTypesSupported && !ifTypesSupported.isEmpty()) {
307             ifTypes = new HashMap<String, String>();
308             String key;
309             for (Map.Entry<String, String> entry : ifTypesSupported.entrySet()) {
310                 key = entry.getValue() + " (" + entry.getKey() + ")";
311                 ifTypes.put(key, entry.getKey());
312             }
313         }
314
315         addManagerListeners();
316
317         // Check whether there is any resource selected already
318         Resource resource = resourceManagerRef.getCurrentResourceInSelection();
319         properties = getData(resource);
320         if (null != properties) {
321             updateViewer(properties);
322         }
323         updateEditControls(resource);
324     }
325
326     private void updateEditControls(Object obj) {
327         if (!editBtn.isDisposed() && !cancelBtn.isDisposed()) {
328
329             if (editBtn.getText().equals("Save")) {
330                 editBtn.setText("Edit");
331                 setEnableEdit(false);
332             }
333
334             if (null == obj) {
335                 editBtn.setEnabled(false);
336             } else {
337                 editBtn.setEnabled(true);
338             }
339             cancelBtn.setEnabled(false);
340         }
341     }
342
343     private List<MetaProperty> getData(Resource resource) {
344         if (null != resource) {
345             List<MetaProperty> metaPropertyList = resourceManagerRef
346                     .getMetaProperties(resource);
347             return metaPropertyList;
348         } else {
349             return null;
350         }
351     }
352
353     private void updateViewer(List<MetaProperty> metaPropertyList) {
354         if (null != tableViewer) {
355             Table tbl = tableViewer.getTable();
356             if (tbl.isDisposed()) {
357                 return;
358             }
359             if (null != metaPropertyList) {
360                 tableViewer.setInput(metaPropertyList.toArray());
361                 tbl.setLinesVisible(true);
362             } else {
363                 tbl.removeAll();
364                 tbl.setLinesVisible(false);
365             }
366         }
367     }
368
369     public void createColumns(final TableViewer tableViewer) {
370         TableViewerColumn propName = new TableViewerColumn(tableViewer,
371                 SWT.NONE);
372         propName.getColumn().setWidth(columnWidth[0]);
373         propName.getColumn().setText(columnHeaders[0]);
374         propName.setLabelProvider(new StyledCellLabelProvider() {
375             @Override
376             public void update(ViewerCell cell) {
377                 MetaProperty prop = (MetaProperty) cell.getElement();
378                 cell.setText(prop.getPropName());
379                 super.update(cell);
380             }
381         });
382
383         TableViewerColumn propValue = new TableViewerColumn(tableViewer,
384                 SWT.NONE);
385         propValue.getColumn().setWidth(columnWidth[1]);
386         propValue.getColumn().setText(columnHeaders[1]);
387         propValue.setLabelProvider(new StyledCellLabelProvider() {
388             @Override
389             public void update(ViewerCell cell) {
390                 MetaProperty prop = (MetaProperty) cell.getElement();
391                 cell.setText(prop.getPropValue());
392                 super.update(cell);
393             }
394         });
395         propValue.setEditingSupport(new PropValueEditor(tableViewer));
396     }
397
398     private void addManagerListeners() {
399         UiListenerHandler.getInstance().addResourceSelectionChangedUIListener(
400                 resourceSelectionChangedListener);
401     }
402
403     class PropertycontentProvider implements IStructuredContentProvider {
404
405         @Override
406         public void dispose() {
407         }
408
409         @Override
410         public void inputChanged(Viewer arg0, Object arg1, Object arg2) {
411         }
412
413         @Override
414         public Object[] getElements(Object element) {
415             return (Object[]) element;
416         }
417     }
418
419     @Override
420     public void dispose() {
421         // Unregister the listener
422         if (null != resourceSelectionChangedListener) {
423             UiListenerHandler.getInstance()
424                     .removeResourceSelectionChangedUIListener(
425                             resourceSelectionChangedListener);
426         }
427         super.dispose();
428     }
429
430     class PropValueEditor extends EditingSupport {
431
432         private final TableViewer viewer;
433
434         public PropValueEditor(TableViewer viewer) {
435             super(viewer);
436             this.viewer = viewer;
437         }
438
439         @Override
440         protected boolean canEdit(Object element) {
441             return true;
442         }
443
444         @Override
445         protected CellEditor getCellEditor(final Object element) {
446             if (!getEnableEdit()) {
447                 return null;
448             }
449             // Disabling edit for resource type
450             String propName = ((MetaProperty) element).getPropName();
451             if (null != propName && propName.equals(Constants.RESOURCE_TYPE)) {
452                 return null;
453             }
454
455             CellEditor editor = new TextCellEditor(viewer.getTable());
456             if (null != propName && propName.equals(Constants.INTERFACE_TYPES)) {
457                 editor.setStyle(SWT.READ_ONLY);
458                 final Text txt = (Text) editor.getControl();
459                 txt.addModifyListener(new ModifyListener() {
460                     @Override
461                     public void modifyText(ModifyEvent e) {
462                         if (null == updatedIfSet) {
463                             return;
464                         }
465                         // Form the result set of interfaces with check-box that
466                         // will be shown in the dialog for editing.
467                         Map<String, String> curResInterfaces = new HashMap<String, String>();
468                         for (Map.Entry<String, String> entry : ifTypes
469                                 .entrySet()) {
470                             if (updatedIfSet.contains(entry.getValue())) {
471                                 curResInterfaces.put(entry.getKey(),
472                                         entry.getValue());
473                             }
474                         }
475
476                         // Show the dialog for editing the resource interfaces.
477                         UpdateResourceInterfaceDialog ad = new UpdateResourceInterfaceDialog(
478                                 Display.getDefault().getActiveShell(),
479                                 curResInterfaces, ifTypes);
480                         if (ad.open() == Window.OK) {
481                             // Update the local copy of the current resource
482                             // interfaces to keep the state for save operation.
483                             updatedIfSet.clear();
484                             String newPropValue = "";
485                             for (Map.Entry<String, String> entry : curResInterfaces
486                                     .entrySet()) {
487                                 if (!newPropValue.isEmpty()) {
488                                     newPropValue += ", ";
489                                 }
490                                 String value = ifTypes.get(entry.getKey());
491                                 newPropValue += value;
492
493                                 updatedIfSet.add(value);
494                             }
495                             // Update the model
496                             MetaProperty prop = (MetaProperty) element;
497                             prop.setPropValue(newPropValue);
498                             // Update the viewer in a separate UI thread.
499                             Display.getDefault().asyncExec(new Runnable() {
500                                 @Override
501                                 public void run() {
502                                     viewer.refresh(element, true);
503                                 }
504                             });
505                         }
506                     }
507                 });
508             }
509             return editor;
510         }
511
512         @Override
513         protected Object getValue(Object element) {
514             return ((MetaProperty) element).getPropValue();
515         }
516
517         @Override
518         protected void setValue(Object element, Object value) {
519             MetaProperty prop = (MetaProperty) element;
520             if (prop.getPropName().equals(Constants.INTERFACE_TYPES)) {
521                 return;
522             }
523             prop.setPropValue(String.valueOf(value));
524             viewer.update(element, null);
525         }
526     }
527
528     private synchronized Boolean getEnableEdit() {
529         return enable_edit;
530     }
531
532     private synchronized void setEnableEdit(boolean value) {
533         enable_edit = value;
534     }
535
536     @Override
537     public void setFocus() {
538     }
539 }