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 POST request.
86 public class PostRequestDialog 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",
101 private final Integer[] attTblColWidth = { 200, 200, 50 };
103 public PostRequestDialog(Shell parentShell) {
108 public void create() {
110 setTitle("Generate POST Request");
111 setMessage("Dialog which takes input and generates a post request.");
115 protected Control createDialogArea(Composite parent) {
116 Composite compLayout = (Composite) super.createDialogArea(parent);
118 Composite rootContainer = new Composite(compLayout, SWT.NONE);
119 GridLayout layout = new GridLayout();
120 rootContainer.setLayout(layout);
121 GridData gd = new GridData(SWT.FILL, SWT.FILL, true, true);
122 rootContainer.setLayoutData(gd);
124 Group paramsGrp = new Group(rootContainer, SWT.NONE);
126 gd.horizontalAlignment = SWT.FILL;
127 gd.grabExcessHorizontalSpace = true;
128 gd.minimumHeight = 50;
129 paramsGrp.setLayoutData(gd);
130 layout = new GridLayout(2, false);
131 layout.verticalSpacing = 10;
132 layout.marginTop = 10;
133 paramsGrp.setLayout(layout);
135 Label ifTypeLbl = new Label(paramsGrp, SWT.NONE);
136 ifTypeLbl.setText("Interface Type");
138 ifTypesCmb = new Combo(paramsGrp, SWT.NULL);
140 gd.grabExcessHorizontalSpace = true;
141 gd.horizontalAlignment = SWT.FILL;
142 ifTypesCmb.setLayoutData(gd);
143 ifTypesCmb.addModifyListener(new ModifyListener() {
145 public void modifyText(ModifyEvent e) {
146 ifType = ifTypesCmb.getText();
150 RemoteResource resource = Activator.getDefault().getResourceManager()
151 .getCurrentResourceInSelection();
153 // Set the interface types in combo box.
154 Map<String, String> ifTypes = Utility.getResourceInterfaces();
155 this.ifTypes = new HashMap<String, String>();
157 for (Map.Entry<String, String> entry : ifTypes.entrySet()) {
158 key = entry.getValue() + " (" + entry.getKey() + ")";
159 this.ifTypes.put(key, entry.getKey());
163 // Select the default value to be shown in the interface types combo.
164 Vector<String> ifTypesSupportedByResource = resource
165 .getRemoteResourceRef().getResourceInterfaces();
166 if (null != ifTypesSupportedByResource) {
168 if (ifTypesSupportedByResource
169 .contains(Constants.BASELINE_INTERFACE)
170 && ifTypes.containsKey(Constants.BASELINE_INTERFACE)) {
171 // Baseline interface is given preference to be shown in the if
173 String value = ifTypes.get(Constants.BASELINE_INTERFACE);
174 index = ifTypesCmb.indexOf(value + " ("
175 + Constants.BASELINE_INTERFACE + ")");
177 ifTypesCmb.select(index);
180 // Baseline interface is not selected so selecting some other
181 // interface supported by the resource.
182 Iterator<String> itr = ifTypesSupportedByResource.iterator();
183 while (itr.hasNext() && index == -1) {
185 if (ifTypes.containsKey(key)) {
186 String value = ifTypes.get(key);
187 index = ifTypesCmb.indexOf(value + " (" + key + ")");
189 ifTypesCmb.select(index);
194 if (index == -1 && !ifTypesSupportedByResource.isEmpty()) {
195 // Resource has custom interfaces.
196 ifTypesCmb.setText(ifTypesSupportedByResource.get(0));
201 Composite container = new Composite(rootContainer, SWT.NONE);
202 container.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
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
211 // for POST requests.
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 tree.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
274 tree.setHeaderVisible(true);
275 tree.setLinesVisible(true);
277 attViewer.setContentProvider(new AttributeContentProvider());
278 attViewer.setLabelProvider(new AttributeLabelProvider());
281 public void createAttributeColumns(TreeViewer viewer) {
282 Tree tree = viewer.getTree();
284 attributeEditor = new AttributeEditingSupport();
286 TreeColumn attName = new TreeColumn(tree, SWT.NONE);
287 attName.setWidth(attTblColWidth[0]);
288 attName.setText(attTblHeaders[0]);
290 TreeColumn attValue = new TreeColumn(tree, SWT.NONE);
291 attValue.setWidth(attTblColWidth[1]);
292 attValue.setText(attTblHeaders[1]);
293 TreeViewerColumn attValueVwrCol = new TreeViewerColumn(attViewer,
295 attValueVwrCol.setEditingSupport(attributeEditor
296 .createAttributeValueEditor(attViewer, this));
298 TreeColumn updateColumn = new TreeColumn(tree, SWT.NONE);
299 updateColumn.setWidth(attTblColWidth[2]);
300 updateColumn.setText(attTblHeaders[2]);
301 TreeViewerColumn updateVwrCol = new TreeViewerColumn(attViewer,
303 updateVwrCol.setEditingSupport(attributeEditor
304 .createPostSelectionEditor(attViewer));
309 private void addMenuItems() {
310 if (null != attViewer) {
311 final Tree resourceTreeHead = attViewer.getTree();
312 if (null != resourceTreeHead) {
313 // Below code creates menu entries and shows them on right
314 // clicking a resource
315 final Menu menu = new Menu(resourceTreeHead);
316 resourceTreeHead.setMenu(menu);
317 menu.addMenuListener(new MenuAdapter() {
319 public void menuShown(MenuEvent e) {
320 // Clear existing menu items
321 MenuItem[] items = menu.getItems();
322 for (int index = 0; index < items.length; index++) {
323 items[index].dispose();
326 IStructuredSelection selection = ((IStructuredSelection) attViewer
328 final AttributeElement attElement = (AttributeElement) selection
330 if (null == attElement) {
334 // Check the type of attribute.
335 SimulatorResourceAttribute attribute = attElement
336 .getSimulatorResourceAttribute();
337 if (null == attribute) {
341 AttributeValue value = attribute.value();
342 if (null == value || null == value.get()) {
346 TypeInfo type = value.typeInfo();
348 final Object parent = attElement.getParent();
350 if ((type.mType == ValueType.ARRAY
351 && type.mBaseType == ValueType.RESOURCEMODEL && type.mDepth == 1)
352 && (null == parent || parent instanceof ResourceRepresentation)) {
353 addMenuToOneDimensionalTopLevelModelAttributes(menu);
358 && parent instanceof AttributeElement) {
359 Object grandParent = ((AttributeElement) parent)
361 if (null == grandParent
362 || grandParent instanceof ResourceRepresentation) {
363 AttributeElement parentElement = (AttributeElement) parent;
365 // Check the type of attribute.
366 SimulatorResourceAttribute parentAttribute = parentElement
367 .getSimulatorResourceAttribute();
368 if (null != parentAttribute
369 && null != parentAttribute.value()
370 && null != parentAttribute.value()
372 AttributeValue parentValue = parentAttribute
375 TypeInfo parentType = parentValue
377 if (parentType.mType == ValueType.ARRAY
378 && parentType.mBaseType == ValueType.RESOURCEMODEL
379 && parentType.mDepth == 1) {
380 addDeleteMenuToArrayItemsOfOneDimensionalModelAttribute(
381 menu, attElement, parentElement);
393 private void addMenuToOneDimensionalTopLevelModelAttributes(Menu menu) {
394 // Menu to add items to the array.
395 MenuItem addItems = new MenuItem(menu, SWT.NONE);
396 addItems.setText("Add Items");
397 addItems.addSelectionListener(new SelectionAdapter() {
399 public void widgetSelected(SelectionEvent e) {
400 // Get the attributes.
401 ResourceRepresentation representation;
402 representation = getRepresentationForOneDimensionTopLevelAttribute();
403 if (null == representation) {
405 .openError(Display.getDefault().getActiveShell(),
406 "Unable to perform the operation.",
407 "Failed to obtain the required data. Operation cannot be performed.");
409 ModelArrayAddItemDialog dialog = new ModelArrayAddItemDialog(
410 Display.getDefault().getActiveShell(),
411 PostRequestDialog.this, representation);
412 if (Window.OK == dialog.open()) {
413 // Add the new item to the local resource
415 AttributeElement newElement = (AttributeElement) representation
416 .getAttributes().values().toArray()[0];
417 SimulatorResourceAttribute newAttribute = newElement
418 .getSimulatorResourceAttribute();
419 SimulatorResourceModel newModel = (SimulatorResourceModel) newAttribute
422 AttributeElement attElement = getSelectedElement();
423 if (null == attElement) {
425 .openError(Display.getDefault()
427 "Unable to perform the operation.",
428 "Failed to obtain the required data. Operation cannot be performed.");
432 SimulatorResourceAttribute attribute = attElement
433 .getSimulatorResourceAttribute();
434 SimulatorResourceModel[] modelArray = (SimulatorResourceModel[]) attribute
436 SimulatorResourceModel[] newModelArray = new SimulatorResourceModel[modelArray.length + 1];
439 for (i = 0; i < modelArray.length; i++) {
440 newModelArray[i] = modelArray[i];
442 newModelArray[i] = newModel;
444 AttributeValue newValue = new AttributeValue(
447 newAttribute.setValue(newValue);
449 newAttribute.setProperty(attribute.property());
451 attribute.setValue(newValue);
453 attElement.update(newAttribute);
455 attElement.setPostState(true);
457 attViewer.refresh(attElement);
459 attViewer.expandAll();
466 private void addDeleteMenuToArrayItemsOfOneDimensionalModelAttribute(
467 final Menu menu, final AttributeElement elementToDelete,
468 final AttributeElement parentElement) {
469 // Menu to add items to the array.
470 MenuItem addItems = new MenuItem(menu, SWT.NONE);
471 addItems.setText("Delete Item");
472 addItems.addSelectionListener(new SelectionAdapter() {
474 public void widgetSelected(SelectionEvent e) {
475 MessageBox dialog = new MessageBox(menu.getShell(),
476 SWT.ICON_QUESTION | SWT.OK | SWT.CANCEL);
477 dialog.setText("Confirm action");
478 dialog.setMessage("Do you want to delete this item from the array?");
479 int retval = dialog.open();
480 if (retval != SWT.OK) {
484 // Removing the element from the attribute value.
485 SimulatorResourceAttribute parentSRA = parentElement
486 .getSimulatorResourceAttribute();
487 AttributeValue value = parentSRA.value();
488 SimulatorResourceModel[] modelArray = (SimulatorResourceModel[]) value
491 String elementIndexName = elementToDelete
492 .getSimulatorResourceAttribute().name();
493 int elementIndex = Integer.parseInt(elementIndexName.substring(
494 elementIndexName.indexOf('[') + 1,
495 elementIndexName.indexOf(']')));
497 SimulatorResourceModel[] newModelArray = new SimulatorResourceModel[modelArray.length - 1];
498 int sIndex = 0, dIndex = 0;
499 for (SimulatorResourceModel model : modelArray) {
500 if (sIndex != elementIndex)
501 newModelArray[dIndex++] = model;
505 // Setting the new model array in the attribute.
506 AttributeValue newValue = new AttributeValue(newModelArray);
507 parentSRA.setValue(newValue);
509 // Removing the element from the child map.
510 Map<String, AttributeElement> elements = parentElement
512 if (null == elements) {
514 .openError(Display.getDefault().getActiveShell(),
516 "There is an error while removing the array items.");
520 List<AttributeElement> attElementList = new ArrayList<AttributeElement>();
521 attElementList.addAll(elements.values());
522 Collections.sort(attElementList, Utility.attributeComparator);
524 // Renaming the index of the elements.
525 AttributeElement[] attElementArray = attElementList
526 .toArray(new AttributeElement[0]);
527 boolean deleted = false;
529 for (index = 0, newIndex = 0; index < attElementArray.length; index++) {
530 if (index == elementIndex) {
531 elements.remove(elementIndexName);
535 AttributeElement element = attElementArray[index];
536 String curIndexStr = "[" + index + "]";
537 String newIndexStr = "[" + newIndex + "]";
539 element.getSimulatorResourceAttribute().setName(
542 elements.remove(curIndexStr);
543 elements.put(newIndexStr, element);
549 parentElement.setPostState(true);
551 attViewer.refresh(parentElement);
556 private ResourceRepresentation getRepresentationForOneDimensionTopLevelAttribute() {
557 ResourceRepresentation representation;
559 AttributeValue value;
560 ModelProperty property = null;
562 AttributeElement element = getSelectedElement();
566 SimulatorResourceAttribute modelArrayAtt = element
567 .getSimulatorResourceAttribute();
568 if (null == modelArrayAtt) {
572 AttributeValue attValue = modelArrayAtt.value();
573 if (null == attValue) {
577 TypeInfo type = attValue.typeInfo();
579 if (!(type.mType == ValueType.ARRAY
580 && type.mBaseType == ValueType.RESOURCEMODEL && type.mDepth == 1)) {
584 SimulatorResourceModel[] modelValue = (SimulatorResourceModel[]) attValue
586 if (null == modelValue || modelValue.length < 0) {
590 // Clone an instance of model value.
592 value = Utility.cloneAttributeValue(new AttributeValue(
594 } catch (Exception e) {
602 // Get the model property of the model value instance.
603 AttributeProperty attProperty = modelArrayAtt.property();
604 if (null != attProperty && attProperty instanceof ArrayProperty) {
605 ArrayProperty prop = attProperty.asArray();
607 AttributeProperty elementProperty = prop.getElementProperty();
608 if (null != elementProperty && elementProperty.isModel()) {
609 property = elementProperty.asModel();
614 SimulatorResourceAttribute attribute = new SimulatorResourceAttribute(
615 modelArrayAtt.name(), value, property);
616 Map<String, SimulatorResourceAttribute> attributes = new HashMap<String, SimulatorResourceAttribute>();
617 attributes.put(modelArrayAtt.name(), attribute);
618 representation = new ResourceRepresentation(attributes, false);
620 return representation;
623 private AttributeElement getSelectedElement() {
624 IStructuredSelection selection = (IStructuredSelection) attViewer
626 if (null == selection) {
630 Object obj = selection.getFirstElement();
635 Tree t = attViewer.getTree();
636 TreeItem item = t.getSelection()[0];
641 if (!(item.getData() instanceof AttributeElement)) {
645 return (AttributeElement) item.getData();
648 private static class AttributeContentProvider implements
649 ITreeContentProvider {
652 public void dispose() {
656 public void inputChanged(Viewer viewer, Object oldAttribute,
657 Object newAttribute) {
661 public Object[] getChildren(Object attribute) {
662 if (attribute instanceof AttributeElement) {
663 List<AttributeElement> attElementList = new ArrayList<AttributeElement>();
664 Map<String, AttributeElement> children = ((AttributeElement) attribute)
666 if (null != children) {
667 attElementList.addAll(children.values());
668 Collections.sort(attElementList,
669 Utility.attributeComparator);
670 return attElementList.toArray();
674 return new Object[0];
678 public Object getParent(Object attribute) {
679 if (attribute instanceof AttributeElement)
680 return ((AttributeElement) attribute).getParent();
685 public boolean hasChildren(Object attribute) {
686 if (attribute instanceof AttributeElement)
687 return ((AttributeElement) attribute).hasChildren();
692 public Object[] getElements(Object resourceModel) {
693 if (resourceModel instanceof ResourceRepresentation) {
694 return ((ResourceRepresentation) resourceModel).getAttributes()
698 return new Object[0];
702 private static class AttributeLabelProvider implements ITableLabelProvider {
705 public void addListener(ILabelProviderListener arg0) {
709 public void dispose() {
713 public boolean isLabelProperty(Object arg0, String arg1) {
718 public void removeListener(ILabelProviderListener arg0) {
723 public Image getColumnImage(Object element, int col) {
725 if (element instanceof AttributeElement) {
727 AttributeElement attrElement = (AttributeElement) element;
728 Object parent = attrElement.getParent();
730 || parent instanceof ResourceRepresentation) {
731 if (attrElement.getPostState()) {
732 return Activator.getDefault().getImageRegistry()
733 .get(Constants.CHECKED);
735 return Activator.getDefault().getImageRegistry()
736 .get(Constants.UNCHECKED);
746 public String getColumnText(Object element, int column) {
747 if (element instanceof AttributeElement) {
748 AttributeElement attrElement = (AttributeElement) element;
750 case 0: // Attribute name column
752 SimulatorResourceAttribute attribute = attrElement
753 .getSimulatorResourceAttribute();
754 return attribute.name();
757 case 1: // Attribute value column
759 SimulatorResourceAttribute attribute = attrElement
760 .getSimulatorResourceAttribute();
762 if (attribute.value().typeInfo().mBaseType != ValueType.RESOURCEMODEL) {
763 String value = Utility
764 .getAttributeValueAsString(attribute
784 protected boolean isResizable() {
789 public boolean isHelpAvailable() {
794 protected Button createButton(Composite parent, int id, String label,
795 boolean defaultButton) {
796 if (id == IDialogConstants.OK_ID) {
799 return super.createButton(parent, id, label, defaultButton);
802 public ResourceRepresentation getUpdatedRepresentation() {
803 return updatedRepresentation;
806 public String getIfType() {
807 if (ifTypes.containsKey(ifType)) {
808 return ifTypes.get(ifType);