da3694dfb0fbf5a3745fce00cfdd4bfda57b93a6
[platform/upstream/iotivity.git] / service / simulator / java / eclipse-plugin / ServiceProviderPlugin / src / oic / simulator / serviceprovider / view / dialogs / LoadRamlPage.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.dialogs;
18
19 import java.io.FileInputStream;
20 import java.lang.reflect.InvocationTargetException;
21 import java.util.Date;
22
23 import oic.simulator.serviceprovider.Activator;
24 import oic.simulator.serviceprovider.model.Resource;
25 import oic.simulator.serviceprovider.model.SingleResource;
26 import oic.simulator.serviceprovider.utils.Constants;
27 import oic.simulator.serviceprovider.utils.Utility;
28 import oic.simulator.serviceprovider.view.dialogs.MainPage.Option;
29
30 import org.eclipse.core.runtime.IProgressMonitor;
31 import org.eclipse.jface.dialogs.MessageDialog;
32 import org.eclipse.jface.operation.IRunnableWithProgress;
33 import org.eclipse.jface.wizard.IWizardPage;
34 import org.eclipse.jface.wizard.WizardPage;
35 import org.eclipse.swt.SWT;
36 import org.eclipse.swt.events.KeyAdapter;
37 import org.eclipse.swt.events.KeyEvent;
38 import org.eclipse.swt.events.ModifyEvent;
39 import org.eclipse.swt.events.ModifyListener;
40 import org.eclipse.swt.events.SelectionAdapter;
41 import org.eclipse.swt.events.SelectionEvent;
42 import org.eclipse.swt.layout.GridData;
43 import org.eclipse.swt.layout.GridLayout;
44 import org.eclipse.swt.widgets.Button;
45 import org.eclipse.swt.widgets.Composite;
46 import org.eclipse.swt.widgets.Display;
47 import org.eclipse.swt.widgets.Event;
48 import org.eclipse.swt.widgets.FileDialog;
49 import org.eclipse.swt.widgets.Group;
50 import org.eclipse.swt.widgets.Label;
51 import org.eclipse.swt.widgets.Listener;
52 import org.eclipse.swt.widgets.Text;
53 import org.eclipse.ui.PlatformUI;
54 import org.oic.simulator.ILogger.Level;
55 import org.oic.simulator.SimulatorException;
56 import org.oic.simulator.server.SimulatorResource;
57 import org.oic.simulator.server.SimulatorResource.Type;
58
59 /**
60  * This class shows UI for creating resources.
61  */
62 public class LoadRamlPage extends WizardPage {
63
64     private Text                   locationTxt;
65     private Button                 btnBrowse;
66     private Text                   noOfInstancesText;
67     private Label                  noOfInstancesLbl;
68     private Label                  locationLbl;
69
70     private String                 configFilePath = null;
71     private int                    resourceCount;
72
73     private Resource               resource;
74
75     private SimulatorResource.Type typeOfResource;
76
77     protected LoadRamlPage() {
78         super("Create Resource");
79         resourceCount = -1;
80     }
81
82     public void initialSetup(SimulatorResource.Type type) {
83         this.typeOfResource = type;
84         if (!noOfInstancesLbl.isDisposed()) {
85             noOfInstancesLbl.setVisible(type == Type.SINGLE);
86         }
87         if (!noOfInstancesText.isDisposed()) {
88             noOfInstancesText.setVisible(type == Type.SINGLE);
89         }
90     }
91
92     @Override
93     public void createControl(Composite parent) {
94         setPageComplete(false);
95         setTitle(Constants.CREATE_PAGE_TITLE);
96         setMessage(Constants.CREATE_PAGE_MESSAGE);
97         Composite compContent = new Composite(parent, SWT.NONE);
98         GridLayout gridLayout = new GridLayout();
99         compContent.setLayout(gridLayout);
100         GridData gd = new GridData(SWT.FILL, SWT.FILL, true, true);
101         compContent.setLayoutData(gd);
102
103         Group configGroup = new Group(compContent, SWT.NONE);
104         gridLayout = new GridLayout(1, false);
105         gridLayout.verticalSpacing = 10;
106         gridLayout.marginTop = 5;
107         configGroup.setLayout(gridLayout);
108         gd = new GridData();
109         gd.horizontalAlignment = SWT.FILL;
110         gd.grabExcessHorizontalSpace = true;
111         configGroup.setLayoutData(gd);
112         configGroup.setText("Load RAML File");
113
114         Composite cusConfigComp = new Composite(configGroup, SWT.NONE);
115         cusConfigComp.setLayout(new GridLayout(3, false));
116         gd = new GridData();
117         gd.horizontalAlignment = SWT.FILL;
118         gd.grabExcessHorizontalSpace = true;
119         cusConfigComp.setLayoutData(gd);
120
121         locationLbl = new Label(cusConfigComp, SWT.NONE);
122         locationLbl.setText("Location:");
123
124         locationTxt = new Text(cusConfigComp, SWT.BORDER);
125         gd = new GridData();
126         gd.minimumWidth = 300;
127         gd.horizontalAlignment = SWT.FILL;
128         gd.grabExcessHorizontalSpace = true;
129         locationTxt.setLayoutData(gd);
130
131         btnBrowse = new Button(cusConfigComp, SWT.NONE);
132         btnBrowse.setText("Browse");
133         gd = new GridData();
134         gd.widthHint = 80;
135         gd.horizontalAlignment = SWT.FILL;
136         btnBrowse.setLayoutData(gd);
137         btnBrowse.setFocus();
138
139         Composite instanceComp = new Composite(compContent, SWT.NONE);
140         instanceComp.setLayout(new GridLayout(2, false));
141         gd = new GridData();
142         gd.horizontalAlignment = SWT.FILL;
143         gd.grabExcessHorizontalSpace = true;
144         instanceComp.setLayoutData(gd);
145
146         noOfInstancesLbl = new Label(instanceComp, SWT.NONE);
147         noOfInstancesLbl.setText("Number of Instances");
148
149         noOfInstancesText = new Text(instanceComp, SWT.BORDER);
150         gd = new GridData();
151         gd.widthHint = 50;
152         gd.horizontalAlignment = SWT.FILL;
153         noOfInstancesText.setLayoutData(gd);
154
155         // Adding the default value. It can be changed by the user.
156         noOfInstancesText.setText("1");
157
158         addUIListeners();
159
160         setControl(compContent);
161     }
162
163     private void addUIListeners() {
164         btnBrowse.addSelectionListener(new SelectionAdapter() {
165             @Override
166             public void widgetSelected(SelectionEvent e) {
167                 FileDialog fileDialog = new FileDialog(PlatformUI
168                         .getWorkbench().getDisplay().getActiveShell(), SWT.NONE);
169                 fileDialog
170                         .setFilterExtensions(Constants.BROWSE_RAML_FILTER_EXTENSIONS);
171                 String configFileAbsolutePath = fileDialog.open();
172                 if (null != configFileAbsolutePath)
173                     locationTxt.setText(configFileAbsolutePath);
174             }
175         });
176
177         locationTxt.addModifyListener(new ModifyListener() {
178             @Override
179             public void modifyText(ModifyEvent e) {
180                 configFilePath = locationTxt.getText();
181                 getWizard().getContainer().updateButtons();
182             }
183         });
184
185         noOfInstancesText.addListener(SWT.Verify, new Listener() {
186             @Override
187             public void handleEvent(Event e) {
188                 String string = e.text;
189                 char[] chars = new char[string.length()];
190                 string.getChars(0, chars.length, chars, 0);
191                 for (int i = 0; i < chars.length; i++) {
192                     if (!('0' <= chars[i] && chars[i] <= '9')) {
193                         e.doit = false;
194                         return;
195                     }
196                 }
197             }
198         });
199
200         noOfInstancesText.addKeyListener(new KeyAdapter() {
201             @Override
202             public void keyReleased(KeyEvent e) {
203                 getWizard().getContainer().updateButtons();
204             }
205         });
206     }
207
208     @Override
209     public boolean canFlipToNextPage() {
210         boolean done = false;
211         try {
212             resourceCount = Integer.parseInt(noOfInstancesText.getText());
213         } catch (Exception e) {
214             resourceCount = -1;
215         }
216         if (null != configFilePath && configFilePath.trim().length() > 0) {
217             if (resourceCount == 1) {
218                 done = true;
219             }
220         }
221         return done;
222     }
223
224     public boolean isSelectionDone() {
225         boolean done = false;
226         try {
227             resourceCount = Integer.parseInt(noOfInstancesText.getText());
228         } catch (Exception e) {
229             resourceCount = -1;
230         }
231         if (null != configFilePath && configFilePath.trim().length() > 0) {
232             if (resourceCount >= 1) {
233                 done = true;
234             }
235         }
236         return done;
237     }
238
239     public boolean isMultiResourceCreation() {
240         if (typeOfResource == Type.SINGLE && resourceCount > 1) {
241             return true;
242         }
243         return false;
244     }
245
246     @Override
247     public IWizardPage getNextPage() {
248         // Validate the file path.
249         try {
250             new FileInputStream(configFilePath);
251         } catch (Exception e) {
252             MessageDialog
253                     .openError(getShell(), "Invalid File",
254                             "File doesn't exist. Either the file path or file name is invalid.");
255             return null;
256         }
257
258         // Checking the resource count
259         if ((Activator.getDefault().getResourceManager().getResourceCount() + resourceCount) > Constants.MAX_RESOURCE_COUNT) {
260             MessageDialog
261                     .openInformation(Display.getDefault().getActiveShell(),
262                             "Resource limit exceeded",
263                             "Exceeded the limit of resources that can exist in the server.");
264             return null;
265         }
266
267         final CreateResourceWizard wizard = ((CreateResourceWizard) getWizard());
268
269         try {
270             getContainer().run(true, false, new IRunnableWithProgress() {
271                 @Override
272                 public void run(IProgressMonitor monitor)
273                         throws InvocationTargetException, InterruptedException {
274                     try {
275                         monitor.beginTask("Resource Creation With RAML", 2);
276                         monitor.worked(1);
277                         resource = Activator.getDefault().getResourceManager()
278                                 .createResourceByRAML(configFilePath);
279                         monitor.worked(1);
280                     } catch (SimulatorException e) {
281                         wizard.setStatus("Failed to create resource.\n"
282                                 + Utility.getSimulatorErrorString(e, null));
283                     } finally {
284                         monitor.done();
285                     }
286                 }
287             });
288         } catch (InvocationTargetException e) {
289             Activator.getDefault().getLogManager()
290                     .log(Level.ERROR.ordinal(), new Date(), e.getMessage());
291             e.printStackTrace();
292         } catch (InterruptedException e) {
293             Activator.getDefault().getLogManager()
294                     .log(Level.ERROR.ordinal(), new Date(), e.getMessage());
295             e.printStackTrace();
296         }
297         if (null == resource) {
298             wizard.setStatus("Failed to create Resource.");
299             wizard.getWizardDialog().close();
300             return null;
301         } else {
302             // Checking whether the resource is of type single.
303             Option intendedResource = wizard.getMainPage().getOption();
304             if ((intendedResource == Option.SIMPLE_FROM_RAML && !(resource instanceof SingleResource))) {
305                 MessageDialog
306                         .openError(
307                                 getShell(),
308                                 "Invalid RAML",
309                                 "Uploaded RAML is not of simple type. "
310                                         + "Please upload the proper RAML of simple type.");
311                 return null;
312             }
313         }
314         UpdatePropertiesPage updatePageRef = wizard.getUpdatePropPage();
315         updatePageRef.setResName(resource.getResourceName());
316         updatePageRef.setResURI(resource.getResourceURI());
317         return updatePageRef;
318     }
319
320     public String getConfigFilePath() {
321         return configFilePath;
322     }
323
324     public int getResourceCount() {
325         return resourceCount;
326     }
327
328     public Resource getResource() {
329         return resource;
330     }
331
332     public void setResource(Resource resource) {
333         this.resource = resource;
334     }
335 }