// We need this as a separate method, as we'll put dependent projects' output // on the classpath private static void addProjectClasspath( IWorkspaceRoot root, IJavaProject otherJavaProject, Set<IJavaProject> projectsProcessed, Set<String> classpath) { // Check for cycles. If we've already seen this project, // no need to go any further. if (projectsProcessed.contains(otherJavaProject)) { return; } projectsProcessed.add(otherJavaProject); try { // Add the output directory first as a binary entry for other projects IPath binPath = otherJavaProject.getOutputLocation(); IResource binPathResource = root.findMember(binPath); String binDirString; if (binPathResource != null) { binDirString = root.findMember(binPath).getLocation().toOSString(); } else { binDirString = binPath.toOSString(); } classpath.add(binDirString); // Now the rest of the classpath IClasspathEntry[] classpathEntries = otherJavaProject.getResolvedClasspath(true); for (IClasspathEntry entry : classpathEntries) { if (entry.getEntryKind() == IClasspathEntry.CPE_LIBRARY) { IPath cpPath = entry.getPath(); IResource res = root.findMember(cpPath); // If res is null, the path is absolute (it's an external jar) if (res == null) { classpath.add(cpPath.toOSString()); } else { // It's relative classpath.add(res.getLocation().toOSString()); } } else if (entry.getEntryKind() == IClasspathEntry.CPE_PROJECT) { IPath otherProjectPath = entry.getPath(); IProject otherProject = root.getProject(otherProjectPath.segment(0)); IJavaProject yetAnotherJavaProject = JavaCore.create(otherProject); if (yetAnotherJavaProject != null) { addProjectClasspath(root, yetAnotherJavaProject, projectsProcessed, classpath); } } // Ignore source types } } catch (JavaModelException jme) { AptPlugin.log( jme, "Failed to get the classpath for the following project: " + otherJavaProject); //$NON-NLS-1$ } }
private void setClassLoader() { IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot(); IJavaProject javaProject = getJavaProject(); try { if (javaProject != null) { List<URL> entries = new ArrayList<URL>(); IPath path = javaProject.getOutputLocation(); IResource iResource = root.findMember(path); path = iResource.getLocation(); path = path.addTrailingSeparator(); entries.add(path.toFile().toURL()); IClasspathEntry[] cpEntries = javaProject.getRawClasspath(); for (IClasspathEntry cpEntry : cpEntries) { switch (cpEntry.getEntryKind()) { case IClasspathEntry.CPE_SOURCE: path = cpEntry.getOutputLocation(); if (path != null) { iResource = root.findMember(path); path = iResource.getLocation(); path = path.addTrailingSeparator(); entries.add(path.toFile().toURL()); } break; case IClasspathEntry.CPE_LIBRARY: iResource = root.findMember(cpEntry.getPath()); if (iResource == null) { // resource is not in workspace, must be an external JAR path = cpEntry.getPath(); } else { path = iResource.getLocation(); } entries.add(path.toFile().toURL()); break; } } ClassLoader oldCl = Thread.currentThread().getContextClassLoader(); URL[] entryArray = new URL[entries.size()]; entries.toArray(entryArray); ClassLoader newCl = new URLClassLoader(entryArray, oldCl); Thread.currentThread().setContextClassLoader(newCl); oldClassLoader = oldCl; } } catch (Exception e) { // ignore - something too complex is wrong ; } }
/** * @see * com.aptana.jaxer.connectors.servlet.interfaces.IDocumentRootResolver#getDocumentRoot(javax.servlet.ServletRequest, * javax.servlet.ServletResponse) */ public String getDocumentRoot(ServletRequest request, ServletResponse res) { String path = null; try { if (request instanceof HttpServletRequest) { path = ((HttpServletRequest) request).getServletPath(); String ref = ((HttpServletRequest) request).getHeader("Referer"); // $NON-NLS-1$ IProject project = null; if (ref != null) { URL url = new URL(ref); String refPath = url.getPath(); IResource resource = workspaceRoot.findMember(new Path(refPath)); if (resource != null) { project = resource.getProject(); } else { resource = workspaceRoot.findMember(new Path(path)); if (resource != null && resource instanceof IFile) { project = resource.getProject(); } } } else { IResource resource = workspaceRoot.findMember(new Path(path)); if (resource != null && resource instanceof IFile) { project = resource.getProject(); } } if (project != null) { String override = project.getPersistentProperty( new QualifiedName( "", //$NON-NLS-1$ HTMLPreviewConstants.HTML_PREVIEW_OVERRIDE)); if (HTMLPreviewConstants.TRUE.equals(override)) { String contextRoot = project.getPersistentProperty( new QualifiedName( "", //$NON-NLS-1$ HTMLPreviewConstants.CONTEXT_ROOT)); IResource root = project.findMember(new Path(contextRoot)); path = root.getLocation().makeAbsolute().toString(); } else { path = project.getLocation().makeAbsolute().toString(); } } } } catch (Exception e) { path = null; } return path; }
private String formatFileName(String fileName) { String formatFile = null; IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot(); IResource resource = root.findMember(fileName); if (resource == null) { return fileName; } basePath = getBasePath(resource.getProject()); if (basePath == null && resource.getProject() != null) basePath = resource.getProject().getName(); else if (basePath == null && resource.getProject() == null) { basePath = ""; // $NON-NLS-1$ } int type = resource.getType(); if (type == IResource.FILE || type == IResource.FOLDER) { formatFile = basePath + "/" //$NON-NLS-1$ + resource.getFullPath().removeFirstSegments(1).toString(); } else { formatFile = basePath + "/"; // $NON-NLS-1$ } if (!formatFile.startsWith("/")) { // $NON-NLS-1$ formatFile = basePath + "/" + formatFile; // $NON-NLS-1$ } return formatFile; }
public static void initialiseProject(IProject project) { if (!project.isOpen()) throw new IllegalArgumentException("Project is not open!"); ModelManager manager = ModelManager.modelManager(); IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot(); try { String property = project.getPersistentProperty(MODELS_KEY); if (property == null || property.trim().equals("")) return; for (String path : property.split(";")) { IResource resource = root.findMember(fromPortableString(path)); if (!(resource instanceof IFile)) { continue; } // EventLogger.getInstance().logModelInitBegin(resource); ArchitectureModel model = manager.getArchitectureModel((IFile) resource); // model.addModelListener(new ModelEventListener(EventLogger.getInstance())); // EventLogger.getInstance().logModelInitEnd(resource); // This will crate an instance of problem manager... ModelProblemManager pm = problemManager(model); pm.attachToProject(project); } } catch (CoreException e) { e.printStackTrace(); } }
private String checkValidSourceFolder(String text) throws CoreException { validatedSourceFolder = null; if (text == null || text.trim().length() == 0) { return "The source folder must be filled."; } IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot(); IResource resource = root.findMember(new Path(text)); if (resource == null) { return "The source folder was not found in the workspace."; } if (!(resource instanceof IContainer)) { return "The source folder was found in the workspace but is not a container."; } IProject project = resource.getProject(); if (project == null) { return "Unable to find the project related to the source folder."; } IPythonPathNature nature = PythonNature.getPythonPathNature(project); if (nature == null) { return "The pydev nature is not configured on the project: " + project.getName(); } String full = resource.getFullPath().toString(); String[] srcPaths = PythonNature.getStrAsStrItems(nature.getProjectSourcePath(true)); for (String str : srcPaths) { if (str.equals(full)) { validatedSourceFolder = (IContainer) resource; return null; } } return "The selected source folder is not recognized as a valid source folder."; }
/** * The worker method. It will find the container, create the file if missing or just replace its * contents, and open the editor on the newly created file. */ private void doFinish( String containerName, String fileName, String name, String description, IProgressMonitor monitor) throws CoreException { // create a sample file monitor.beginTask("Creating " + fileName, 2); IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot(); IResource resource = root.findMember(new Path(containerName)); if (!resource.exists() || !(resource instanceof IContainer)) { throwCoreException("Container \"" + containerName + "\" does not exist."); } IContainer container = (IContainer) resource; final IFile file = container.getFile(new Path(fileName)); try { Test emptyTest = createEmptyTest(name, description); String xml = new CubicTestXStream().toXML(emptyTest); FileUtils.writeStringToFile(file.getLocation().toFile(), xml, "ISO-8859-1"); file.getParent().refreshLocal(IResource.DEPTH_INFINITE, null); } catch (IOException e) { ErrorHandler.logAndRethrow(e); } monitor.worked(1); if (openCreatedTestOnFinish) { openFileForEditing(monitor, file); } }
protected String checkValidPackage(String text) { validatedPackage = null; packageText = null; // there is a chance that the package is the default project, so, the validation below may not // be valid. // if(text == null || text.trim().length() == 0 ){ // } String initialText = text; if (text.indexOf('/') != -1) { labelWarningImageWillCreate.setVisible(false); labelWarningWillCreate.setVisible(false); labelWarningWillCreate.getParent().layout(); return "The package name must not contain '/'."; } if (text.indexOf('\\') != -1) { labelWarningImageWillCreate.setVisible(false); labelWarningWillCreate.setVisible(false); labelWarningWillCreate.getParent().layout(); return "The package name must not contain '\\'."; } if (text.endsWith(".")) { labelWarningImageWillCreate.setVisible(false); labelWarningWillCreate.setVisible(false); labelWarningWillCreate.getParent().layout(); return "The package may not end with a dot"; } text = text.replace('.', '/'); if (validatedSourceFolder == null) { labelWarningImageWillCreate.setVisible(false); labelWarningWillCreate.setVisible(false); labelWarningWillCreate.getParent().layout(); return "The source folder was not correctly validated."; } IPath path = validatedSourceFolder.getFullPath().append(text); IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot(); IResource resource = root.findMember(path); if (resource == null) { packageText = initialText; labelWarningImageWillCreate.setVisible(true); labelWarningWillCreate.setVisible(true); labelWarningWillCreate.getParent().layout(); return null; } labelWarningImageWillCreate.setVisible(false); labelWarningWillCreate.setVisible(false); labelWarningWillCreate.getParent().layout(); if (!(resource instanceof IContainer)) { return "The resource found for the package is not a valid container."; } if (!resource.exists()) { return "The package selected does not exist in the filesystem."; } validatedPackage = (IContainer) resource; return null; }
public ExclusionInclusionEntryDialog( Shell parent, boolean isExclusion, String patternToEdit, List existingPatterns, CPListElement entryToEdit) { super(parent); fIsExclusion = isExclusion; fExistingPatterns = existingPatterns; String title, message; if (isExclusion) { if (patternToEdit == null) { title = NewWizardMessages.ExclusionInclusionEntryDialog_exclude_add_title; } else { title = NewWizardMessages.ExclusionInclusionEntryDialog_exclude_edit_title; } message = Messages.format( NewWizardMessages.ExclusionInclusionEntryDialog_exclude_pattern_label, BasicElementLabels.getPathLabel(entryToEdit.getPath(), false)); } else { if (patternToEdit == null) { title = NewWizardMessages.ExclusionInclusionEntryDialog_include_add_title; } else { title = NewWizardMessages.ExclusionInclusionEntryDialog_include_edit_title; } message = Messages.format( NewWizardMessages.ExclusionInclusionEntryDialog_include_pattern_label, BasicElementLabels.getPathLabel(entryToEdit.getPath(), false)); } setTitle(title); if (patternToEdit != null) { fExistingPatterns.remove(patternToEdit); } IWorkspaceRoot root = entryToEdit.getJavaProject().getProject().getWorkspace().getRoot(); IResource res = root.findMember(entryToEdit.getPath()); if (res instanceof IContainer) { fCurrSourceFolder = (IContainer) res; } fExclusionPatternStatus = new StatusInfo(); ExclusionPatternAdapter adapter = new ExclusionPatternAdapter(); fExclusionPatternDialog = new StringButtonDialogField(adapter); fExclusionPatternDialog.setLabelText(message); fExclusionPatternDialog.setButtonLabel( NewWizardMessages.ExclusionInclusionEntryDialog_pattern_button); fExclusionPatternDialog.setDialogFieldListener(adapter); fExclusionPatternDialog.enableButton(fCurrSourceFolder != null); if (patternToEdit == null) { fExclusionPatternDialog.setText(""); // $NON-NLS-1$ } else { fExclusionPatternDialog.setText(patternToEdit.toString()); } }
public void setFiles(String[] fileNames) { int size = Arrays.asList(fileNames).size(); Vector iFileNames = new Vector(); for (int i = 0; i < size; i++) { IResource resource = workspaceRoot.findMember(fileNames[i]); if (resource instanceof IFile) iFileNames.addElement(resource); } IFile[] dummyArray = new IFile[iFileNames.size()]; this.fileNames = (IFile[]) (iFileNames.toArray(dummyArray)); }
protected static AssemblyInstance loadnewICM(String filename) { // There may be other ways of loading the file IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot(); IResource resource = root.findMember(new Path(filename)); IContainer container = (IContainer) resource; IFile ifile = container.getFile(new Path(filename)); // This is the method provided by the ReasoningFramework API AssemblyInstance assembly = ReasoningFramework.loadConstructiveAssembly(ifile); return (assembly); }
public static boolean refreshLocal(IWorkbenchWindow window, String param) { try { IWorkspaceRoot workspaceRoot = ResourcesPlugin.getWorkspace().getRoot(); IResource resource = workspaceRoot.findMember(param); // refresh resource resource.refreshLocal(IResource.DEPTH_INFINITE, monitor); } catch (Exception e) { e.printStackTrace(); return false; } return true; }
/** * @see * com.aptana.jaxer.connectors.servlet.interfaces.IDocumentRootResolver#getPageFile(javax.servlet.ServletRequest, * javax.servlet.ServletResponse) */ public String getPageFile(ServletRequest request, ServletResponse response) { String path = null; try { if (request instanceof HttpServletRequest) { path = ((HttpServletRequest) request).getServletPath(); String ref = ((HttpServletRequest) request).getHeader("Referer"); // $NON-NLS-1$ if (ref != null) { URL url = new URL(ref); String refPath = url.getPath(); IResource resource = workspaceRoot.findMember(new Path(refPath)); if (resource != null) { IProject project = resource.getProject(); path = HTMLContextRootUtils.resolveURL(project, path); IResource candidate = workspaceRoot.findMember(new Path(path)); if (candidate != null && candidate.getProject().equals(project) && candidate instanceof IFile) { path = candidate.getLocation().makeAbsolute().toString(); } else { candidate = project.findMember(new Path(path)); if (candidate != null && candidate.getProject().equals(project) && candidate instanceof IFile) { path = candidate.getLocation().makeAbsolute().toString(); } } } } else { IResource resource = workspaceRoot.findMember(new Path(path)); if (resource != null && resource instanceof IFile) { path = resource.getLocation().makeAbsolute().toString(); } } } } catch (Exception e) { path = null; } return path; }
private boolean isVirtualTypeResource(IResource fileSystemLoc) { IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot(); IResource resource = root.findMember(fileSystemLoc.getFullPath()); if (resource != null) { URI location = resource.getLocationURI(); if (location != null) { if (location.getScheme().equals("typespace")) { return true; } } } return false; }
private void renameResource() { try { String newName = queryNewResourceName(resSelectedResource); if (newName == null || newName.equals("")) // $NON-NLS-1$ return; IPath newPath = resSelectedResource.getFullPath().removeLastSegments(1).append(newName); IWorkspaceRoot workspaceRoot = resSelectedResource.getWorkspace().getRoot(); IProgressMonitor monitor = new NullProgressMonitor(); IResource newResource = workspaceRoot.findMember(newPath); IWorkbenchPage iwbp = getIWorkbenchPage(); // determine if file open in workspace... boolean wasOpen = isEditorOpen(iwbp, resSelectedResource); // do the move: if (newResource != null) { if (checkOverwrite(getShell(), newResource)) { if (resSelectedResource.getType() == IResource.FILE && newResource.getType() == IResource.FILE) { IFile file = (IFile) resSelectedResource; IFile newFile = (IFile) newResource; // need to check for the case that a file we are overwriting is open, // and re-open it if it is, regardless of whether the old file was open wasOpen = isEditorOpen(iwbp, newResource); if (validateEdit(file, newFile, getShell())) { newFile.setContents(file.getContents(), IResource.KEEP_HISTORY, monitor); file.delete(IResource.KEEP_HISTORY, monitor); } } } } else { resSelectedResource.move( newPath, IResource.KEEP_HISTORY | IResource.SHALLOW, new SubProgressMonitor(monitor, 50)); } reOpenEditor(wasOpen, newName, iwbp); } catch (CoreException err) { ModelerCore.Util.log(IStatus.ERROR, err, err.getMessage()); } }
/** Writes the given contents to a file with the given fileName in the specified project. */ public void writeContent() { String contents = generateSpecfile(); InputStream contentInputStream = new ByteArrayInputStream(contents.getBytes()); IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot(); IResource resource = root.findMember(new Path(projectName)); if (!resource.exists() || !(resource instanceof IContainer)) { IStatus status = new Status( IStatus.ERROR, StubbyPlugin.PLUGIN_ID, IStatus.OK, "Project \"" + projectName + "\" does not exist.", null); StubbyLog.logError(new CoreException(status)); } IContainer container = (IContainer) resource; IResource specsFolder = container.getProject().findMember("SPECS"); // $NON-NLS-1$ IFile file = container.getFile(new Path(specfileName)); if (specsFolder != null) { file = ((IFolder) specsFolder).getFile(new Path(specfileName)); } final IFile openFile = file; try { InputStream stream = contentInputStream; if (file.exists()) { file.setContents(stream, true, true, null); } else { file.create(stream, true, null); } stream.close(); } catch (IOException e) { StubbyLog.logError(e); } catch (CoreException e) { StubbyLog.logError(e); } Display.getCurrent() .asyncExec( new Runnable() { public void run() { IWorkbenchPage page = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage(); try { IDE.openEditor(page, openFile, true); } catch (PartInitException e) { StubbyLog.logError(e); } } }); }
public IProject getTargetProject() { IProject result = null; String containerName = getContainerName(); if (!CoreStringUtil.isEmpty(containerName)) { IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot(); IResource resource = root.findMember(new Path(containerName)); if (resource.exists()) { result = resource.getProject(); } } return result; }
/** Convenience method to copy resources. */ protected void copyResources(IResource[] resources, IPath container) throws DartModelException { IProgressMonitor subProgressMonitor = getSubProgressMonitor(resources.length); IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot(); try { for (int i = 0, length = resources.length; i < length; i++) { IResource resource = resources[i]; IPath destination = container.append(resource.getName()); if (root.findMember(destination) == null) { resource.copy(destination, false, subProgressMonitor); } } setAttribute(HAS_MODIFIED_RESOURCE_ATTR, TRUE); } catch (CoreException e) { throw new DartModelException(e); } }
public static void saveToModelFile(final EObject obj, final Diagram d) throws CoreException, IOException { URI uri = d.eResource().getURI(); uri = uri.trimFragment(); uri = uri.trimFileExtension(); uri = uri.appendFileExtension("model"); ResourceSet rSet = d.eResource().getResourceSet(); final IWorkspaceRoot workspaceRoot = ResourcesPlugin.getWorkspace().getRoot(); IResource file = workspaceRoot.findMember(uri.toPlatformString(true)); if (file == null || !file.exists()) { Resource createResource = rSet.createResource(uri); createResource.save(new HashMap()); createResource.setTrackingModification(true); } final Resource resource = rSet.getResource(uri, true); resource.getContents().add(obj); }
private void loadVersionAndRepID(IPath path) { IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot(); IResource res = root.findMember(path); IFile f = (IFile) res; try { BufferedReader d = new BufferedReader(new InputStreamReader(((IFile) res).getContents())); int bytein; StringBuffer strbuff = new StringBuffer(100); while ((bytein = d.read()) != -1) { strbuff.append((char) bytein); } version = strbuff.toString().trim(); d.close(); } catch (CoreException e) { } catch (IOException e1) { } }
/** * The worker method. It will find the container, create the file if missing or just replace its * contents, and open the editor on the newly created file. */ private void doFinish(String containerName, String fileName, IProgressMonitor monitor) throws CoreException { // create a sample file monitor.beginTask("Creating " + fileName, 2); IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot(); IResource resource = root.findMember(new Path(containerName)); // if (!(resource.exists()) || !(resource instanceof IContainer)) { if (resource == null || !(resource.exists()) || !(resource instanceof IContainer)) { // throwCoreException("Container \"" + containerName + // "\" does not exist."); IProject datamapperProject = root.getProject(containerName); datamapperProject.create(null); datamapperProject.open(null); // datamapperProject. } IContainer container = (IContainer) resource; // // // final IFile file = container.getFile(new Path(fileName)); // try { // InputStream stream = openContentStream(); // if (file.exists()) { // // file.setContents(null, true, true, monitor); // } else { // file.create(null, true, monitor); // // } // stream.close();` // } catch (IOException e) { // } // monitor.worked(1); // monitor.setTaskName("Opening file for editing..."); // getShell().getDisplay().asyncExec(new Runnable() { // public void run() { // IWorkbenchPage page = // PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage(); // try { // IDE.openEditor(page, file); // } catch (PartInitException e) { // } // } // }); // monitor.worked(1); }
public SetFilterWizardPage(BPListElement entryToEdit, ArrayList existingEntries) { super(PAGE_NAME); fExistingEntries = existingEntries; setTitle(NewWizardMessages.ExclusionInclusionDialog_title); setDescription(NewWizardMessages.ExclusionInclusionDialog_description2); fCurrElement = entryToEdit; fCurrProject = entryToEdit.getScriptProject().getProject(); IWorkspaceRoot root = fCurrProject.getWorkspace().getRoot(); IResource res = root.findMember(entryToEdit.getPath()); if (res instanceof IContainer) { fCurrSourceFolder = (IContainer) res; } String excLabel = NewWizardMessages.ExclusionInclusionDialog_exclusion_pattern_label; ImageDescriptor excDescriptor = DLTKPluginImages.DESC_OBJS_EXCLUSION_FILTER_ATTRIB; String[] excButtonLabels = new String[] { NewWizardMessages.ExclusionInclusionDialog_exclusion_pattern_add, NewWizardMessages.ExclusionInclusionDialog_exclusion_pattern_add_multiple, NewWizardMessages.ExclusionInclusionDialog_exclusion_pattern_edit, null, NewWizardMessages.ExclusionInclusionDialog_exclusion_pattern_remove }; String incLabel = NewWizardMessages.ExclusionInclusionDialog_inclusion_pattern_label; ImageDescriptor incDescriptor = DLTKPluginImages.DESC_OBJS_INCLUSION_FILTER_ATTRIB; String[] incButtonLabels = new String[] { NewWizardMessages.ExclusionInclusionDialog_inclusion_pattern_add, NewWizardMessages.ExclusionInclusionDialog_inclusion_pattern_add_multiple, NewWizardMessages.ExclusionInclusionDialog_inclusion_pattern_edit, null, NewWizardMessages.ExclusionInclusionDialog_inclusion_pattern_remove }; fExclusionPatternList = createListContents( entryToEdit, BPListElement.EXCLUSION, excLabel, excDescriptor, excButtonLabels); fInclusionPatternList = createListContents( entryToEdit, BPListElement.INCLUSION, incLabel, incDescriptor, incButtonLabels); }
private IFile getFileForPathImpl(IPath path, IProject project) { IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot(); if (path.isAbsolute()) { IFile c = root.getFileForLocation(path); return c; } if (project != null && project.exists()) { ICProject cproject = CoreModel.getDefault().create(project); if (cproject != null) { try { ISourceRoot[] roots = cproject.getAllSourceRoots(); for (ISourceRoot sourceRoot : roots) { IResource r = sourceRoot.getResource(); if (r instanceof IContainer) { IContainer parent = (IContainer) r; IResource res = parent.findMember(path); if (res != null && res.exists() && res instanceof IFile) { IFile file = (IFile) res; return file; } } } IOutputEntry entries[] = cproject.getOutputEntries(); for (IOutputEntry pathEntry : entries) { IPath p = pathEntry.getPath(); IResource r = root.findMember(p); if (r instanceof IContainer) { IContainer parent = (IContainer) r; IResource res = parent.findMember(path); if (res != null && res.exists() && res instanceof IFile) { IFile file = (IFile) res; return file; } } } } catch (CModelException _) { Activator.getDefault().getLog().log(_.getStatus()); } } } return null; }
/** * If the value starts with a path variable such as %ROOT%, replace it with the absolute path. * * @param value the value of a -Akey=value command option */ private static String resolveVarPath(IJavaProject jproj, String value) { if (value == null) { return null; } // is there a token to substitute? if (!Pattern.matches(PATHVAR_TOKEN, value)) { return value; } IPath path = new Path(value); String firstToken = path.segment(0); // If it matches %ROOT%/project, it is a project-relative path. if (PATHVAR_ROOT.equals(firstToken)) { IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot(); IResource proj = root.findMember(path.segment(1)); if (proj == null) { return value; } // all is well; do the substitution IPath relativePath = path.removeFirstSegments(2); IPath absoluteProjPath = proj.getLocation(); IPath absoluteResPath = absoluteProjPath.append(relativePath); return absoluteResPath.toOSString(); } // If it matches %PROJECT.DIR%/project, the path is relative to the current project. if (jproj != null && PATHVAR_PROJECTROOT.equals(firstToken)) { // all is well; do the substitution IPath relativePath = path.removeFirstSegments(1); IPath absoluteProjPath = jproj.getProject().getLocation(); IPath absoluteResPath = absoluteProjPath.append(relativePath); return absoluteResPath.toOSString(); } // otherwise it's a classpath-var-based path. String cpvName = firstToken.substring(1, firstToken.length() - 1); IPath cpvPath = JavaCore.getClasspathVariable(cpvName); if (cpvPath != null) { IPath resolved = cpvPath.append(path.removeFirstSegments(1)); return resolved.toOSString(); } else { return value; } }
/** Convenience method to move resources. */ protected void moveResources(IResource[] resources, IPath container) throws DartModelException { IProgressMonitor subProgressMonitor = null; if (progressMonitor != null) { subProgressMonitor = new SubProgressMonitor( progressMonitor, resources.length, SubProgressMonitor.PREPEND_MAIN_LABEL_TO_SUBTASK); } IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot(); try { for (int i = 0, length = resources.length; i < length; i++) { IResource resource = resources[i]; IPath destination = container.append(resource.getName()); if (root.findMember(destination) == null) { resource.move(destination, false, subProgressMonitor); } } setAttribute(HAS_MODIFIED_RESOURCE_ATTR, TRUE); } catch (CoreException exception) { throw new DartModelException(exception); } }
private void doFinish(String containerName, String fileName, IProgressMonitor monitor) throws CoreException { // create a sample file monitor.beginTask("Creating " + fileName, 2); IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot(); IResource resource = root.findMember(new Path(containerName)); if (!resource.exists() || !(resource instanceof IContainer)) { throwCoreException("Container \"" + containerName + "\" does not exist."); } IContainer container = (IContainer) resource; final IFile file = container.getFile(new Path(fileName)); try { InputStream stream = wizard.openContentStream(); if (file.exists()) { file.setContents(stream, true, true, monitor); } else { file.create(stream, true, monitor); } stream.close(); } catch (IOException e) { } monitor.worked(1); monitor.setTaskName("Opening file for editing..."); getShell() .getDisplay() .asyncExec( new Runnable() { public void run() { IWorkbenchPage page = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage(); try { IDE.openEditor(page, file, true); } catch (PartInitException e) { } } }); monitor.worked(1); }
private static void handleClasspathLibrary( IClasspathEntry e, IWorkspaceRoot wsRoot, Set<File> jarFiles) { // get the IPath IPath path = e.getPath(); IResource resource = wsRoot.findMember(path); if (SdkConstants.EXT_JAR.equalsIgnoreCase(path.getFileExtension())) { // case of a jar file (which could be relative to the workspace or a full path) if (resource != null && resource.exists() && resource.getType() == IResource.FILE) { jarFiles.add(new CPEFile(resource.getLocation().toFile(), e)); } else { // if the jar path doesn't match a workspace resource, // then we get an OSString and check if this links to a valid file. String osFullPath = path.toOSString(); File f = new CPEFile(osFullPath, e); if (f.isFile()) { jarFiles.add(f); } } } }
/** * Writes the given contents to a file with the given fileName in the specified project. * * @param projectName The name of the project to put the file into. * @throws CoreException Thrown when the project doesn't exist. */ public void writeContent(String projectName) throws CoreException { String fileName = model.getPackageName().toLowerCase() + ".spec"; String contents = generateSpecfile(); InputStream contentInputStream = new ByteArrayInputStream(contents.getBytes()); IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot(); IResource resource = root.findMember(new Path(projectName)); if (!resource.exists() || !(resource instanceof IContainer)) { throwCoreException("Project \"" + projectName + "\" does not exist."); } IContainer container = (IContainer) resource; final IFile file = container.getFile(new Path(fileName)); try { InputStream stream = contentInputStream; if (file.exists()) { file.setContents(stream, true, true, null); } else { file.create(stream, true, null); } stream.close(); } catch (IOException e) { StubbyLog.logError(e); } StubbyPlugin.getActiveWorkbenchShell() .getDisplay() .asyncExec( new Runnable() { public void run() { IWorkbenchPage page = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage(); try { IDE.openEditor(page, file, true); } catch (PartInitException e) { StubbyLog.logError(e); } } }); }
/** * @return a list of configuration errors and the interpreter info for the project (the * interpreter info can be null) * @throws PythonNatureWithoutProjectException */ public Tuple<List<ProjectConfigError>, IInterpreterInfo> getConfigErrorsAndInfo( final IProject relatedToProject) throws PythonNatureWithoutProjectException { if (IN_TESTS) { return new Tuple<List<ProjectConfigError>, IInterpreterInfo>( new ArrayList<ProjectConfigError>(), null); } ArrayList<ProjectConfigError> lst = new ArrayList<ProjectConfigError>(); if (this.project == null) { lst.add( new ProjectConfigError( relatedToProject, "The configured nature has no associated project.")); } IInterpreterInfo info = null; try { info = this.getProjectInterpreter(); String executableOrJar = info.getExecutableOrJar(); if (!new File(executableOrJar).exists()) { lst.add( new ProjectConfigError( relatedToProject, "The interpreter configured does not exist in the filesystem: " + executableOrJar)); } List<String> projectSourcePathSet = new ArrayList<String>(this.getPythonPathNature().getProjectSourcePathSet(true)); Collections.sort(projectSourcePathSet); IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot(); for (String path : projectSourcePathSet) { if (path.trim().length() > 0) { IPath p = new Path(path); IResource resource = root.findMember(p); if (resource == null) { relatedToProject.refreshLocal(p.segmentCount(), null); resource = root.findMember(p); // 2nd attempt (after refresh) } if (resource == null || !resource.exists()) { lst.add( new ProjectConfigError(relatedToProject, "Source folder: " + path + " not found")); } } } List<String> externalPaths = this.getPythonPathNature().getProjectExternalSourcePathAsList(true); Collections.sort(externalPaths); for (String path : externalPaths) { if (!new File(path).exists()) { lst.add( new ProjectConfigError( relatedToProject, "Invalid external source folder specified: " + path)); } } Tuple<String, String> versionAndError = getVersionAndError(); if (versionAndError.o2 != null) { lst.add( new ProjectConfigError( relatedToProject, StringUtils.replaceNewLines(versionAndError.o2, " "))); } } catch (MisconfigurationException e) { lst.add( new ProjectConfigError( relatedToProject, StringUtils.replaceNewLines(e.getMessage(), " "))); } catch (Throwable e) { lst.add( new ProjectConfigError( relatedToProject, StringUtils.replaceNewLines("Unexpected error:" + e.getMessage(), " "))); } return new Tuple<List<ProjectConfigError>, IInterpreterInfo>(lst, info); }
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(); }