2 * Copyright 2015 Samsung Electronics All Rights Reserved.
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
17 package oic.simulator.clientcontroller.view.dialogs;
19 import org.eclipse.jface.dialogs.IDialogConstants;
20 import org.eclipse.jface.dialogs.MessageDialog;
21 import org.eclipse.jface.dialogs.TitleAreaDialog;
22 import org.eclipse.jface.viewers.ILabelProviderListener;
23 import org.eclipse.jface.viewers.IStructuredSelection;
24 import org.eclipse.jface.viewers.ITableLabelProvider;
25 import org.eclipse.jface.viewers.ITreeContentProvider;
26 import org.eclipse.jface.viewers.TreeViewer;
27 import org.eclipse.jface.viewers.TreeViewerColumn;
28 import org.eclipse.jface.viewers.Viewer;
29 import org.eclipse.jface.window.Window;
30 import org.eclipse.swt.SWT;
31 import org.eclipse.swt.events.MenuAdapter;
32 import org.eclipse.swt.events.MenuEvent;
33 import org.eclipse.swt.events.ModifyEvent;
34 import org.eclipse.swt.events.ModifyListener;
35 import org.eclipse.swt.events.SelectionAdapter;
36 import org.eclipse.swt.events.SelectionEvent;
37 import org.eclipse.swt.graphics.Image;
38 import org.eclipse.swt.layout.GridData;
39 import org.eclipse.swt.layout.GridLayout;
40 import org.eclipse.swt.widgets.Button;
41 import org.eclipse.swt.widgets.Combo;
42 import org.eclipse.swt.widgets.Composite;
43 import org.eclipse.swt.widgets.Control;
44 import org.eclipse.swt.widgets.Display;
45 import org.eclipse.swt.widgets.Group;
46 import org.eclipse.swt.widgets.Label;
47 import org.eclipse.swt.widgets.Menu;
48 import org.eclipse.swt.widgets.MenuItem;
49 import org.eclipse.swt.widgets.MessageBox;
50 import org.eclipse.swt.widgets.Shell;
51 import org.eclipse.swt.widgets.Tree;
52 import org.eclipse.swt.widgets.TreeColumn;
53 import org.eclipse.swt.widgets.TreeItem;
55 import java.util.ArrayList;
56 import java.util.Collections;
57 import java.util.Date;
58 import java.util.HashMap;
59 import java.util.Iterator;
60 import java.util.List;
62 import java.util.Vector;
64 import org.oic.simulator.ArrayProperty;
65 import org.oic.simulator.AttributeProperty;
66 import org.oic.simulator.AttributeValue;
67 import org.oic.simulator.AttributeValue.TypeInfo;
68 import org.oic.simulator.AttributeValue.ValueType;
69 import org.oic.simulator.ILogger.Level;
70 import org.oic.simulator.ModelProperty;
71 import org.oic.simulator.SimulatorResourceAttribute;
72 import org.oic.simulator.SimulatorResourceModel;
73 import org.oic.simulator.client.SimulatorRemoteResource.RequestType;
75 import oic.simulator.clientcontroller.Activator;
76 import oic.simulator.clientcontroller.remoteresource.AttributeElement;
77 import oic.simulator.clientcontroller.remoteresource.RemoteResource;
78 import oic.simulator.clientcontroller.remoteresource.ResourceRepresentation;
79 import oic.simulator.clientcontroller.utils.Constants;
80 import oic.simulator.clientcontroller.utils.Utility;
81 import oic.simulator.clientcontroller.view.AttributeEditingSupport;
84 * This dialog is used for generating a PUT request.
86 public class PutRequestDialog extends TitleAreaDialog {
88 private TreeViewer attViewer;
89 private Combo ifTypesCmb;
91 private String ifType;
93 private Map<String, String> ifTypes;
95 private AttributeEditingSupport attributeEditor;
97 private ResourceRepresentation updatedRepresentation;
99 private final String[] attTblHeaders = { "Name", "Value" };
100 private final Integer[] attTblColWidth = { 200, 200 };
102 public PutRequestDialog(Shell parentShell) {
107 public void create() {
109 setTitle("Generate PUT Request");
110 setMessage("Dialog which takes input and generates a put request.");
114 protected Control createDialogArea(Composite parent) {
115 Composite compLayout = (Composite) super.createDialogArea(parent);
117 Composite rootContainer = new Composite(compLayout, SWT.NONE);
118 GridLayout layout = new GridLayout();
119 rootContainer.setLayout(layout);
120 GridData gd = new GridData(SWT.FILL, SWT.FILL, true, true);
121 rootContainer.setLayoutData(gd);
123 Group paramsGrp = new Group(rootContainer, SWT.NONE);
125 gd.horizontalAlignment = SWT.FILL;
126 gd.grabExcessHorizontalSpace = true;
127 gd.minimumHeight = 50;
128 paramsGrp.setLayoutData(gd);
129 layout = new GridLayout(2, false);
130 layout.verticalSpacing = 10;
131 layout.marginTop = 10;
132 paramsGrp.setLayout(layout);
134 Label ifTypeLbl = new Label(paramsGrp, SWT.NONE);
135 ifTypeLbl.setText("Interface Type");
137 ifTypesCmb = new Combo(paramsGrp, SWT.NULL);
139 gd.grabExcessHorizontalSpace = true;
140 gd.horizontalAlignment = SWT.FILL;
141 ifTypesCmb.setLayoutData(gd);
142 ifTypesCmb.addModifyListener(new ModifyListener() {
144 public void modifyText(ModifyEvent e) {
145 ifType = ifTypesCmb.getText();
149 RemoteResource resource = Activator.getDefault().getResourceManager()
150 .getCurrentResourceInSelection();
152 // Set the interface types in combo box.
153 Map<String, String> ifTypes = Utility.getResourceInterfaces();
154 this.ifTypes = new HashMap<String, String>();
156 for (Map.Entry<String, String> entry : ifTypes.entrySet()) {
157 key = entry.getValue() + " (" + entry.getKey() + ")";
158 this.ifTypes.put(key, entry.getKey());
162 // Select the default value to be shown in the interface types combo.
163 Vector<String> ifTypesSupportedByResource = resource
164 .getRemoteResourceRef().getResourceInterfaces();
165 if (null != ifTypesSupportedByResource) {
167 if (ifTypesSupportedByResource
168 .contains(Constants.BASELINE_INTERFACE)
169 && ifTypes.containsKey(Constants.BASELINE_INTERFACE)) {
170 // Baseline interface is given preference to be shown in the if
172 String value = ifTypes.get(Constants.BASELINE_INTERFACE);
173 index = ifTypesCmb.indexOf(value + " ("
174 + Constants.BASELINE_INTERFACE + ")");
176 ifTypesCmb.select(index);
179 // Baseline interface is not selected so selecting some other
180 // interface supported by the resource.
181 Iterator<String> itr = ifTypesSupportedByResource.iterator();
182 while (itr.hasNext() && index == -1) {
184 if (ifTypes.containsKey(key)) {
185 String value = ifTypes.get(key);
186 index = ifTypesCmb.indexOf(value + " (" + key + ")");
188 ifTypesCmb.select(index);
193 if (index == -1 && !ifTypesSupportedByResource.isEmpty()) {
194 // Resource has custom interfaces.
195 ifTypesCmb.setText(ifTypesSupportedByResource.get(0));
200 Composite container = new Composite(rootContainer, SWT.NONE);
201 gd = new GridData(SWT.FILL, SWT.FILL, true, true);
202 container.setLayoutData(gd);
203 layout = new GridLayout(1, false);
204 layout.verticalSpacing = 10;
205 layout.marginTop = 10;
206 container.setLayout(layout);
208 createTreeViewer(container);
210 // Clone the resource model for maintaining a local copy of attributes
212 SimulatorResourceModel resourceModel = null;
214 AttributeValue attValue = Utility
215 .cloneAttributeValue(new AttributeValue(resource
216 .getResourceModelRef()));
217 if (null != attValue)
218 resourceModel = (SimulatorResourceModel) attValue.get();
219 } catch (Exception e) {
223 .log(Level.ERROR.ordinal(),
225 "There is an error while forming an instance of the attribute value.\n"
226 + Utility.getSimulatorErrorString(e, null));
229 if (null == resourceModel) {
230 // Failed to clone. So taking the base copy and continuing the
232 resourceModel = resource.getResourceModelRef();
235 updatedRepresentation = new ResourceRepresentation(resourceModel);
237 if (resource.isConfigUploaded()) {
239 // Request Type needs to be changed to PUT.
240 updatedRepresentation.updateAttributeProperties(resource
241 .getRequestModels().get(RequestType.POST),
243 } catch (Exception e) {
247 .log(Level.ERROR.ordinal(),
249 "There is an error while forming an instance of the attribute value.\n"
250 + Utility.getSimulatorErrorString(e,
255 attViewer.setInput(updatedRepresentation);
257 attViewer.expandAll();
262 private void createTreeViewer(Composite parent) {
263 Tree addressTree = new Tree(parent, SWT.SINGLE | SWT.BORDER
264 | SWT.H_SCROLL | SWT.V_SCROLL | SWT.FULL_SELECTION);
265 addressTree.setHeaderVisible(true);
267 attViewer = new TreeViewer(addressTree);
269 createAttributeColumns(attViewer);
271 // make lines and header visible
272 Tree tree = attViewer.getTree();
273 GridData gd = new GridData(SWT.FILL, SWT.FILL, true, true);
274 tree.setLayoutData(gd);
275 tree.setHeaderVisible(true);
276 tree.setLinesVisible(true);
278 attViewer.setContentProvider(new AttributeContentProvider());
279 attViewer.setLabelProvider(new AttributeLabelProvider());
282 public void createAttributeColumns(TreeViewer viewer) {
283 Tree tree = viewer.getTree();
285 attributeEditor = new AttributeEditingSupport();
287 TreeColumn attName = new TreeColumn(tree, SWT.NONE);
288 attName.setWidth(attTblColWidth[0]);
289 attName.setText(attTblHeaders[0]);
291 TreeColumn attValue = new TreeColumn(tree, SWT.NONE);
292 attValue.setWidth(attTblColWidth[1]);
293 attValue.setText(attTblHeaders[1]);
294 TreeViewerColumn attValueVwrCol = new TreeViewerColumn(attViewer,
296 attValueVwrCol.setEditingSupport(attributeEditor
297 .createAttributeValueEditor(attViewer, this));
302 private void addMenuItems() {
303 if (null != attViewer) {
304 final Tree resourceTreeHead = attViewer.getTree();
305 if (null != resourceTreeHead) {
306 // Below code creates menu entries and shows them on right
307 // clicking a resource
308 final Menu menu = new Menu(resourceTreeHead);
309 resourceTreeHead.setMenu(menu);
310 menu.addMenuListener(new MenuAdapter() {
312 public void menuShown(MenuEvent e) {
313 // Clear existing menu items
314 MenuItem[] items = menu.getItems();
315 for (int index = 0; index < items.length; index++) {
316 items[index].dispose();
319 IStructuredSelection selection = ((IStructuredSelection) attViewer
321 final AttributeElement attElement = (AttributeElement) selection
323 if (null == attElement) {
327 // Check the type of attribute.
328 SimulatorResourceAttribute attribute = attElement
329 .getSimulatorResourceAttribute();
330 if (null == attribute) {
334 AttributeValue value = attribute.value();
335 if (null == value || null == value.get()) {
339 TypeInfo type = value.typeInfo();
341 final Object parent = attElement.getParent();
343 if ((type.mType == ValueType.ARRAY
344 && type.mBaseType == ValueType.RESOURCEMODEL && type.mDepth == 1)
345 && (null == parent || parent instanceof ResourceRepresentation)) {
346 addMenuToOneDimensionalTopLevelModelAttributes(menu);
351 && parent instanceof AttributeElement) {
352 Object grandParent = ((AttributeElement) parent)
354 if (null == grandParent
355 || grandParent instanceof ResourceRepresentation) {
356 AttributeElement parentElement = (AttributeElement) parent;
358 // Check the type of attribute.
359 SimulatorResourceAttribute parentAttribute = parentElement
360 .getSimulatorResourceAttribute();
361 if (null != parentAttribute
362 && null != parentAttribute.value()
363 && null != parentAttribute.value()
365 AttributeValue parentValue = parentAttribute
368 TypeInfo parentType = parentValue
370 if (parentType.mType == ValueType.ARRAY
371 && parentType.mBaseType == ValueType.RESOURCEMODEL
372 && parentType.mDepth == 1) {
373 addDeleteMenuToArrayItemsOfOneDimensionalModelAttribute(
374 menu, attElement, parentElement);
386 private void addMenuToOneDimensionalTopLevelModelAttributes(Menu menu) {
387 // Menu to add items to the array.
388 MenuItem addItems = new MenuItem(menu, SWT.NONE);
389 addItems.setText("Add Items");
390 addItems.addSelectionListener(new SelectionAdapter() {
392 public void widgetSelected(SelectionEvent e) {
393 // Get the attributes.
394 ResourceRepresentation representation;
395 representation = getRepresentationForOneDimensionTopLevelAttribute();
396 if (null == representation) {
398 .openError(Display.getDefault().getActiveShell(),
399 "Unable to perform the operation.",
400 "Failed to obtain the required data. Operation cannot be performed.");
402 ModelArrayAddItemDialog dialog = new ModelArrayAddItemDialog(
403 Display.getDefault().getActiveShell(),
404 PutRequestDialog.this, representation);
405 if (Window.OK == dialog.open()) {
406 // Add the new item to the local resource
408 AttributeElement newElement = (AttributeElement) representation
409 .getAttributes().values().toArray()[0];
410 SimulatorResourceAttribute newAttribute = newElement
411 .getSimulatorResourceAttribute();
412 SimulatorResourceModel newModel = (SimulatorResourceModel) newAttribute
415 AttributeElement attElement = getSelectedElement();
416 if (null == attElement) {
418 .openError(Display.getDefault()
420 "Unable to perform the operation.",
421 "Failed to obtain the required data. Operation cannot be performed.");
425 SimulatorResourceAttribute attribute = attElement
426 .getSimulatorResourceAttribute();
427 SimulatorResourceModel[] modelArray = (SimulatorResourceModel[]) attribute
429 SimulatorResourceModel[] newModelArray = new SimulatorResourceModel[modelArray.length + 1];
432 for (i = 0; i < modelArray.length; i++) {
433 newModelArray[i] = modelArray[i];
435 newModelArray[i] = newModel;
437 AttributeValue newValue = new AttributeValue(
440 newAttribute.setValue(newValue);
442 newAttribute.setProperty(attribute.property());
444 attribute.setValue(newValue);
446 attElement.update(newAttribute);
448 attViewer.refresh(attElement);
450 attViewer.expandAll();
457 private void addDeleteMenuToArrayItemsOfOneDimensionalModelAttribute(
458 final Menu menu, final AttributeElement elementToDelete,
459 final AttributeElement parentElement) {
460 // Menu to add items to the array.
461 MenuItem addItems = new MenuItem(menu, SWT.NONE);
462 addItems.setText("Delete Item");
463 addItems.addSelectionListener(new SelectionAdapter() {
465 public void widgetSelected(SelectionEvent e) {
466 MessageBox dialog = new MessageBox(menu.getShell(),
467 SWT.ICON_QUESTION | SWT.OK | SWT.CANCEL);
468 dialog.setText("Confirm action");
469 dialog.setMessage("Do you want to delete this item from the array?");
470 int retval = dialog.open();
471 if (retval != SWT.OK) {
475 // Removing the element from the attribute value.
476 SimulatorResourceAttribute parentSRA = parentElement
477 .getSimulatorResourceAttribute();
478 AttributeValue value = parentSRA.value();
479 SimulatorResourceModel[] modelArray = (SimulatorResourceModel[]) value
482 String elementIndexName = elementToDelete
483 .getSimulatorResourceAttribute().name();
484 int elementIndex = Integer.parseInt(elementIndexName.substring(
485 elementIndexName.indexOf('[') + 1,
486 elementIndexName.indexOf(']')));
488 SimulatorResourceModel[] newModelArray = new SimulatorResourceModel[modelArray.length - 1];
489 int sIndex = 0, dIndex = 0;
490 for (SimulatorResourceModel model : modelArray) {
491 if (sIndex != elementIndex)
492 newModelArray[dIndex++] = model;
496 // Setting the new model array in the attribute.
497 AttributeValue newValue = new AttributeValue(newModelArray);
498 parentSRA.setValue(newValue);
500 // Removing the element from the child map.
501 Map<String, AttributeElement> elements = parentElement
503 if (null == elements) {
505 .openError(Display.getDefault().getActiveShell(),
507 "There is an error while removing the array items.");
511 List<AttributeElement> attElementList = new ArrayList<AttributeElement>();
512 attElementList.addAll(elements.values());
513 Collections.sort(attElementList, Utility.attributeComparator);
515 // Renaming the index of the elements.
516 AttributeElement[] attElementArray = attElementList
517 .toArray(new AttributeElement[0]);
518 boolean deleted = false;
520 for (index = 0, newIndex = 0; index < attElementArray.length; index++) {
521 if (index == elementIndex) {
522 elements.remove(elementIndexName);
526 AttributeElement element = attElementArray[index];
527 String curIndexStr = "[" + index + "]";
528 String newIndexStr = "[" + newIndex + "]";
530 element.getSimulatorResourceAttribute().setName(
533 elements.remove(curIndexStr);
534 elements.put(newIndexStr, element);
540 attViewer.refresh(parentElement);
545 private ResourceRepresentation getRepresentationForOneDimensionTopLevelAttribute() {
546 ResourceRepresentation representation;
548 AttributeValue value;
549 ModelProperty property = null;
551 AttributeElement element = getSelectedElement();
555 SimulatorResourceAttribute modelArrayAtt = element
556 .getSimulatorResourceAttribute();
557 if (null == modelArrayAtt) {
561 AttributeValue attValue = modelArrayAtt.value();
562 if (null == attValue) {
566 TypeInfo type = attValue.typeInfo();
568 if (!(type.mType == ValueType.ARRAY
569 && type.mBaseType == ValueType.RESOURCEMODEL && type.mDepth == 1)) {
573 SimulatorResourceModel[] modelValue = (SimulatorResourceModel[]) attValue
575 if (null == modelValue || modelValue.length < 0) {
579 // Clone an instance of model value.
581 value = Utility.cloneAttributeValue(new AttributeValue(
583 } catch (Exception e) {
591 // Get the model property of the model value instance.
592 AttributeProperty attProperty = modelArrayAtt.property();
593 if (null != attProperty && attProperty instanceof ArrayProperty) {
594 ArrayProperty prop = attProperty.asArray();
596 AttributeProperty elementProperty = prop.getElementProperty();
597 if (null != elementProperty && elementProperty.isModel()) {
598 property = elementProperty.asModel();
603 SimulatorResourceAttribute attribute = new SimulatorResourceAttribute(
604 modelArrayAtt.name(), value, property);
605 Map<String, SimulatorResourceAttribute> attributes = new HashMap<String, SimulatorResourceAttribute>();
606 attributes.put(modelArrayAtt.name(), attribute);
607 representation = new ResourceRepresentation(attributes, false);
609 return representation;
612 private AttributeElement getSelectedElement() {
613 IStructuredSelection selection = (IStructuredSelection) attViewer
615 if (null == selection) {
619 Object obj = selection.getFirstElement();
624 Tree t = attViewer.getTree();
625 TreeItem item = t.getSelection()[0];
630 if (!(item.getData() instanceof AttributeElement)) {
634 return (AttributeElement) item.getData();
637 private static class AttributeContentProvider implements
638 ITreeContentProvider {
641 public void dispose() {
645 public void inputChanged(Viewer viewer, Object oldAttribute,
646 Object newAttribute) {
650 public Object[] getChildren(Object attribute) {
651 if (attribute instanceof AttributeElement) {
652 List<AttributeElement> attElementList = new ArrayList<AttributeElement>();
653 Map<String, AttributeElement> children = ((AttributeElement) attribute)
655 if (null != children) {
656 attElementList.addAll(children.values());
657 Collections.sort(attElementList,
658 Utility.attributeComparator);
659 return attElementList.toArray();
663 return new Object[0];
667 public Object getParent(Object attribute) {
668 if (attribute instanceof AttributeElement)
669 return ((AttributeElement) attribute).getParent();
674 public boolean hasChildren(Object attribute) {
675 if (attribute instanceof AttributeElement)
676 return ((AttributeElement) attribute).hasChildren();
681 public Object[] getElements(Object resourceModel) {
682 if (resourceModel instanceof ResourceRepresentation) {
683 return ((ResourceRepresentation) resourceModel).getAttributes()
687 return new Object[0];
691 private static class AttributeLabelProvider implements ITableLabelProvider {
694 public void addListener(ILabelProviderListener arg0) {
698 public void dispose() {
702 public boolean isLabelProperty(Object arg0, String arg1) {
707 public void removeListener(ILabelProviderListener arg0) {
712 public Image getColumnImage(Object element, int col) {
717 public String getColumnText(Object element, int column) {
718 if (element instanceof AttributeElement) {
719 AttributeElement attrElement = (AttributeElement) element;
721 case 0: // Attribute name column
723 SimulatorResourceAttribute attribute = attrElement
724 .getSimulatorResourceAttribute();
725 return attribute.name();
728 case 1: // Attribute value column
730 SimulatorResourceAttribute attribute = attrElement
731 .getSimulatorResourceAttribute();
733 if (attribute.value().typeInfo().mBaseType != ValueType.RESOURCEMODEL) {
734 String value = Utility
735 .getAttributeValueAsString(attribute
751 protected boolean isResizable() {
756 public boolean isHelpAvailable() {
761 protected Button createButton(Composite parent, int id, String label,
762 boolean defaultButton) {
763 if (id == IDialogConstants.OK_ID) {
766 return super.createButton(parent, id, label, defaultButton);
769 public ResourceRepresentation getUpdatedRepresentation() {
770 return updatedRepresentation;
773 public String getIfType() {
774 if (ifTypes.containsKey(ifType)) {
775 return ifTypes.get(ifType);