List of usage examples for org.eclipse.jface.dialogs ProgressMonitorDialog ProgressMonitorDialog
public ProgressMonitorDialog(Shell parent)
From source file:com.microsoft.tfs.client.eclipse.ui.actions.sync.ExternalCompareAction.java
License:Open Source License
@Override public void run() { final AdaptedSelectionInfo selectionInfo = ActionHelpers.adaptSelectionToStandardResources( getStructuredSelection(), PluginResourceFilters.IN_REPOSITORY_FILTER, false); if (ActionHelpers.ensureNonZeroResourceCountAndSingleRepository(selectionInfo, getShell()) == false) { return;/*from w ww . j a v a 2 s . c o m*/ } final IResource localResource = selectionInfo.getResources()[0]; String localFile = localResource.exists() ? localResource.getLocation().toOSString() : null; String remoteTempFile = null; /* * Open a progress dialog because we'll be fetching content from the * server. */ final ProgressMonitorDialog monitorDialog = new ProgressMonitorDialog(getShell()); monitorDialog.open(); final IProgressMonitor progressMonitor = monitorDialog.getProgressMonitor(); progressMonitor.beginTask(Messages.getString("ExternalCompareAction.ProgressText"), 100); //$NON-NLS-1$ try { /* * If the local file doesn't exist (due to deletion or incoming * addition, etc) then we need to make a dummy blank file for it so * that the external compare tool doesn't choke. */ if (localFile == null) { try { final File tempDir = TempStorageService.getInstance().createTempDirectory(); localFile = File.createTempFile("LocalNonexistant", //$NON-NLS-1$ "." + localResource.getFileExtension(), //$NON-NLS-1$ tempDir).getAbsolutePath(); } catch (final IOException e) { log.error("Error creating an empty local file as substitute for missing resource", e); //$NON-NLS-1$ // let the localFile == null test show errors } } /* * Get the remote file as a temp file. */ try { final SyncInfo syncInfo = SynchronizeSubscriber.getInstance().getSyncInfo(localResource); if (syncInfo != null) { final IResourceVariant variant = syncInfo.getRemote(); // variant is non-null normally... if (variant != null) { final SubProgressMonitor getMonitor = new SubProgressMonitor(progressMonitor, 75); final IStorage storage = variant.getStorage(getMonitor); // if there's a path to the storage, then the remote // item // was found normally if (storage != null && storage.getFullPath() != null) { remoteTempFile = storage.getFullPath().toOSString(); } // otherwise, the remote item is a deletion or a rename, // create a blank temp file for the external compare // tool else { final File tempDir = TempStorageService.getInstance().createTempDirectory(); remoteTempFile = File.createTempFile("RemoteNonexistant", //$NON-NLS-1$ "." + localResource.getFileExtension(), //$NON-NLS-1$ tempDir).getAbsolutePath(); } } } } catch (final Exception e) { log.error("Error getting the remote file contents", e); //$NON-NLS-1$ // suppress, fall-through to remoteFile == null test } } finally { progressMonitor.done(); monitorDialog.close(); } // SynchronizeSusbcriber.getSyncInfo().getRemote().getStorage() // should always return (even when in-sync, it will hit the // server intelligently.) if (remoteTempFile == null) { MessageDialog.openError(getShell(), Messages.getString("ExternalCompareAction.CompareErrorDialogTitle"), //$NON-NLS-1$ Messages.getString("ExternalCompareAction.CompareErrorDialogText")); //$NON-NLS-1$ return; } final Compare compare = new Compare(); compare.setModified(CompareUtils.createCompareElementForLocalPath(localFile, ResourceType.FILE)); compare.setOriginal(CompareUtils.createCompareElementForLocalPath(remoteTempFile, ResourceType.FILE)); compare.addComparator(TFSItemContentComparator.INSTANCE); compare.setExternalCompareHandler(new UserPreferenceExternalCompareHandler(getShell())); compare.open(); }
From source file:com.microsoft.webapp.debug.WebAppLaunchConfigurationDelegate.java
License:Open Source License
@Override public void launch(ILaunchConfiguration config, String mode, ILaunch launch, IProgressMonitor monitor) throws CoreException { final ILaunchConfiguration configToUse = config; String port = "8000"; Map<String, String> conMap = config.getAttribute(IJavaLaunchConfigurationConstants.ATTR_CONNECT_MAP, new HashMap<String, String>()); for (java.util.Map.Entry<String, String> entry : conMap.entrySet()) { if (entry.getKey().equalsIgnoreCase("port")) { port = entry.getValue();/*from w w w . j ava2 s . c om*/ } } final String portToDisplayError = port; try { // check port availability if (Utils.isPortAvailable(Integer.parseInt(port))) { // get web app name to which user want to debug his application String website = config.getAttribute(AzureLaunchConfigurationAttributes.WEBSITE_DISPLAY, ""); if (!website.isEmpty()) { website = website.substring(0, website.indexOf('(')).trim(); Map<WebSite, WebSiteConfiguration> webSiteConfigMap = PreferenceWebAppUtil.load(); // retrieve web apps configurations for (Entry<WebSite, WebSiteConfiguration> entry : webSiteConfigMap.entrySet()) { final WebSite websiteTemp = entry.getKey(); if (websiteTemp.getName().equals(website)) { // check is there a need for preparation AzureManager manager = AzureManagerImpl.getManager(); final WebSiteConfiguration webSiteConfiguration = entry.getValue(); final WebSitePublishSettings webSitePublishSettings = manager.getWebSitePublishSettings( webSiteConfiguration.getSubscriptionId(), webSiteConfiguration.getWebSpaceName(), website); // case - if user uses shortcut without going to Azure Tab Map<String, Boolean> mp = Activator.getDefault().getWebsiteDebugPrep(); if (!mp.containsKey(website)) { mp.put(website, false); } Activator.getDefault().setWebsiteDebugPrep(mp); if (Activator.getDefault().getWebsiteDebugPrep().get(website).booleanValue()) { // already prepared. Just start debugSession.bat // retrieve MSDeploy publish profile WebSitePublishSettings.MSDeployPublishProfile msDeployProfile = null; for (PublishProfile pp : webSitePublishSettings.getPublishProfileList()) { if (pp instanceof MSDeployPublishProfile) { msDeployProfile = (MSDeployPublishProfile) pp; break; } } if (msDeployProfile != null) { ProcessBuilder pb = null; String os = System.getProperty("os.name").toLowerCase(); String webAppDirPath = String.format("%s%s%s", PluginUtil.pluginFolder, File.separator, com.microsoft.webapp.util.Messages.webAppPluginID); if (Activator.IS_WINDOWS) { String command = String.format(Messages.command, port, website, msDeployProfile.getUserName(), msDeployProfile.getPassword()); pb = new ProcessBuilder("cmd", "/c", "start", "cmd", "/k", command); } else if (os.indexOf("nix") >= 0 || os.indexOf("nux") >= 0 || os.indexOf("aix") > 0) { // escape $ for linux String userName = "\\" + msDeployProfile.getUserName(); String command = String.format(Messages.commandSh, port, website, userName, msDeployProfile.getPassword()); pb = new ProcessBuilder("/bin/bash", "-c", command); } else { // escape $ for mac String userName = "'" + msDeployProfile.getUserName() + "'"; // On mac, you need to specify exact path of JAR String command = String.format(Messages.commandMac, webAppDirPath + "/", port, website, userName, msDeployProfile.getPassword()); String commandNext = "tell application \"Terminal\" to do script \"" + command + "\""; pb = new ProcessBuilder("osascript", "-e", commandNext); } pb.directory(new File(webAppDirPath)); try { pb.start(); Thread.sleep(10000); } catch (Exception e) { Activator.getDefault().log(Messages.errTtl, e); } super.launch(config, mode, launch, monitor); } } else { // start the process of preparing the web app, in a blocking way Display.getDefault().syncExec(new Runnable() { @Override public void run() { boolean choice = MessageDialog.openConfirm(PluginUtil.getParentShell(), Messages.title, Messages.remoteDebug); if (choice) { IRunnableWithProgress op = new PrepareForDebug(websiteTemp, webSiteConfiguration, webSitePublishSettings); try { new ProgressMonitorDialog(PluginUtil.getParentShell()).run(true, true, op); MessageDialog.openInformation(PluginUtil.getParentShell(), Messages.title, Messages.debugReady); } catch (Exception e) { Activator.getDefault().log(e.getMessage(), e); } } WebAppUtils.openDebugLaunchDialog(configToUse); } }); } break; } } } } else { Display.getDefault().syncExec(new Runnable() { @Override public void run() { PluginUtil.displayErrorDialog(PluginUtil.getParentShell(), Messages.errTtl, String.format(Messages.portMsg, portToDisplayError)); WebAppUtils.openDebugLaunchDialog(configToUse); } }); } } catch (Exception ex) { Activator.getDefault().log(ex.getMessage(), ex); } }
From source file:com.mmyumu.magictome.handlers.OpenHandler.java
License:Open Source License
@Execute public void execute(IEclipseContext context, @Named(IServiceConstants.ACTIVE_SHELL) final Shell shell) throws InvocationTargetException, InterruptedException { FileDialog dialog = new FileDialog(shell); dialog.setFilterExtensions(new String[] { "*.xml" }); dialog.setFilterNames(new String[] { "MTG Database XML File" }); dialog.setText("Open MTG Database"); final String filePath = dialog.open(); if (filePath != null) { ProgressMonitorDialog monitorDialog = new ProgressMonitorDialog(shell); monitorDialog.run(true, true, new IRunnableWithProgress() { public void run(IProgressMonitor monitor) { monitor.beginTask("Importing card database", 100); try { JAXBContext jc = JAXBContext.newInstance(MtgCarddatabase.class); Unmarshaller unmarshaller = jc.createUnmarshaller(); unmarshaller.setProperty("com.sun.xml.internal.bind.ObjectFactory", new ObjectFactoryEx()); monitor.worked(30);//from w w w. j a v a 2 s . c o m final MtgCarddatabase mtgCarddatabase = (MtgCarddatabase) unmarshaller .unmarshal(new File(filePath)); monitor.worked(80); shell.getDisplay().syncExec(new Runnable() { public void run() { // Add sets to Model List<IModelCheckElement> sets = new ArrayList<>(); for (Set set : mtgCarddatabase.getSets().getSet()) { SetEx setEx = (SetEx) set; sets.add(setEx); } MtgDatabaseModel mtgModel = ModelProvider.getModel(AppParams.ID, MtgDatabaseModel.class); SetsModel setsModel = mtgModel.getSetsModel(); setsModel.addElements(sets); // Add cards to Model List<IModelElement> cards = new ArrayList<>(); for (Card card : mtgCarddatabase.getCards().getCard()) { CardEx cardEx = (CardEx) card; cards.add(cardEx); } CardsModel cardsModel = mtgModel.getCardsModel(); cardsModel.addElements(cards); AppLifecycle.save(); } }); // Add cards to the set // for (Card card : // mtgCarddatabase.getCards().getCard()) { // CardEx cardEx = (CardEx) card; // ((SetExFull) cardEx.getSet()).addCard(cardEx); // } monitor.worked(100); } catch (JAXBException e) { logger.error(e, "Error while parsing XML file"); } monitor.done(); } }); } }
From source file:com.mmyumu.magictome.handlers.SaveHandler.java
License:Open Source License
@Execute public void execute(IEclipseContext context, @Named(IServiceConstants.ACTIVE_SHELL) Shell shell, @Named(IServiceConstants.ACTIVE_PART) final MContribution contribution) throws InvocationTargetException, InterruptedException { final IEclipseContext pmContext = context.createChild(); ProgressMonitorDialog dialog = new ProgressMonitorDialog(shell); dialog.open();//from ww w . j av a 2s . c om dialog.run(true, true, new IRunnableWithProgress() { public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException { pmContext.set(IProgressMonitor.class.getName(), monitor); if (contribution != null) { // Object clientObject = contribution.getObject(); // ContextInjectionFactory.invoke(clientObject, Persist.class, //$NON-NLS-1$ // pmContext, null); } } }); pmContext.dispose(); }
From source file:com.motorola.studio.android.devices.services.console.ADBShellHandler.java
License:Apache License
@Override public IStatus runService(IInstance theInstance, Map<Object, Object> arguments, IProgressMonitor monitor) { IStatus status = Status.OK_STATUS;//from w w w . ja v a 2 s. co m List<String> command = new LinkedList<String>(); final IInstance instance = theInstance; File sdkPath = new File(SdkUtils.getSdkPath()); String adbPath = SdkUtils.getAdbPath(); File adb = new File(adbPath); if ((sdkPath != null) && sdkPath.exists() && sdkPath.isDirectory()) { if (adb.exists() && adb.isFile()) { if (instance instanceof ISerialNumbered) { final String[] serialNumber = new String[1]; serialNumber[0] = ((ISerialNumbered) instance).getSerialNumber(); if (serialNumber[0] == null) { PlatformUI.getWorkbench().getDisplay().syncExec(new Runnable() { public void run() { ProgressMonitorDialog dialog = new ProgressMonitorDialog( new Shell(PlatformUI.getWorkbench().getDisplay())); try { dialog.run(false, false, new IRunnableWithProgress() { public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException { int limit = 20; SubMonitor theMonitor = SubMonitor.convert(monitor); theMonitor.beginTask(ServicesNLS.ADBShellHandler_WaitingDeviceToLoad, limit); int times = 0; while ((serialNumber[0] == null) && (times < limit)) { theMonitor.worked(1); Thread.sleep(500); serialNumber[0] = ((ISerialNumbered) instance).getSerialNumber(); times++; } theMonitor.setWorkRemaining(0); } }); } catch (Exception e) { //do nothing } } }); } // Fix a condition that Studio holds the UI thread forever if (serialNumber[0] == null) { status = new Status(IStatus.ERROR, DeviceServicesPlugin.PLUGIN_ID, ServicesNLS.ERR_ADBShellHandler_CouldNotExecuteTheAdbShell); return status; } if (adbPath.contains(" ")) //$NON-NLS-1$ { if (DeviceServicesPlugin.IS_WIN32) { adbPath = "\"" + adbPath + "\""; //$NON-NLS-1$ //$NON-NLS-2$ } else { adbPath = adbPath.replace(" ", "\\ "); //$NON-NLS-1$ //$NON-NLS-2$ } } command.add(adbPath); command.add(SERIAL_PARAMETER); command.add(serialNumber[0]); command.add(SHELL_COMMAND); try { Integer i = consolesCache.get(serialNumber[0]); i = (i == null ? 1 : ++i); consolesCache.put(serialNumber[0], i); String[] cmdArray = command.toArray(new String[4]); StringBuffer sb = new StringBuffer(); for (String cmd : cmdArray) { sb.append(cmd); sb.append(" "); //$NON-NLS-1$ } Process p = Runtime.getRuntime().exec(cmdArray); String consoleName = CONSOLE_NAME + " - " + serialNumber[0]; //$NON-NLS-1$ if (i != null) { consoleName += " (" + i + ")"; //$NON-NLS-1$ //$NON-NLS-2$ } consolesProcesses.put(consoleName, p); DeviceServicesPlugin.redirectProcessStreamsToConsole(p, consoleName); DeviceServicesPlugin.addConsoleKilledListener(listener); } catch (IOException e) { status = new Status(IStatus.ERROR, DeviceServicesPlugin.PLUGIN_ID, ServicesNLS.ERR_ADBShellHandler_CouldNotExecuteTheAdbShell, e); } } } else { status = new Status(IStatus.ERROR, DeviceServicesPlugin.PLUGIN_ID, ServicesNLS.ERR_ADBShellHandler_MissingAdbShell); } } else { status = new Status(IStatus.ERROR, DeviceServicesPlugin.PLUGIN_ID, ServicesNLS.ERR_ADBShellHandler_AndroidSdkIsNotConfigured); } return status; }
From source file:com.motorola.studio.android.devices.services.console.EmulatorConsoleHandler.java
License:Apache License
@Override public IStatus runService(final IInstance instance, Map<Object, Object> arguments, IProgressMonitor monitor) { IStatus status = Status.OK_STATUS;/* w w w.j av a 2 s . c o m*/ if (instance instanceof ISerialNumbered) { // Retrieve the emulator port from its serial number Pattern pattern = Pattern.compile("emulator-([0-9]+)"); final String[] serialNumber = new String[1]; serialNumber[0] = ((ISerialNumbered) instance).getSerialNumber(); if (serialNumber[0] == null) { PlatformUI.getWorkbench().getDisplay().syncExec(new Runnable() { public void run() { ProgressMonitorDialog dialog = new ProgressMonitorDialog( new Shell(PlatformUI.getWorkbench().getDisplay())); try { dialog.run(false, false, new IRunnableWithProgress() { public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException { int limit = 20; SubMonitor theMonitor = SubMonitor.convert(monitor); theMonitor.beginTask(ServicesNLS.ADBShellHandler_WaitingDeviceToLoad, limit); int times = 0; while ((serialNumber[0] == null) && (times < limit)) { theMonitor.worked(1); Thread.sleep(500); serialNumber[0] = ((ISerialNumbered) instance).getSerialNumber(); times++; } theMonitor.setWorkRemaining(0); } }); } catch (Exception e) { //do nothing } } }); } // Fix a condition that Studio holds the UI thread forever if (serialNumber[0] == null) { status = new Status(IStatus.ERROR, DeviceServicesPlugin.PLUGIN_ID, ServicesNLS.ERR_EmulatorConsoleHandler_CouldNotOpenTheConsoleShell); return status; } Matcher matcher = pattern.matcher(serialNumber[0]); if (matcher.matches()) { String port = matcher.group(1); final TelnetFrameworkAndroid telnet = new TelnetFrameworkAndroid(); try { Integer i = consolesCache.get(serialNumber[0]); i = (i == null ? 1 : ++i); consolesCache.put(serialNumber[0], i); telnet.connect(LOCALHOST, Integer.parseInt(port)); InputStream in = telnet.getInputStream(); OutputStream out = telnet.getOutputStream(); String consoleName = CONSOLE_NAME + " - " + serialNumber[0]; if (i != null) { consoleName += " (" + i + ")"; } telnetsCache.put(consoleName, telnet); DeviceServicesPlugin.addConsoleKilledListener(listener); DeviceServicesPlugin.redirectStreamsToConsole(in, out, consoleName); } catch (IOException e) { status = new Status(IStatus.ERROR, DeviceServicesPlugin.PLUGIN_ID, ServicesNLS.ERR_EmulatorConsoleHandler_CouldNotOpenTheConsoleShell, e); } } } else { status = new Status(IStatus.ERROR, DeviceServicesPlugin.PLUGIN_ID, ServicesNLS.ERR_EmulatorConsoleHandler_CouldNotRetrieveTheEmulatorPort); } return status; }
From source file:com.motorola.studio.android.emulator.ui.view.AbstractAndroidView.java
License:Apache License
/** * Stops all emulator instances with the Progress Monitor opened. *///from ww w.j a v a 2 s . com private void stopEmulatorInstances() { // defines the runnable object for stopping emulator instances. final IRunnableWithProgress stopRunnable = new IRunnableWithProgress() { public void run(IProgressMonitor monitor) { Collection<IAndroidEmulatorInstance> startedInstances = DeviceFrameworkManager.getInstance() .getAllStartedInstances(); boolean errorsHappened = false; for (IAndroidEmulatorInstance instance : startedInstances) { try { instance.stop(true); } catch (InstanceStopException e) { errorsHappened = true; } } // if closing on shutdown, use a progress bar and stall UI if (closingOnShutdown) { // start a progress monitor monitor.beginTask("", IProgressMonitor.UNKNOWN); // make sure the stop instance job finished Job[] jobs = Job.getJobManager().find(null); // get all jobs for (Job job : jobs) { if (job.getName().equals(EmulatorNLS.UI_AbstractAndroidView_StopInstanceJob)) { // when job result is not null, it has finished while (job.getResult() == null) { try { // sleep a little so the waiting is not too busy Thread.sleep(1000); } catch (InterruptedException e) { // do nothing } } } } } if (errorsHappened) { EclipseUtils.showErrorDialog(EmulatorNLS.GEN_Error, EmulatorNLS.EXC_AncroidView_CannotRunMultipleStopServices); } } }; // executes the runnable defined above. PlatformUI.getWorkbench().getDisplay().syncExec(new Runnable() { public void run() { Shell currentShell = getViewSite().getShell(); ProgressMonitorDialog dialog = new ProgressMonitorDialog(currentShell); try { dialog.run(true, false, stopRunnable); } catch (Exception e) { // Should not have exceptions. // The runnable is not interrupted and it handles exceptions internally // Log runtime exceptions error("Runtime exception was thrown: " + e.getClass().getSimpleName()); } } }); }
From source file:com.motorola.studio.android.generatemenucode.ui.GenerateMenuCodeHandler.java
License:Apache License
/** * Open {@link GenerateMenuCodeDialog} and use {@link JavaModifierBasedOnMenu} to insert code into Android source code (Activity/Fragment). */// w w w. java 2 s.co m public Object execute(ExecutionEvent event) throws ExecutionException { SelectionBean selectionBean = resolveSelection(event); if (selectionBean.isProject() || selectionBean.isAllowedClassInstance()) { final IWorkbenchWindow window = HandlerUtil.getActiveWorkbenchWindow(event); GenerateMenuCodeDialog menuDialog = new GenerateMenuCodeDialog(window.getShell(), CodeUtilsNLS.GenerateMenuCodeDialog_DefaultMessage, CodeUtilsNLS.GenerateMenuCodeDialog_Title, CodeUtilsNLS.GenerateMenuCodeDialog_ShellTitle, CodeUtilsActivator.getImageDescriptor(WIZARD_IMAGE_PATH).createImage()); final JavaModifierBasedOnMenu modifier = new JavaModifierBasedOnMenu(); menuDialog.init(modifier, selectionBean.getJavaProject(), selectionBean.getJavaFile()); int status = menuDialog.open(); if (status == Window.OK) { ICompilationUnit compilationUnit = menuDialog.getJavaFile(); IEditorPart editor = null; try { editor = JavaUI.openInEditor(compilationUnit); } catch (Exception e) { StudioLogger.warn(GenerateMenuCodeHandler.class, "Unable to open editor or bring it to front for Java file while trying to generate menu code based on xml file", //$NON-NLS-1$ e); } final ProgressMonitorDialog dialog = new ProgressMonitorDialog(menuDialog.getShell()); final IEditorPart editorPart = editor; PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() { public void run() { try { dialog.run(true, false, new IRunnableWithProgress() { public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException { try { // collect usage data - UDC StudioLogger.collectUsageData(UsageDataConstants.WHAT_VIEW_BY_MENU_EXEC, UsageDataConstants.KIND_VIEW_BY_MENU_EXEC, "View by menu feature executed.", //$NON-NLS-1$ CodeUtilsActivator.PLUGIN_ID, CodeUtilsActivator.getDefault() .getBundle().getVersion().toString()); modifier.insertCode(monitor, editorPart); } catch (final JavaModelException e) { final MultiStatus errorStatus = new MultiStatus( CodeUtilsActivator.PLUGIN_ID, IStatus.ERROR, "Error inserting code on activity/fragment based on menu", //$NON-NLS-1$ null); errorStatus.merge(e.getStatus()); PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() { public void run() { IStatus mostSevere = EclipseUtils.findMostSevereError(errorStatus); ErrorDialog.openError( PlatformUI.getWorkbench().getDisplay().getActiveShell(), "Error inserting code on activity/fragment based on menu", //$NON-NLS-1$ e.getMessage(), mostSevere); } }); StudioLogger.error(this.getClass(), "Error inserting code on activity/fragment based on menu" //$NON-NLS-1$ + ": " + e.getMessage()); //$NON-NLS-1$ } } }); } catch (Exception e) { StudioLogger.error(this.getClass(), "Error inserting code on activity/fragment based on menu" //$NON-NLS-1$ + ": " + e.getMessage()); //$NON-NLS-1$ } } }); } } else { EclipseUtils.showErrorDialog(CodeUtilsNLS.GenerateMenuCodeDialog_Title, CodeUtilsNLS.GenerateMenuCodeHandler_SelectedClassNeitherActivityFragment);//GenerateMenuCodeHandler_SelectedClassNeitherActivityFragment } return null; }
From source file:com.motorola.studio.android.generateviewbylayout.ui.AbstractCodeGeneratorHandler.java
License:Apache License
protected static void executeCodeGenerationWizard(ExecutionEvent event, IFile javaFile, final IProject javaProject, final AbstractLayoutItemsDialog layoutDialog) { final JavaModifierBasedOnLayout modifier = new JavaModifierBasedOnLayout(); layoutDialog.init(modifier, javaProject, javaFile); int status = layoutDialog.open(); if (status == Window.OK) { ICompilationUnit compilationUnit = layoutDialog.getJavaFile(); IEditorPart editor = null;// ww w . jav a 2s .c o m try { editor = JavaUI.openInEditor(compilationUnit); } catch (Exception e) { StudioLogger.warn(AbstractCodeGeneratorHandler.class, "Unable to open editor or bring it to front for Java file while trying to generate code from layout xml file", //$NON-NLS-1$ e); } final ProgressMonitorDialog dialog = new ProgressMonitorDialog(layoutDialog.getShell()); final IEditorPart editorPart = editor; PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() { public void run() { try { dialog.run(true, false, new IRunnableWithProgress() { public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException { try { // collect usage data - UDC StudioLogger.collectUsageData(UsageDataConstants.WHAT_VIEW_BY_LAYOUT_EXEC, UsageDataConstants.KIND_VIEW_BY_LAYOUT_EXEC, "View by layout feature executed.", //$NON-NLS-1$ CodeUtilsActivator.PLUGIN_ID, CodeUtilsActivator.getDefault().getBundle().getVersion().toString()); modifier.insertCode(monitor, editorPart); } catch (final JavaModelException e) { final MultiStatus errorStatus = new MultiStatus(CodeUtilsActivator.PLUGIN_ID, IStatus.ERROR, "Error inserting code on activity/fragment based on layout", null); errorStatus.merge(e.getStatus()); PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() { public void run() { IStatus mostSevere = EclipseUtils.findMostSevereError(errorStatus); ErrorDialog.openError( PlatformUI.getWorkbench().getDisplay().getActiveShell(), "Error inserting code on activity/fragment based on layout", e.getMessage(), mostSevere); } }); StudioLogger.error(this.getClass(), "Error inserting code on activity/fragment based on layout" + ": " //$NON-NLS-2$ + e.getMessage()); } } }); } catch (Exception e) { StudioLogger.error(this.getClass(), "Error inserting code on activity/fragment based on layout" + ": " //$NON-NLS-2$ + e.getMessage()); } } }); } }
From source file:com.motorola.studio.android.packaging.ui.export.PackageExportWizardArea.java
License:Apache License
/** * do the finish: Create the package for each selected descriptor */// w ww .jav a 2 s . c o m public boolean performFinish() { final boolean[] finished = { false }; boolean destOK = false; final MultiStatus status = new MultiStatus(PackagingUIPlugin.PLUGIN_ID, IStatus.OK, "", null); //$NON-NLS-1$ ProgressMonitorDialog monitorDialog = null; String DESCRIPTION_TO_LOG = StudioLogger.DESCRIPTION_DEFAULT; try { destOK = checkDestination(); } catch (CoreException e) { status.add(e.getStatus()); } if (destOK) { monitorDialog = new ProgressMonitorDialog(parentComposite.getShell()); try { monitorDialog.run(false, false, new IRunnableWithProgress() { @Override public void run(IProgressMonitor aMonitor) throws InvocationTargetException, InterruptedException { int finishSize = getSelectedItems().size() * PackagingUIPlugin.PROGRESS_MONITOR_MULTIPLIER; SubMonitor monitor = SubMonitor.convert(aMonitor); monitor.beginTask(Messages.PACKAGE_EXPORT_WIZARD_AREA_FINISH_ACTION_LABEL, finishSize); IPath exportDestinationFolder = new Path(destinationText.getText()); IPath exportDestinationFile = null; for (TreeItem item : getSelectedItems()) { // get the eclipse project as a java project to get // the project // destination IProject eclipseProject = (IProject) item.getData(); try { monitor.worked(PackagingUIPlugin.PROGRESS_MONITOR_MULTIPLIER / 4); JavaProject javaProject = new JavaProject(); javaProject.setProject(eclipseProject); // find all packages built by Android builder Map<String, String> apkConfigurations = SdkUtils .getAPKConfigurationsForProject(eclipseProject); Set<String> apkConfNames = new HashSet<String>(); if (apkConfigurations != null) { apkConfNames.addAll(apkConfigurations.keySet()); } apkConfNames.add(""); // the default package //$NON-NLS-1$ SubMonitor submonitor = monitor .newChild(PackagingUIPlugin.PROGRESS_MONITOR_MULTIPLIER / 4); submonitor.beginTask(Messages.PACKAGE_EXPORT_WIZARD_AREA_EXPORTING_ACTION_LABEL, 3 * PackagingUIPlugin.PROGRESS_MONITOR_MULTIPLIER * apkConfNames.size()); for (String apkConfName : apkConfNames) { String apkName = eclipseProject.getName() + (apkConfName.isEmpty() ? apkConfName : "-" //$NON-NLS-1$ //$NON-NLS-2$ + apkConfName); if (defaultDestination.getSelection()) { exportDestinationFolder = eclipseProject.getLocation() .append(CertificateManagerActivator.PACKAGE_PROJECT_DESTINATION); } exportDestinationFile = exportDestinationFolder.append(apkName) .addFileExtension(CertificateManagerActivator.PACKAGE_EXTENSION); File file = exportDestinationFile.toFile(); submonitor.worked(PackagingUIPlugin.PROGRESS_MONITOR_MULTIPLIER); //always export unsigned package AdtUtils.exportUnsignedReleaseApk(javaProject.getProject(), file, submonitor); submonitor.worked(PackagingUIPlugin.PROGRESS_MONITOR_MULTIPLIER); if (signCheckBox.getSelection()) { //sign the package if required IStatus signStatus = signPackage(eclipseProject, file); status.add(signStatus); } //zipalign the file and we are done exporting the package PackageFile.zipAlign(file); submonitor.worked(PackagingUIPlugin.PROGRESS_MONITOR_MULTIPLIER); } submonitor.done(); } catch (CoreException e) { StudioLogger.error(PackageExportWizardArea.class, "Error while building project or getting project output folder" //$NON-NLS-1$ + eclipseProject.getName(), e); status.add(new Status(IStatus.ERROR, PackagingUIPlugin.PLUGIN_ID, Messages.PACKAGE_EXPORT_WIZARD_AREA_ERROR_PROJECT_BUILD + " " //$NON-NLS-1$ + eclipseProject.getName())); } finally { try { eclipseProject.refreshLocal(IResource.DEPTH_INFINITE, monitor.newChild(PackagingUIPlugin.PROGRESS_MONITOR_MULTIPLIER / 4)); } catch (CoreException e) { // do nothing } } monitor.worked(PackagingUIPlugin.PROGRESS_MONITOR_MULTIPLIER / 4); } finished[0] = true; } }); } catch (Exception e) { StudioLogger.warn("Error finishing package export."); } } if (!status.isOK()) { status.getMessage(); DESCRIPTION_TO_LOG = Messages.PACKAGE_EXPORT_WIZARD_AREA_READONLY_TITLE; ErrorDialog.openError(parentComposite.getShell(), Messages.PACKAGE_EXPORT_WIZARD_AREA_READONLY_TITLE, Messages.PACKAGE_EXPORT_WIZARD_AREA_READONLY_MESSAGE, status); } // Saving usage data try { StudioLogger.collectUsageData(StudioLogger.WHAT_APP_MANAGEMENT_PACKAGE, StudioLogger.KIND_APP_MANAGEMENT, DESCRIPTION_TO_LOG, PackagingUIPlugin.PLUGIN_ID, PackagingUIPlugin.getDefault().getBundle().getVersion().toString()); } catch (Throwable e) { // Do nothing, but error on the log should never prevent app from // working } return finished[0]; }