e7c35b2ae85fef66f0d66090488e27c301b2d465
[platform/upstream/iotivity.git] / service / simulator / java / eclipse-plugin / ServiceProviderPlugin / src / oic / simulator / serviceprovider / view / dialogs / CreateResourceWizard.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.net.URL;
22 import java.util.Date;
23 import java.util.HashMap;
24 import java.util.Iterator;
25 import java.util.Map;
26 import java.util.Set;
27
28 import oic.simulator.serviceprovider.Activator;
29 import oic.simulator.serviceprovider.model.AttributeHelper;
30 import oic.simulator.serviceprovider.model.Resource;
31 import oic.simulator.serviceprovider.model.SingleResource;
32 import oic.simulator.serviceprovider.utils.Constants;
33 import oic.simulator.serviceprovider.utils.Utility;
34 import oic.simulator.serviceprovider.view.dialogs.MainPage.Option;
35
36 import org.eclipse.core.runtime.FileLocator;
37 import org.eclipse.core.runtime.IPath;
38 import org.eclipse.core.runtime.IProgressMonitor;
39 import org.eclipse.core.runtime.Path;
40 import org.eclipse.jface.dialogs.MessageDialog;
41 import org.eclipse.jface.operation.IRunnableWithProgress;
42 import org.eclipse.jface.resource.ImageDescriptor;
43 import org.eclipse.jface.wizard.IWizardPage;
44 import org.eclipse.jface.wizard.Wizard;
45 import org.eclipse.jface.wizard.WizardDialog;
46 import org.eclipse.swt.widgets.Display;
47 import org.oic.simulator.ILogger.Level;
48 import org.oic.simulator.SimulatorException;
49 import org.oic.simulator.SimulatorResourceAttribute;
50
51 /**
52  * This class creates a UI wizard for create resource operation.
53  */
54 public class CreateResourceWizard extends Wizard {
55
56     private MainPage                       mainPage;
57     private SimpleResourceBasicDetailsPage simpleResourceBasicDetailsPage;
58     private SimpleResourceAddAttributePage simpleResourceAddAttributePage;
59     private SimpleResourceOtherDetailsPage simpleResourceOtherDetailsPage;
60     private LoadRamlPage                   loadRamlPage;
61     private UpdatePropertiesPage           updatePropPage;
62
63     private String                         status;
64
65     private WizardDialog                   wizDialog;
66     private boolean                        dlgForceClosed;
67
68     private Resource                       createdResource;
69
70     public CreateResourceWizard() {
71         setWindowTitle("Create resources");
72         IPath path = new Path("/icons/oic_logo_64x64.png");
73         URL find = FileLocator.find(Activator.getDefault().getBundle(), path,
74                 null);
75         setDefaultPageImageDescriptor(ImageDescriptor.createFromURL(find));
76
77         setNeedsProgressMonitor(true);
78     }
79
80     @Override
81     public void addPages() {
82         mainPage = new MainPage();
83         simpleResourceBasicDetailsPage = new SimpleResourceBasicDetailsPage();
84         simpleResourceAddAttributePage = new SimpleResourceAddAttributePage();
85         simpleResourceOtherDetailsPage = new SimpleResourceOtherDetailsPage();
86         loadRamlPage = new LoadRamlPage();
87         updatePropPage = new UpdatePropertiesPage();
88
89         addPage(mainPage);
90         addPage(simpleResourceBasicDetailsPage);
91         addPage(simpleResourceAddAttributePage);
92         addPage(simpleResourceOtherDetailsPage);
93         addPage(loadRamlPage);
94         addPage(updatePropPage);
95     }
96
97     public void setWizardDialog(WizardDialog dlg) {
98         wizDialog = dlg;
99     }
100
101     public WizardDialog getWizardDialog() {
102         return wizDialog;
103     }
104
105     public boolean isDlgForceClosed() {
106         return dlgForceClosed;
107     }
108
109     public void setDlgForceClosed(boolean dlgForceClosed) {
110         this.dlgForceClosed = dlgForceClosed;
111     }
112
113     public String getConfigFilePath() {
114         if (null == loadRamlPage) {
115             return null;
116         }
117         return loadRamlPage.getConfigFilePath();
118     }
119
120     public int getResourceCount() {
121         if (null == loadRamlPage) {
122             return 0;
123         }
124         return loadRamlPage.getResourceCount();
125     }
126
127     public Resource getCreatedResource() {
128         return createdResource;
129     }
130
131     @Override
132     public boolean canFinish() {
133         IWizardPage curPage = this.getContainer().getCurrentPage();
134         if ((curPage == updatePropPage && ((mainPage.getOption() == Option.SIMPLE_FROM_RAML) || !Activator
135                 .getDefault().getResourceManager().isAnyResourceExist()))
136                 || curPage == simpleResourceAddAttributePage
137                 || (curPage == loadRamlPage && loadRamlPage.isSelectionDone() && loadRamlPage
138                 .isMultiResourceCreation())) {
139             return true;
140         }
141         return false;
142     }
143
144     @Override
145     public boolean performFinish() {
146         final IWizardPage curPage = this.getContainer().getCurrentPage();
147         // Handling Simple Resource Creation without RAML
148         if (curPage == simpleResourceAddAttributePage) {
149             try {
150                 getContainer().run(true, false, new IRunnableWithProgress() {
151
152                     @Override
153                     public void run(IProgressMonitor monitor)
154                             throws InvocationTargetException,
155                             InterruptedException {
156                         try {
157                             monitor.beginTask(
158                                     "Single Resource Creation Without RAML", 2);
159                             monitor.worked(1);
160                             createSingleResourceWithoutRAML();
161                         } finally {
162                             monitor.done();
163                         }
164                     }
165                 });
166             } catch (InvocationTargetException e) {
167                 Activator.getDefault().getLogManager()
168                 .log(Level.ERROR.ordinal(), new Date(), e.getMessage());
169                 e.printStackTrace();
170             } catch (InterruptedException e) {
171                 Activator.getDefault().getLogManager()
172                 .log(Level.ERROR.ordinal(), new Date(), e.getMessage());
173                 e.printStackTrace();
174             }
175         } else if (curPage == loadRamlPage) {
176             // Validate the file path.
177             try {
178                 new FileInputStream(loadRamlPage.getConfigFilePath());
179             } catch (Exception e) {
180                 MessageDialog
181                 .openError(getShell(), "Invalid File",
182                         "File doesn't exist. Either the file path or file name is invalid.");
183                 // TODO: Instead of MessageDialog, errors may be shown on wizard
184                 // itself.
185                 return false;
186             }
187
188             // Handling multiple instance creation of simple resource with RAML
189             if ((loadRamlPage.getResourceCount() + Activator.getDefault()
190                     .getResourceManager().getResourceCount()) > Constants.MAX_RESOURCE_COUNT) {
191                 MessageDialog
192                 .openInformation(Display.getDefault().getActiveShell(),
193                         "Resource limit exceeded",
194                         "Exceeded the limit of resources that can exist in the server.");
195                 return false;
196             }
197
198             try {
199                 getContainer().run(true, false, new IRunnableWithProgress() {
200
201                     @Override
202                     public void run(IProgressMonitor monitor)
203                             throws InvocationTargetException,
204                             InterruptedException {
205                         try {
206                             monitor.beginTask(
207                                     "Single Resource Creation(multi-instance) With RAML",
208                                     3);
209                             monitor.worked(1);
210                             createMultiInstanceSingleResourceWithoutRAML();
211                             monitor.worked(2);
212                         } finally {
213                             monitor.done();
214                         }
215                     }
216                 });
217             } catch (InvocationTargetException e) {
218                 Activator.getDefault().getLogManager()
219                 .log(Level.ERROR.ordinal(), new Date(), e.getMessage());
220                 e.printStackTrace();
221             } catch (InterruptedException e) {
222                 Activator.getDefault().getLogManager()
223                 .log(Level.ERROR.ordinal(), new Date(), e.getMessage());
224                 e.printStackTrace();
225             }
226         } else if (curPage == updatePropPage) {
227             // Handling the single instance
228             String resName = updatePropPage.getResName();
229             String resURI = updatePropPage.getResURI();
230             if (null == resName || resName.trim().length() < 1) {
231                 MessageDialog.openError(Display.getDefault().getActiveShell(),
232                         "Invalid Resource Name.", "Resource name is invalid");
233                 return false;
234             }
235             if (!Utility.isUriValid(resURI)) {
236                 MessageDialog.openError(Display.getDefault().getActiveShell(),
237                         "Invalid Resource URI.", Constants.INVALID_URI_MESSAGE);
238                 return false;
239             }
240             // Creation of simple resource with RAML
241             // Checking whether the URI is used by any other resource.
242             if (Activator.getDefault().getResourceManager()
243                     .isResourceExist(updatePropPage.getResURI())) {
244                 MessageDialog
245                 .openError(getShell(), "Resource URI in use",
246                         "Entered resource URI is in use. Please try a different one.");
247                 // TODO: Instead of MessageDialog, errors may be shown on wizard
248                 // itself.
249                 return false;
250             }
251
252             try {
253                 getContainer().run(true, false, new IRunnableWithProgress() {
254
255                     @Override
256                     public void run(IProgressMonitor monitor)
257                             throws InvocationTargetException,
258                             InterruptedException {
259                         try {
260                             monitor.beginTask("Completing Resource Creation", 2);
261                             monitor.worked(1);
262                             completeResourceCreationWithRAML();
263                             monitor.worked(1);
264                         } finally {
265                             monitor.done();
266                         }
267                     }
268                 });
269             } catch (InvocationTargetException e) {
270                 Activator.getDefault().getLogManager()
271                 .log(Level.ERROR.ordinal(), new Date(), e.getMessage());
272                 e.printStackTrace();
273             } catch (InterruptedException e) {
274                 Activator.getDefault().getLogManager()
275                 .log(Level.ERROR.ordinal(), new Date(), e.getMessage());
276                 e.printStackTrace();
277             }
278         }
279         return true;
280     }
281
282     public MainPage getMainPage() {
283         return mainPage;
284     }
285
286     public SimpleResourceBasicDetailsPage getSimpleResourceBasicDetailsPage() {
287         return simpleResourceBasicDetailsPage;
288     }
289
290     public SimpleResourceAddAttributePage getSimpleResourceAddAttributePage() {
291         return simpleResourceAddAttributePage;
292     }
293
294     public SimpleResourceOtherDetailsPage getSimpleResourceOtherDetailsPage() {
295         return simpleResourceOtherDetailsPage;
296     }
297
298     public LoadRamlPage getLoadRamlPage() {
299         return loadRamlPage;
300     }
301
302     public UpdatePropertiesPage getUpdatePropPage() {
303         return updatePropPage;
304     }
305
306     public void setStatus(String status) {
307         this.status = status;
308     }
309
310     public String getStatus() {
311         return status;
312     }
313
314     private void createSingleResourceWithoutRAML() {
315         SingleResource resource = new SingleResource();
316         // Basic resource details
317         resource.setResourceURI(simpleResourceBasicDetailsPage.getResURI());
318         resource.setResourceName(simpleResourceBasicDetailsPage.getResName());
319         resource.setResourceType(simpleResourceBasicDetailsPage.getResType());
320         resource.setObservable(simpleResourceBasicDetailsPage.isObservable());
321
322         // Resource Attributes
323         Map<String, SimulatorResourceAttribute> attributes = new HashMap<String, SimulatorResourceAttribute>();
324         Set<AttributeHelper> attributeSet = simpleResourceAddAttributePage
325                 .getAttributes();
326         if (null != attributeSet && !attributeSet.isEmpty()) {
327             Iterator<AttributeHelper> itr = attributeSet.iterator();
328             AttributeHelper attHelper;
329             SimulatorResourceAttribute attribute;
330             while (itr.hasNext()) {
331                 attHelper = itr.next();
332                 if (null != attHelper) {
333                     attribute = attHelper.convertToSimulatorResourceAttribute();
334                     attributes.put(attribute.name(), attribute);
335                 }
336             }
337         }
338
339         // Request types
340         resource.setGetAllowed(simpleResourceOtherDetailsPage.isGetChecked());
341         resource.setPutAllowed(simpleResourceOtherDetailsPage.isPutChecked());
342         resource.setPostAllowed(simpleResourceOtherDetailsPage.isPostChecked());
343
344         // Call method of ResourceManager and update the response in the status
345         // string.
346         try {
347             boolean result = Activator.getDefault().getResourceManager()
348                     .createSingleResource(resource, attributes);
349             if (result) {
350                 status = "Resource created.";
351                 createdResource = resource;
352             } else {
353                 status = "Failed to create resource.";
354                 createdResource = null;
355             }
356         } catch (Exception e) {
357             status = "Failed to create resource.\n"
358                     + Utility.getSimulatorErrorString(e, null);
359             createdResource = null;
360         }
361     }
362
363     private void completeResourceCreationWithRAML() {
364         try {
365             boolean result = false;
366             Resource res = loadRamlPage.getResource();
367             if (res instanceof SingleResource) {
368                 result = Activator
369                         .getDefault()
370                         .getResourceManager()
371                         .completeSingleResourceCreationByRAML(res,
372                                 updatePropPage.getResURI(),
373                                 updatePropPage.getResName(), false);
374             }
375
376             if (result) {
377                 status = "Resource created.";
378                 createdResource = res;
379             } else {
380                 status = "Failed to create resource.";
381                 createdResource = null;
382             }
383         } catch (Exception e) {
384             status = "Failed to create resource.\n"
385                     + Utility.getSimulatorErrorString(e, null);
386             createdResource = null;
387         }
388     }
389
390     private void createMultiInstanceSingleResourceWithoutRAML() {
391         try {
392             int toCreateCount = loadRamlPage.getResourceCount();
393             int resCreatedCount = Activator
394                     .getDefault()
395                     .getResourceManager()
396                     .createSingleResourceMultiInstances(
397                             loadRamlPage.getConfigFilePath(), toCreateCount);
398             if (resCreatedCount > 0) {
399                 status = "[" + resCreatedCount + " out of " + toCreateCount
400                         + "]";
401                 status += ((resCreatedCount == 1) ? "resource" : "resources")
402                         + " created successfully.";
403             } else {
404                 status = "Failed to create resources.";
405             }
406         } catch (SimulatorException e) {
407             status = "Failed to create resource.\n"
408                     + Utility.getSimulatorErrorString(e, null);
409         }
410     }
411 }