/** * Adds the text and move changes to the root change This change is the a more global change, it * includes both the file(s) move, the update of it's includes and update all the references, all * the files that have includes to the moved file. * * @param pm - progress monitor * @param rootChange - the root change that the new changes are added to * @return the root change after the additions */ private Change createReferenceUpdatingMoveChange(IProgressMonitor pm, CompositeChange rootChange) throws CoreException, OperationCanceledException { try { pm.beginTask(PhpRefactoringCoreMessages.getString("MoveDelegate.0"), 100); // $NON-NLS-1$ IResource[] sourceResources = fProcessor.getSourceSelection(); createTextChanges(new SubProgressMonitor(pm, 80), rootChange, phpFiles, sourceResources); pm.worked(80); // update configuration file. createRunConfigurationChange(sourceResources, rootChange); // There is a tricky thing here. // The resource move must be happened after text change, and run // configuration changes(this is because the share file under the // project) // but before the other changes, e.g. break point and etc. createMoveChange(sourceResources, rootChange); // update associated break point. createBreakPointChange(sourceResources, rootChange); createBuildPathChange(sourceResources, rootChange); createRenameLibraryFolderChange(sourceResources, rootChange); pm.worked(20); } finally { pm.done(); } return rootChange; }
/* (non-Javadoc) * @see org.eclipse.core.internal.jobs.InternalJob#run(org.eclipse.core.runtime.IProgressMonitor) */ protected IStatus run(IProgressMonitor monitor) { TreeNode root = new TreeNode(""); File it = new File(proj.getLocation().addTrailingSeparator() + "goblin.xml"); if (!it.canRead()) return new Status(IStatus.ERROR, "ee.ut.goblin", 97, "Can't read analysis file.", null); DefaultHandler handler = new XMLHandler(root); SAXParserFactory factory = SAXParserFactory.newInstance(); try { // Parse the input SAXParser saxParser = factory.newSAXParser(); saxParser.parse(it, handler); } catch (Throwable t) { return new Status(IStatus.ERROR, "ee.ut.goblin", 96, t.getMessage(), t); } TreeAnalysisMap tam = new TreeAnalysisMap((TreeAnalysis) root.getChildren()[0]); try { proj.setSessionProperty(GoblinPlugin.RESULT_NAME, tam); } catch (CoreException e) { return new Status(IStatus.ERROR, "ee.ut.goblin", 95, e.getMessage(), e); } monitor.done(); return Status.OK_STATUS; }
@Override public void setCharset(String newCharset, IProgressMonitor monitor) throws CoreException { monitor = Policy.monitorFor(monitor); try { String message = NLS.bind(Messages.resources_settingCharset, getFullPath()); monitor.beginTask(message, Policy.totalWork); // need to get the project as a scheduling rule because we might be creating a new folder/file // to // hold the project settings final ISchedulingRule rule = workspace.getRuleFactory().charsetRule(this); try { workspace.prepareOperation(rule, monitor); ResourceInfo info = getResourceInfo(false, false); checkAccessible(getFlags(info)); workspace.beginOperation(true); workspace.getCharsetManager().setCharsetFor(getFullPath(), newCharset); info = getResourceInfo(false, true); info.incrementCharsetGenerationCount(); monitor.worked(Policy.opWork); } catch (OperationCanceledException e) { workspace.getWorkManager().operationCanceled(); throw e; } finally { workspace.endOperation(rule, true, Policy.subMonitorFor(monitor, Policy.endOpWork)); } } finally { monitor.done(); } }
protected IResource[] checkOverwriteOfDirtyResources( IResource[] resources, IProgressMonitor monitor) throws CVSException, InterruptedException { List dirtyResources = new ArrayList(); IResource[] selectedResources = getSelectedResources(); try { monitor = Policy.monitorFor(monitor); monitor.beginTask(null, selectedResources.length * 100); monitor.setTaskName(CVSUIMessages.ReplaceWithAction_calculatingDirtyResources); for (int i = 0; i < selectedResources.length; i++) { IResource resource = selectedResources[i]; ICVSResource cvsResource = getCVSResourceFor(resource); if (cvsResource.isModified(Policy.subMonitorFor(monitor, 100))) { dirtyResources.add(resource); } } } finally { monitor.done(); } PromptingDialog dialog = new PromptingDialog( getShell(), selectedResources, getPromptCondition( (IResource[]) dirtyResources.toArray(new IResource[dirtyResources.size()])), CVSUIMessages.ReplaceWithAction_confirmOverwrite); return dialog.promptForMultiple(); }
@Override public void setContents(InputStream content, int updateFlags, IProgressMonitor monitor) throws CoreException { monitor = Policy.monitorFor(monitor); try { String message = NLS.bind(Messages.resources_settingContents, getFullPath()); monitor.beginTask(message, Policy.totalWork); if (workspace.shouldValidate) workspace.validateSave(this); final ISchedulingRule rule = workspace.getRuleFactory().modifyRule(this); try { workspace.prepareOperation(rule, monitor); ResourceInfo info = getResourceInfo(false, false); checkAccessible(getFlags(info)); workspace.beginOperation(true); IFileInfo fileInfo = getStore().fetchInfo(); internalSetContents( content, fileInfo, updateFlags, false, Policy.subMonitorFor(monitor, Policy.opWork)); } catch (OperationCanceledException e) { workspace.getWorkManager().operationCanceled(); throw e; } finally { workspace.endOperation(rule, true, Policy.subMonitorFor(monitor, Policy.endOpWork)); } } finally { monitor.done(); FileUtil.safeClose(content); } }
/* * @see IWorkspaceRunnable#run(IProgressMonitor) */ public void run(IProgressMonitor monitor) throws CoreException, OperationCanceledException { if (monitor == null) { monitor = new NullProgressMonitor(); } monitor.beginTask(MDEUIMessages.FeatureImportWizard_operation_creating, fModels.length); try { MultiStatus multiStatus = new MultiStatus( MDEPlugin.getPluginId(), IStatus.OK, MDEUIMessages.FeatureImportWizard_operation_multiProblem, null); for (int i = 0; i < fModels.length; i++) { try { createProject(fModels[i], new SubProgressMonitor(monitor, 1)); } catch (CoreException e) { multiStatus.merge(e.getStatus()); } if (monitor.isCanceled()) { throw new OperationCanceledException(); } } if (!multiStatus.isOK()) { throw new CoreException(multiStatus); } } finally { monitor.done(); } }
@Override protected IStatus run(IProgressMonitor monitor) { MultiStatus result = new MultiStatus( ResourcesPlugin.PI_RESOURCES, IResourceStatus.FAILED_SETTING_CHARSET, Messages.resources_updatingEncoding, null); monitor = Policy.monitorFor(monitor); try { monitor.beginTask(Messages.resources_charsetUpdating, Policy.totalWork); final ISchedulingRule rule = workspace.getRuleFactory().modifyRule(workspace.getRoot()); try { workspace.prepareOperation(rule, monitor); workspace.beginOperation(true); Map.Entry<IProject, Boolean> next; while ((next = getNextChange()) != null) { // just exit if the system is shutting down or has been shut down // it is too late to change the workspace at this point anyway if (systemBundle.getState() != Bundle.ACTIVE) return Status.OK_STATUS; IProject project = next.getKey(); try { if (project.isAccessible()) { boolean shouldDisableCharsetDeltaJob = next.getValue().booleanValue(); // flush preferences for non-derived resources flushPreferences( getPreferences(project, false, false, true), shouldDisableCharsetDeltaJob); // flush preferences for derived resources flushPreferences( getPreferences(project, false, true, true), shouldDisableCharsetDeltaJob); } } catch (BackingStoreException e) { // we got an error saving String detailMessage = Messages.resources_savingEncoding; result.add( new ResourceStatus( IResourceStatus.FAILED_SETTING_CHARSET, project.getFullPath(), detailMessage, e)); } } monitor.worked(Policy.opWork); } catch (OperationCanceledException e) { workspace.getWorkManager().operationCanceled(); throw e; } finally { workspace.endOperation(rule, true, Policy.subMonitorFor(monitor, Policy.endOpWork)); } } catch (CoreException ce) { return ce.getStatus(); } finally { monitor.done(); } return result; }
public void execute(IProgressMonitor monitor) { IPluginModelBase[] plugins = PluginJavaSearchUtil.getPluginImports(fImportID); monitor.beginTask( PDEUIMessages.DependencyExtentOperation_searching + " " + fImportID + "...", 10); //$NON-NLS-1$//$NON-NLS-2$ checkForJavaDependencies(plugins, new SubProgressMonitor(monitor, 9)); for (int i = 0; i < plugins.length; i++) { checkForExtensionPointsUsed(plugins[i]); } monitor.done(); }
/** * Initializes DLTKCore internal structures to allow subsequent operations (such as the ones that * need a resolved classpath) to run full speed. A client may choose to call this method in a * background thread early after the workspace has started so that the initialization is * transparent to the user. * * <p>However calling this method is optional. Services will lazily perform initialization when * invoked. This is only a way to reduce initialization overhead on user actions, if it can be * performed before at some appropriate moment. * * <p>This initialization runs accross all Java projects in the workspace. Thus the workspace root * scheduling rule is used during this operation. * * <p>This method may return before the initialization is complete. The initialization will then * continue in a background thread. * * <p>This method can be called concurrently. * * @param monitor a progress monitor, or <code>null</code> if progress reporting and cancellation * are not desired * @exception CoreException if the initialization fails, the status of the exception indicates the * reason of the failure * @since 3.1 */ public static void initializeAfterLoad(IProgressMonitor monitor) throws CoreException { try { if (monitor != null) { monitor.beginTask(CoreMessages.PHPCorePlugin_initializingPHPToolkit, 125); } // dummy query for waiting until the indexes are ready IDLTKSearchScope scope = SearchEngine.createWorkspaceScope(PHPLanguageToolkit.getDefault()); try { LanguageModelInitializer.cleanup(monitor); if (monitor != null) { monitor.subTask(CoreMessages.PHPCorePlugin_initializingSearchEngine); monitor.worked(25); } PhpModelAccess.getDefault() .findMethods(ID, MatchRule.PREFIX, Modifiers.AccGlobal, 0, scope, monitor); if (monitor != null) { monitor.worked(25); } PhpModelAccess.getDefault() .findTypes(ID, MatchRule.PREFIX, Modifiers.AccGlobal, 0, scope, monitor); if (monitor != null) { monitor.worked(25); } PhpModelAccess.getDefault() .findFields(ID, MatchRule.PREFIX, Modifiers.AccGlobal, 0, scope, monitor); if (monitor != null) { monitor.worked(25); } PhpModelAccess.getDefault().findIncludes(ID, MatchRule.PREFIX, scope, monitor); if (monitor != null) { monitor.worked(25); } } catch (OperationCanceledException e) { if (monitor != null && monitor.isCanceled()) { throw e; } // else indexes were not ready: catch the exception so that jars // are still refreshed } } finally { if (monitor != null) { monitor.done(); } toolkitInitialized = true; } }
/** * Adds the move changes to the root change This change is the proper move change, nothing else * * @param pm - progress monitor * @param rootChange - the root change that the new changes are added to * @return the root change after the additions */ private Change createSimpleMoveChange(final IProgressMonitor pm, final CompositeChange rootChange) throws CoreException, OperationCanceledException { try { pm.beginTask(PhpRefactoringCoreMessages.getString("MoveDelegate.0"), 100); // $NON-NLS-1$ IResource[] sourceResources = fProcessor.getSourceSelection(); createMoveChange(sourceResources, rootChange); pm.worked(100); } finally { pm.done(); } return rootChange; }
public ICVSRemoteResource[] getFoldersForTag( ICVSRepositoryLocation location, CVSTag tag, IProgressMonitor monitor) throws CVSException { monitor = Policy.monitorFor(monitor); try { monitor.beginTask( NLS.bind( CVSUIMessages.RepositoryManager_fetchingRemoteFolders, new String[] {tag.getName()}), 100); if (tag.getType() == CVSTag.HEAD) { ICVSRemoteResource[] resources = location.members(tag, false, Policy.subMonitorFor(monitor, 60)); RepositoryRoot root = getRepositoryRootFor(location); ICVSRemoteResource[] modules = root.getDefinedModules(tag, Policy.subMonitorFor(monitor, 40)); ICVSRemoteResource[] result = new ICVSRemoteResource[resources.length + modules.length]; System.arraycopy(resources, 0, result, 0, resources.length); System.arraycopy(modules, 0, result, resources.length, modules.length); return result; } if (tag.getType() == CVSTag.DATE) { ICVSRemoteResource[] resources = location.members(tag, false, Policy.subMonitorFor(monitor, 60)); RepositoryRoot root = getRepositoryRootFor(location); ICVSRemoteResource[] modules = root.getDefinedModules(tag, Policy.subMonitorFor(monitor, 40)); ICVSRemoteResource[] result = new ICVSRemoteResource[resources.length + modules.length]; System.arraycopy(resources, 0, result, 0, resources.length); System.arraycopy(modules, 0, result, resources.length, modules.length); return result; } Set result = new HashSet(); // Get the tags for the location RepositoryRoot root = getRepositoryRootFor(location); String[] paths = root.getKnownRemotePaths(); for (int i = 0; i < paths.length; i++) { String path = paths[i]; List tags = Arrays.asList(root.getAllKnownTags(path)); if (tags.contains(tag)) { ICVSRemoteFolder remote = root.getRemoteFolder(path, tag, Policy.subMonitorFor(monitor, 100)); result.add(remote); } } return (ICVSRemoteResource[]) result.toArray(new ICVSRemoteResource[result.size()]); } finally { monitor.done(); } }
/** * Implements the interface method by looping through template sections and executing them * sequentially. * * @param project the project * @param model the plug-in model * @param monitor the progress monitor to track the execution progress as part of the overall new * project creation operation * @return <code>true</code> if the wizard completed the operation with success, <code>false * </code> otherwise. */ public boolean performFinish(IProject project, IPluginModelBase model, IProgressMonitor monitor) { try { ITemplateSection[] sections = getTemplateSections(); monitor.beginTask("", sections.length); // $NON-NLS-1$ for (int i = 0; i < sections.length; i++) { sections[i].execute(project, model, new SubProgressMonitor(monitor, 1)); } // No reason to do this any more with the new editors // saveTemplateFile(project, null); } catch (CoreException e) { PDEPlugin.logException(e); return false; } finally { monitor.done(); } return true; }
private void checkForJavaDependencies(IPluginModelBase[] models, IProgressMonitor monitor) { try { if (!fProject.hasNature(JavaCore.NATURE_ID)) return; IJavaProject jProject = JavaCore.create(fProject); IPackageFragment[] packageFragments = PluginJavaSearchUtil.collectPackageFragments(models, jProject, true); monitor.beginTask("", packageFragments.length); // $NON-NLS-1$ SearchEngine engine = new SearchEngine(); for (int i = 0; i < packageFragments.length; i++) { if (monitor.isCanceled()) break; IPackageFragment pkgFragment = packageFragments[i]; monitor.subTask( PDEUIMessages.DependencyExtentOperation_inspecting + " " + pkgFragment.getElementName()); // $NON-NLS-1$ if (pkgFragment.hasChildren()) { IJavaElement[] children = pkgFragment.getChildren(); for (int j = 0; j < children.length; j++) { if (monitor.isCanceled()) break; IJavaElement child = children[j]; IType[] types = new IType[0]; if (child instanceof IClassFile) { types = new IType[] {((IClassFile) child).getType()}; } else if (child instanceof ICompilationUnit) { types = ((ICompilationUnit) child).getTypes(); } if (types.length > 0) searchForTypesUsed( engine, child, types, PluginJavaSearchUtil.createSeachScope(jProject)); } } monitor.worked(1); } } catch (CoreException e) { } finally { monitor.done(); } }
/** * Creates the text changes for all the affected files. Updates all the include statements in the * current file and all the includes in the "including " files. In case of folders, creates the * changes recursively * * @param pm - progress monitor * @param rootChange - the root change that the new changes are added to * @param sourceResources * @return the root change after the additions * @throws CoreException */ private Change createTextChanges( IProgressMonitor pm, CompositeChange rootChange, Set<IFile> phpFiles, IResource[] sourceResources) throws CoreException { List<ProgramFileChange> changes = new ArrayList<ProgramFileChange>(); try { pm.beginTask(PhpRefactoringCoreMessages.getString("MoveDelegate.1"), 100); // $NON-NLS-1$ // creat text changes: // for each file that will be moved, update its includes // and update all the files that include it, IResource[] uniqueSourceResources = removeDuplicateResources(sourceResources); for (Iterator<IFile> it = phpFiles.iterator(); it.hasNext(); ) { IFile currentMovedResource = it.next(); Map<IFile, Program> participantFiles = collectReferencingFiles(currentMovedResource, pm); for (Entry<IFile, Program> entry : participantFiles.entrySet()) { final IFile file = entry.getKey(); if (phpFiles.contains(file)) { continue; } final Program program = entry.getValue(); final ChangeIncludePath rename = new ChangeIncludePath( currentMovedResource, file, fMainDestinationPath, false, uniqueSourceResources); // aggregate the changes identifiers program.accept(rename); if (pm.isCanceled()) throw new OperationCanceledException(); pm.worked(1); if (rename.hasChanges()) { ProgramFileChange change = new ProgramFileChange(file.getName(), file, program); change.setEdit(new MultiTextEdit()); change.setTextType("php"); // $NON-NLS-1$ changes.add(change); rename.updateChange(change); } } ISourceModule sourceModule = DLTKCore.createSourceModuleFrom(currentMovedResource); if (sourceModule instanceof ISourceModule) { Program program = null; try { program = ASTUtils.createProgramFromSource(sourceModule); } catch (Exception e) { } if (program != null) { final ChangeIncludePath rename = new ChangeIncludePath( currentMovedResource, currentMovedResource, fMainDestinationPath, true, uniqueSourceResources); // aggregate the changes identifiers program.accept(rename); if (pm.isCanceled()) throw new OperationCanceledException(); pm.worked(1); if (rename.hasChanges()) { ProgramFileChange change = new ProgramFileChange( currentMovedResource.getName(), currentMovedResource, program); change.setEdit(new MultiTextEdit()); change.setTextType("php"); // $NON-NLS-1$ changes.add(change); rename.updateChange(change); } } } } pm.worked(70); } finally { pm.done(); } // getChildren() Map<IFile, List<TextEdit>> changeMap = new HashMap<IFile, List<TextEdit>>(); Map<IFile, ProgramFileChange> fileMap = new HashMap<IFile, ProgramFileChange>(); for (ProgramFileChange programFileChange : changes) { List<TextEdit> list = changeMap.get(programFileChange.getFile()); if (list == null) { list = new ArrayList<TextEdit>(); changeMap.put(programFileChange.getFile(), list); fileMap.put(programFileChange.getFile(), programFileChange); } else { } list.addAll(Arrays.asList(programFileChange.getEdit().getChildren())); } for (IFile file : changeMap.keySet()) { ProgramFileChange change = new ProgramFileChange(file.getName(), file, fileMap.get(file).getProgram()); change.setEdit(new MultiTextEdit()); change.setTextType("php"); // $NON-NLS-1$ List<TextEdit> list = changeMap.get(file); Collections.sort( list, new Comparator<TextEdit>() { public int compare(TextEdit o1, TextEdit o2) { return o2.getOffset() - o1.getOffset(); } }); for (TextEdit textEdit : list) { if (textEdit instanceof ReplaceEdit) { ReplaceEdit replaceEdit = (ReplaceEdit) textEdit; change.addEdit( new ReplaceEdit( replaceEdit.getOffset(), replaceEdit.getLength(), replaceEdit.getText())); } } rootChange.add(change); } return rootChange; }
/** * This is run by the job scheduler. A list of subscribers will be refreshed, errors will not stop * the job and it will continue to refresh the other subscribers. */ @Override public IStatus run(IProgressMonitor monitor) { // Perform a pre-check for auto-build or manual build jobs // when auto-refreshing if (shouldReschedule() && (isJobInFamilyRunning(ResourcesPlugin.FAMILY_AUTO_BUILD) || isJobInFamilyRunning(ResourcesPlugin.FAMILY_MANUAL_BUILD))) { return POSTPONED; } // Only allow one refresh job at a time // NOTE: It would be cleaner if this was done by a scheduling // rule but at the time of writing, it is not possible due to // the scheduling rule containment rules. // Acquiring lock to ensure only one refresh job is running at a particular time boolean acquired = false; try { while (!acquired) { try { acquired = lock.acquire(1000); } catch (InterruptedException e1) { acquired = false; } Policy.checkCanceled(monitor); } IChangeDescription changeDescription = createChangeDescription(); RefreshEvent event = new RefreshEvent( reschedule ? IRefreshEvent.SCHEDULED_REFRESH : IRefreshEvent.USER_REFRESH, participant, changeDescription); IStatus status = null; NonblockingProgressMonitor wrappedMonitor = null; try { event.setStartTime(System.currentTimeMillis()); if (monitor.isCanceled()) { return Status.CANCEL_STATUS; } // Pre-Notify notifyListeners(STARTED, event); // Perform the refresh monitor.setTaskName(getName()); wrappedMonitor = new NonblockingProgressMonitor(monitor, this); doRefresh(changeDescription, wrappedMonitor); // Prepare the results setProperty(IProgressConstants.KEEPONE_PROPERTY, Boolean.valueOf(!isJobModal())); } catch (OperationCanceledException e2) { if (monitor.isCanceled()) { // The refresh was canceled by the user status = Status.CANCEL_STATUS; } else { // The refresh was canceled due to a blockage or a canceled authentication if (wrappedMonitor != null && wrappedMonitor.wasBlocking()) { status = POSTPONED; } else { status = Status.CANCEL_STATUS; } } } catch (CoreException e) { // Determine the status to be returned and the GOTO action status = e.getStatus(); if (!isUser()) { // Use the GOTO action to show the error and return OK Object prop = getProperty(IProgressConstants.ACTION_PROPERTY); if (prop instanceof GotoActionWrapper) { GotoActionWrapper wrapper = (GotoActionWrapper) prop; wrapper.setStatus(e.getStatus()); status = new Status(IStatus.OK, TeamUIPlugin.ID, IStatus.OK, e.getStatus().getMessage(), e); } } if (!isUser() && status.getSeverity() == IStatus.ERROR) { // Never prompt for errors on non-user jobs setProperty(IProgressConstants.NO_IMMEDIATE_ERROR_PROMPT_PROPERTY, Boolean.TRUE); } } finally { event.setStopTime(System.currentTimeMillis()); } // Post-Notify if (status == null) { status = calculateStatus(event); } event.setStatus(status); notifyListeners(DONE, event); if (event.getChangeDescription().getChangeCount() > 0) { if (participant instanceof AbstractSynchronizeParticipant) { AbstractSynchronizeParticipant asp = (AbstractSynchronizeParticipant) participant; asp.firePropertyChange( participant, ISynchronizeParticipant.P_CONTENT, null, event.getChangeDescription()); } } return event.getStatus(); } finally { if (acquired) lock.release(); monitor.done(); } }
/** * The worker method. It will create a new project, then create the appropriate Soar heirarchy and * files. */ private void doFinish(String projectName, IProgressMonitor monitor) throws CoreException { monitor.beginTask("Creating " + projectName, 7); IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot(); IProject newProject = root.getProject(projectName); // creation of the project if (newProject.exists()) { throwCoreException("Project \"" + projectName + "\" already exists"); } else { newProject.create(monitor); newProject.open(monitor); try { IProjectDescription description = newProject.getDescription(); String[] natures = description.getNatureIds(); String[] newNatures = new String[natures.length + 1]; System.arraycopy(natures, 0, newNatures, 0, natures.length); newNatures[natures.length] = SoarProjectNature.NATURE_ID; description.setNatureIds(newNatures); newProject.setDescription(description, IResource.FORCE, monitor); newProject.setPersistentProperty(DataMap.VERTEX_ID, "0"); } catch (CoreException e) { e.printStackTrace(); } // catch } // else monitor.worked(2); // Create the contents of the project's root directory IFolder folderAll = newProject.getFolder("all"); if (!folderAll.exists()) { folderAll.create(true, true, monitor); } // if FileMarker.markResource(folderAll, "file"); IFolder folderElaborations = newProject.getFolder("elaborations"); if (!folderElaborations.exists()) { folderElaborations.create(true, true, monitor); } // if FileMarker.markResource(folderElaborations, "file"); IFile file_firstload = newProject.getFile("_firstload.soar"); if (!file_firstload.exists()) { file_firstload.create( Utility.getFileTemplate(file_firstload, "_firstload.soar"), true, monitor); } // if FileMarker.markResource(file_firstload, "file"); IFile filedatamap = newProject.getFile("datamap.xdm"); if (!filedatamap.exists()) { filedatamap.create(Utility.getFileTemplate(filedatamap, "datamap.xdm"), true, monitor); } // if monitor.worked(3); // Create the contents of the elaborations folder IFile file_all = folderElaborations.getFile("_all.soar"); if (!file_all.exists()) { file_all.create(Utility.getFileTemplate(file_all, "_all.soar"), true, monitor); } // if FileMarker.markResource(file_all, "file"); IFile filetopstate = folderElaborations.getFile("top-state.soar"); if (!filetopstate.exists()) { filetopstate.create(Utility.getFileTemplate(filetopstate, "top-state.soar"), true, monitor); } // if FileMarker.markResource(filetopstate, "file"); SourcingFile.createSourcingFile(newProject, monitor); newProject.close(monitor); newProject.open(monitor); monitor.worked(2); monitor.done(); } // void doFinish(...)
public void launch( ILaunchConfiguration configuration, String mode, ILaunch launch, IProgressMonitor monitor) throws CoreException { if (monitor.isCanceled()) { DebugPlugin.getDefault().getLaunchManager().removeLaunch(launch); return; } PHPexeItem phpExeItem = PHPLaunchUtilities.getPHPExe(configuration); if (phpExeItem == null) { Logger.log(Logger.ERROR, "Launch configuration could not find PHP exe item"); // $NON-NLS-1$ monitor.setCanceled(true); monitor.done(); return; } // get the launch info: php exe, php ini final String phpExeString = configuration.getAttribute(IPHPDebugConstants.ATTR_EXECUTABLE_LOCATION, (String) null); final String phpIniString = configuration.getAttribute(IPHPDebugConstants.ATTR_INI_LOCATION, (String) null); final String phpScriptString = configuration.getAttribute(IPHPDebugConstants.ATTR_FILE, (String) null); if (phpScriptString == null || phpScriptString.trim().length() == 0) { DebugPlugin.getDefault().getLaunchManager().removeLaunch(launch); displayErrorMessage(PHPDebugCoreMessages.XDebug_ExeLaunchConfigurationDelegate_0); return; } if (monitor.isCanceled()) { DebugPlugin.getDefault().getLaunchManager().removeLaunch(launch); return; } // locate the project from the php script final IWorkspaceRoot workspaceRoot = ResourcesPlugin.getWorkspace().getRoot(); final IPath filePath = new Path(phpScriptString); final IResource scriptRes = workspaceRoot.findMember(filePath); if (scriptRes == null) { DebugPlugin.getDefault().getLaunchManager().removeLaunch(launch); displayErrorMessage(PHPDebugCoreMessages.XDebug_ExeLaunchConfigurationDelegate_1); return; } // resolve php exe location final IPath phpExe = new Path(phpExeString); // resolve project directory IProject project = scriptRes.getProject(); // Set Project Name as this is required by the source lookup computer // delegate final String projectString = project.getFullPath().toString(); ILaunchConfigurationWorkingCopy wc = null; if (configuration.isWorkingCopy()) { wc = (ILaunchConfigurationWorkingCopy) configuration; } else { wc = configuration.getWorkingCopy(); } wc.setAttribute(IPHPDebugConstants.PHP_Project, projectString); wc.setAttribute( IDebugParametersKeys.TRANSFER_ENCODING, PHPProjectPreferences.getTransferEncoding(project)); wc.setAttribute( IDebugParametersKeys.OUTPUT_ENCODING, PHPProjectPreferences.getOutputEncoding(project)); wc.doSave(); if (monitor.isCanceled()) { DebugPlugin.getDefault().getLaunchManager().removeLaunch(launch); return; } IPath projectLocation = project.getRawLocation(); if (projectLocation == null) { projectLocation = project.getLocation(); } // resolve the script location, but not relative to anything IPath phpFile = scriptRes.getLocation(); if (monitor.isCanceled()) { DebugPlugin.getDefault().getLaunchManager().removeLaunch(launch); return; } // Resolve the PHP ini location // Locate the php ini by using the attribute. If the attribute was null, // try to locate an ini that exists next to the executable. File phpIni = (phpIniString != null && new File(phpIniString).exists()) ? new File(phpIniString) : PHPINIUtil.findPHPIni(phpExeString); File tempIni = PHPINIUtil.prepareBeforeLaunch(phpIni, phpExeString, project); launch.setAttribute(IDebugParametersKeys.PHP_INI_LOCATION, tempIni.getAbsolutePath()); // add process type to process attributes, basically the name of the exe // that was launched final Map<String, String> processAttributes = new HashMap<String, String>(); String programName = phpExe.lastSegment(); final String extension = phpExe.getFileExtension(); if (extension != null) { programName = programName.substring(0, programName.length() - (extension.length() + 1)); } programName = programName.toLowerCase(); // used by the console colorer extension to determine what class to use // should allow the console color providers and line trackers to work // process.setAttribute(IProcess.ATTR_PROCESS_TYPE, // IPHPConstants.PHPProcessType); processAttributes.put(IProcess.ATTR_PROCESS_TYPE, programName); // used by the Console to give that console a name processAttributes.put(IProcess.ATTR_CMDLINE, phpScriptString); if (monitor.isCanceled()) { DebugPlugin.getDefault().getLaunchManager().removeLaunch(launch); return; } // determine the environment variables String[] envVarString = null; DBGpTarget target = null; if (mode.equals(ILaunchManager.DEBUG_MODE)) { // check the launch for stop at first line, if not there go to // project specifics boolean stopAtFirstLine = PHPProjectPreferences.getStopAtFirstLine(project); stopAtFirstLine = configuration.getAttribute(IDebugParametersKeys.FIRST_LINE_BREAKPOINT, stopAtFirstLine); String sessionID = DBGpSessionHandler.getInstance().generateSessionId(); String ideKey = null; if (phpExeItem != null) { DBGpProxyHandler proxyHandler = DBGpProxyHandlersManager.INSTANCE.getHandler(phpExeItem.getUniqueId()); if (proxyHandler != null && proxyHandler.useProxy()) { ideKey = proxyHandler.getCurrentIdeKey(); if (proxyHandler.registerWithProxy() == false) { displayErrorMessage( PHPDebugCoreMessages.XDebug_ExeLaunchConfigurationDelegate_2 + proxyHandler.getErrorMsg()); DebugPlugin.getDefault().getLaunchManager().removeLaunch(launch); return; } } else { ideKey = DBGpSessionHandler.getInstance().getIDEKey(); } } target = new DBGpTarget(launch, phpFile.lastSegment(), ideKey, sessionID, stopAtFirstLine); target.setPathMapper(PathMapperRegistry.getByLaunchConfiguration(configuration)); DBGpSessionHandler.getInstance().addSessionListener(target); envVarString = createDebugLaunchEnvironment(configuration, sessionID, ideKey, phpExe); int requestPort = getDebugPort(phpExeItem); // Check that the debug daemon is functional // DEBUGGER - Make sure that the active debugger id is indeed Zend's // debugger if (!PHPLaunchUtilities.isDebugDaemonActive( requestPort, XDebugCommunicationDaemon.XDEBUG_DEBUGGER_ID)) { PHPLaunchUtilities.showLaunchErrorMessage( NLS.bind( PHPDebugCoreMessages.ExeLaunchConfigurationDelegate_PortInUse, requestPort, phpExeItem.getName())); monitor.setCanceled(true); monitor.done(); return; } } else { envVarString = PHPLaunchUtilities.getEnvironment(configuration, new String[] {getLibraryPath(phpExe)}); } IProgressMonitor subMonitor = new SubProgressMonitor(monitor, 30); subMonitor.beginTask(PHPDebugCoreMessages.XDebug_ExeLaunchConfigurationDelegate_3, 10); // determine the working directory. default is the location of the // script IPath workingPath = phpFile.removeLastSegments(1); File workingDir = workingPath.makeAbsolute().toFile(); boolean found = false; for (int i = 0; i < envVarString.length && !found; i++) { String envEntity = envVarString[i]; String[] elements = envEntity.split("="); // $NON-NLS-1$ if (elements.length > 0 && elements[0].equals("XDEBUG_WORKING_DIR")) { // $NON-NLS-1$ found = true; workingPath = new Path(elements[1]); File temp = workingPath.makeAbsolute().toFile(); if (temp.exists()) { workingDir = temp; } } } // Detect PHP SAPI type and thus where we need arguments File phpExeFile = new File(phpExeString); String sapiType = null; String phpV = null; PHPexeItem[] items = PHPexes.getInstance().getAllItems(); for (PHPexeItem item : items) { if (item.getExecutable().equals(phpExeFile)) { sapiType = item.getSapiType(); phpV = item.getVersion(); break; } } String[] args = null; if (PHPexeItem.SAPI_CLI.equals(sapiType)) { args = PHPLaunchUtilities.getProgramArguments(launch.getLaunchConfiguration()); } // define the command line for launching String[] cmdLine = null; cmdLine = PHPLaunchUtilities.getCommandLine( configuration, phpExe.toOSString(), tempIni.toString(), phpFile.toOSString(), args, phpV); // Launch the process final Process phpExeProcess = DebugPlugin.exec(cmdLine, workingDir, envVarString); // Attach a crash detector new Thread(new ProcessCrashDetector(launch, phpExeProcess)).start(); IProcess eclipseProcessWrapper = null; if (phpExeProcess != null) { subMonitor.worked(10); eclipseProcessWrapper = DebugPlugin.newProcess(launch, phpExeProcess, phpExe.toOSString(), processAttributes); if (eclipseProcessWrapper == null) { // another error so we stop everything somehow phpExeProcess.destroy(); subMonitor.done(); DebugPlugin.getDefault().getLaunchManager().removeLaunch(launch); throw new CoreException(new Status(IStatus.ERROR, PHPDebugPlugin.ID, 0, null, null)); } // if launching in debug mode, create the debug infrastructure and // link it with the launched process if (mode.equals(ILaunchManager.DEBUG_MODE) && target != null) { target.setProcess(eclipseProcessWrapper); launch.addDebugTarget(target); subMonitor.subTask(PHPDebugCoreMessages.XDebug_ExeLaunchConfigurationDelegate_4); target.waitForInitialSession( (DBGpBreakpointFacade) IDELayerFactory.getIDELayer(), XDebugPreferenceMgr.createSessionPreferences(), monitor); } } else { // we did not launch if (mode.equals(ILaunchManager.DEBUG_MODE)) { DBGpSessionHandler.getInstance().removeSessionListener(target); } DebugPlugin.getDefault().getLaunchManager().removeLaunch(launch); } subMonitor.done(); }
@Override protected void doSaveDocument( IProgressMonitor monitor, Object element, IDocument document, boolean overwrite) throws CoreException { try { IStorage storage = EditorUtils.getStorageFromInput(element); File localFile = null; if (storage == null) { localFile = EditorUtils.getLocalFileFromInput(element); if (localFile == null) { throw new DBException("Can't obtain file from editor input"); } } String encoding = (storage instanceof IEncodedStorage ? ((IEncodedStorage) storage).getCharset() : GeneralUtils.DEFAULT_FILE_CHARSET_NAME); Charset charset = Charset.forName(encoding); CharsetEncoder encoder = charset.newEncoder(); encoder.onMalformedInput(CodingErrorAction.REPLACE); encoder.onUnmappableCharacter(CodingErrorAction.REPORT); byte[] bytes; ByteBuffer byteBuffer = encoder.encode(CharBuffer.wrap(document.get())); if (byteBuffer.hasArray()) { bytes = byteBuffer.array(); } else { bytes = new byte[byteBuffer.limit()]; byteBuffer.get(bytes); } InputStream stream = new ByteArrayInputStream(bytes, 0, byteBuffer.limit()); if (storage instanceof IFile) { IFile file = (IFile) storage; if (file.exists()) { // inform about the upcoming content change fireElementStateChanging(element); try { file.setContents(stream, true, true, monitor); } catch (CoreException x) { // inform about failure fireElementStateChangeFailed(element); throw x; } catch (RuntimeException x) { // inform about failure fireElementStateChangeFailed(element); throw x; } } else { try { monitor.beginTask("Save file '" + file.getName() + "'", 2000); // ContainerCreator creator = new ContainerCreator(file.getWorkspace(), // file.getParent().getFullPath()); // creator.createContainer(new SubProgressMonitor(monitor, 1000)); file.create(stream, false, monitor); } finally { monitor.done(); } } } else if (storage instanceof IPersistentStorage) { monitor.beginTask("Save document", 1); ((IPersistentStorage) storage).setContents(monitor, stream); } else if (localFile != null) { try (OutputStream os = new FileOutputStream(localFile)) { IOUtils.copyStream(stream, os); } } else { throw new DBException("Storage [" + storage + "] doesn't support save"); } } catch (Exception e) { if (e instanceof CoreException) { throw (CoreException) e; } else { throw new CoreException(GeneralUtils.makeExceptionStatus(e)); } } }
/** * Indicate completion of monitor activity. * * @see IProgressMonitor#done() * @since 2.0 */ public void done() { monitor.done(); }
@Override public void create(InputStream content, int updateFlags, IProgressMonitor monitor) throws CoreException { final boolean monitorNull = monitor == null; monitor = Policy.monitorFor(monitor); try { String message = monitorNull ? "" : NLS.bind(Messages.resources_creating, getFullPath()); // $NON-NLS-1$ monitor.beginTask(message, Policy.totalWork); checkValidPath(path, FILE, true); final ISchedulingRule rule = workspace.getRuleFactory().createRule(this); try { workspace.prepareOperation(rule, monitor); checkDoesNotExist(); Container parent = (Container) getParent(); ResourceInfo info = parent.getResourceInfo(false, false); parent.checkAccessible(getFlags(info)); checkValidGroupContainer(parent, false, false); workspace.beginOperation(true); IFileStore store = getStore(); IFileInfo localInfo = store.fetchInfo(); if (BitMask.isSet(updateFlags, IResource.FORCE)) { if (!Workspace.caseSensitive) { if (localInfo.exists()) { String name = getLocalManager().getLocalName(store); if (name == null || localInfo.getName().equals(name)) { delete(true, null); } else { // The file system is not case sensitive and there is already a file // under this location. message = NLS.bind( Messages.resources_existsLocalDifferentCase, new Path(store.toString()).removeLastSegments(1).append(name).toOSString()); throw new ResourceException( IResourceStatus.CASE_VARIANT_EXISTS, getFullPath(), message, null); } } } } else { if (localInfo.exists()) { // return an appropriate error message for case variant collisions if (!Workspace.caseSensitive) { String name = getLocalManager().getLocalName(store); if (name != null && !localInfo.getName().equals(name)) { message = NLS.bind( Messages.resources_existsLocalDifferentCase, new Path(store.toString()).removeLastSegments(1).append(name).toOSString()); throw new ResourceException( IResourceStatus.CASE_VARIANT_EXISTS, getFullPath(), message, null); } } message = NLS.bind(Messages.resources_fileExists, store.toString()); throw new ResourceException( IResourceStatus.FAILED_WRITE_LOCAL, getFullPath(), message, null); } } monitor.worked(Policy.opWork * 40 / 100); info = workspace.createResource(this, updateFlags); boolean local = content != null; if (local) { try { internalSetContents( content, localInfo, updateFlags, false, Policy.subMonitorFor(monitor, Policy.opWork * 60 / 100)); } catch (CoreException e) { // a problem happened creating the file on disk, so delete from the workspace and disk workspace.deleteResource(this); store.delete(EFS.NONE, null); throw e; // rethrow } catch (OperationCanceledException e) { // the operation of setting contents has been canceled, so delete the file from the // workspace and disk workspace.deleteResource(this); store.delete(EFS.NONE, null); throw e; } } internalSetLocal(local, DEPTH_ZERO); if (!local) getResourceInfo(true, true).clearModificationStamp(); } catch (OperationCanceledException e) { workspace.getWorkManager().operationCanceled(); throw e; } finally { workspace.endOperation(rule, true, Policy.subMonitorFor(monitor, Policy.endOpWork)); } } finally { monitor.done(); FileUtil.safeClose(content); } }
private void createProject(IFeatureModel model, IProgressMonitor monitor) throws CoreException { String name = model.getFeature().getId(); IFeaturePlugin[] plugins = model.getFeature().getPlugins(); for (int i = 0; i < plugins.length; i++) { if (name.equals(plugins[i].getId())) { name += "-feature"; // $NON-NLS-1$ break; } } String task = NLS.bind(MDEUIMessages.FeatureImportWizard_operation_creating2, name); monitor.beginTask(task, 9); try { IProject project = fRoot.getProject(name); if (project.exists() || new File(project.getParent().getLocation().toFile(), name).exists()) { if (queryReplace(project)) { if (!project.exists()) project.create(new SubProgressMonitor(monitor, 1)); project.delete(true, true, new SubProgressMonitor(monitor, 1)); try { RepositoryProvider.unmap(project); } catch (TeamException e) { } } else { return; } } else { monitor.worked(1); } IProjectDescription description = MDEPlugin.getWorkspace().newProjectDescription(name); if (fTargetPath != null) description.setLocation(fTargetPath.append(name)); project.create(description, new SubProgressMonitor(monitor, 1)); if (!project.isOpen()) { project.open(null); } File featureDir = new File(model.getInstallLocation()); importContent( featureDir, project.getFullPath(), FileSystemStructureProvider.INSTANCE, null, new SubProgressMonitor(monitor, 1)); IFolder folder = project.getFolder("META-INF"); // $NON-NLS-1$ if (folder.exists()) { folder.delete(true, null); } if (fBinary) { // Mark this project so that we can show image overlay // using the label decorator project.setPersistentProperty( MDECore.EXTERNAL_PROJECT_PROPERTY, MDECore.BINARY_PROJECT_VALUE); } createBuildProperties(project); setProjectNatures(project, model, monitor); if (project.hasNature(JavaCore.NATURE_ID)) setClasspath(project, model, monitor); } finally { monitor.done(); } }