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