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