Java Code Examples for org.eclipse.core.resources.IResource#getName()

The following examples show how to use org.eclipse.core.resources.IResource#getName() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: AbstractFileStore.java    From bonita-studio with GNU General Public License v2.0 6 votes vote down vote up
@Override
public IStatus export(final String targetAbsoluteFilePath) throws IOException {
    checkWritePermission(new File(targetAbsoluteFilePath));
    final IResource file = getResource();
    if (file != null) {
        final File to = new File(targetAbsoluteFilePath);
        to.mkdirs();
        final File target = new File(to, file.getName());
        if (target.exists()) {
            if (FileActionDialog.overwriteQuestion(file.getName())) {
                PlatformUtil.delete(target, Repository.NULL_PROGRESS_MONITOR);
            } else {
                return ValidationStatus.cancel("");
            }
        }
        PlatformUtil.copyResource(to, file.getLocation().toFile(), Repository.NULL_PROGRESS_MONITOR);
        return ValidationStatus.ok();
    }
    return ValidationStatus.error(String.format(Messages.failedToRetrieveResourceToExport, getName()));
}
 
Example 2
Source File: ImportConflictHandler.java    From tracecompass with Eclipse Public License 2.0 6 votes vote down vote up
private static String rename(IPath tracePath) {
    IResource existingResource = getExistingResource(tracePath);
    if (existingResource == null) {
        return tracePath.lastSegment();
    }

    // Not using IFolder on purpose to leave the door open to import
    // directly into an IProject
    IContainer folder = existingResource.getParent();

    int i = 2;
    while (true) {
        String name = existingResource.getName() + '(' + Integer.toString(i++) + ')';
        IResource resource = folder.findMember(name);
        if (resource == null) {
            return name;
        }
    }
}
 
Example 3
Source File: MassOpenHandler.java    From n4js with Eclipse Public License 1.0 6 votes vote down vote up
private void collectFiles(IContainer container, Set<String> names, Consumer<IFile> consumer) throws CoreException {
	final IResource[] members = container.members();
	for (IResource member : members) {
		if (member instanceof IContainer) {
			if (member instanceof IProject && !((IProject) member).isOpen()) {
				continue;
			}
			collectFiles((IContainer) member, names, consumer);
		} else if (member instanceof IFile) {
			final String fileName = member.getName();
			if (names.contains(fileName)) {
				consumer.accept((IFile) member);
			}
		}
	}
}
 
Example 4
Source File: TexBuilder.java    From texlipse with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Find a handle to the index file of this project.
 * @param project the current project
 * @param source buildable resource inside project 
 * @return handle to index file or null if not found.
 *         Returns null also if the index file is older than the current output file
 */
private IResource findIndex(IProject project, IResource source) {
    
    IContainer srcDir = TexlipseProperties.getProjectSourceDir(project);
    if (srcDir == null) {
        srcDir = project;
    }
    
    String name = source.getName();
    String idxName = name.substring(0, name.length() - source.getFileExtension().length()) + TexlipseProperties.INPUT_FORMAT_IDX;
    IResource idxFile = srcDir.findMember(idxName);
    if (idxFile == null) {
        return null;
    }
    
    IResource outFile = TexlipseProperties.getProjectOutputFile(project);
    if (outFile.getLocalTimeStamp() > idxFile.getLocalTimeStamp()) {
        return null;
    }
    
    return idxFile;
}
 
Example 5
Source File: TexBuilder.java    From texlipse with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Find a handle to the index file of this project.
 * @param project the current project
 * @param source buildable resource inside project 
 * @return handle to index file or null if not found.
 *         Returns null also if the index file is older than the current output file
 */
private IResource findNomencl(IProject project, IResource source) {
    
    IContainer srcDir = TexlipseProperties.getProjectSourceDir(project);
    if (srcDir == null) {
        srcDir = project;
    }

    String name = source.getName();
    String nomenclName = name.substring(0, name.length() - source.getFileExtension().length()) + TexlipseProperties.INPUT_FORMAT_NOMENCL;
    IResource idxFile = srcDir.findMember(nomenclName);

    if (idxFile == null) {
        return null;
    }
    
    IResource outFile = TexlipseProperties.getProjectOutputFile(project);
    if (outFile.getLocalTimeStamp() > idxFile.getLocalTimeStamp()) {
        return null;
    }
    
    return idxFile;
}
 
Example 6
Source File: ProjectExplorerContentProvider.java    From xds-ide with Eclipse Public License 1.0 5 votes vote down vote up
private String getNameWithExtension(IXdsElement xdsElement) {
	if (xdsElement instanceof IXdsResource) {
		IXdsResource xdsResource = (IXdsResource) xdsElement;
		IResource resource = xdsResource.getResource();
		return resource.getName();
	}
	else if (xdsElement instanceof IXdsCompilationUnit) {
		IXdsCompilationUnit compilationUnit = (IXdsCompilationUnit) xdsElement;
		return compilationUnit.getAbsoluteFile().fetchInfo().getName();
	}
	
	return null;
}
 
Example 7
Source File: ResourceSelectionTree.java    From APICloud-Studio with GNU General Public License v3.0 5 votes vote down vote up
public String getText(Object element) {
	if (statusMap == null) return workbenchLabelProvider.getText(element);
	String text = null;
	IResource resource = (IResource)element;
	ISVNLocalResource svnResource = SVNWorkspaceRoot.getSVNResourceFor(resource);
	if (mode == MODE_FLAT) text = resource.getName() + " - " + resource.getFullPath().toString(); //$NON-NLS-1$
	else if (mode == MODE_COMPRESSED_FOLDERS) {
		if (element instanceof IContainer) {
			IContainer container = (IContainer)element;
			text = container.getFullPath().makeRelative().toString();
		}
		else text = resource.getName();
	}
	else {
		text = resource.getName();
	}
	if (svnResource != null) {
		try {
			LocalResourceStatus status = svnResource.getStatus();
			if (status != null) {
				if (status.getMovedFromAbspath() != null) {
					text = text + Policy.bind("ResourceSelectionTree.movedFrom") + status.getMovedFromAbspath().substring(ResourcesPlugin.getWorkspace().getRoot().getLocation().toString().length()) + ")"; //$NON-NLS-1$ //$NON-NLS-2$
				}
				else if (status.getMovedToAbspath() != null) {
					text = text + Policy.bind("ResourceSelectionTree.movedTo") + status.getMovedToAbspath().substring(ResourcesPlugin.getWorkspace().getRoot().getLocation().toString().length()) + ")"; //$NON-NLS-1$ //$NON-NLS-2$
				}
			}
		} catch (SVNException e) {}
	}
	return text;
}
 
Example 8
Source File: FileMetaDataProvider.java    From gama with GNU General Public License v3.0 5 votes vote down vote up
private GenericFileInfo createShapeFileSupportMetaData(final IFile file) {
	GenericFileInfo info = null;
	final IResource r = shapeFileSupportedBy(file);
	if (r == null) { return null; }
	final String ext = file.getFileExtension();
	final String type = longNames.containsKey(ext) ? longNames.get(ext) : "Data";
	info = new GenericFileInfo(file.getModificationStamp(), "" + type + " for '" + r.getName() + "'");
	return info;

}
 
Example 9
Source File: QuickfixMulti.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
private void checkJavaFiles(IResource[] iResources) throws CoreException, IOException, JavaModelException {
    for (IResource resource : iResources) {
        if (resource instanceof IFile) {
            String fileName = resource.getName();
            if (fileName.endsWith(".java")) {
                assertEqualFiles(getExpectedOutputFile(fileName), getInputCompilationUnit(fileName));
            }
        } else if (resource instanceof IFolder) {
            checkJavaFiles(((IFolder) resource).members());
        }
    }
}
 
Example 10
Source File: Util.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Checks whether the given resource is a Java artifact (i.e. either a Java
 * source file or a Java class file).
 *
 * @param resource
 *            The resource to check.
 * @return <code>true</code> if the given resource is a Java artifact.
 *         <code>false</code> otherwise.
 */
public static boolean isJavaArtifact(IResource resource) {
    if (resource == null || (resource.getType() != IResource.FILE)) {
        return false;
    }
    String ex = resource.getFileExtension();
    if ("java".equalsIgnoreCase(ex) || "class".equalsIgnoreCase(ex)) {
        return true;
    }
    String name = resource.getName();
    return Archive.isArchiveFileName(name);
}
 
Example 11
Source File: IgnoreResourcesDialog.java    From APICloud-Studio with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Determines the ignore pattern to use for a resource given the selected action.
 * 
 * @param resource the resource
 * @return the ignore pattern for the specified resource
 */
public String getIgnorePatternFor(IResource resource) {
	switch (selectedAction) {
		case ADD_NAME_ENTRY:
			return resource.getName();
		case ADD_EXTENSION_ENTRY: {
			String extension = resource.getFileExtension();
			return (extension == null) ? resource.getName() : "*." + extension; //$NON-NLS-1$
		}
		case ADD_CUSTOM_ENTRY:
			return customPattern;
	}
	throw new IllegalStateException();
}
 
Example 12
Source File: LaunchTargetTester.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Returns true if the resource is a web.xml or appengine-web.xml in the canonical location.
 *
 * @param resource
 * @return whether the resource is a web.xml or appengine-web.xml file as expected.
 */
private boolean resourceIsDeploymentDescriptor(IResource resource) {
  IProject project = resource.getProject();

  if (WebAppUtilities.isWebApp(project)) {
    IFolder webInf = WebAppUtilities.getWebInfSrc(project);
    if (webInf.exists()) {
      if (resource.getParent().equals(webInf)) {
        String name = resource.getName();
        return name.equals("web.xml") || name.equals("appengine-web.xml");
      }
    }
  }
  return false;
}
 
Example 13
Source File: TestabilityResourceMarkerField.java    From testability-explorer with Apache License 2.0 5 votes vote down vote up
@Override
public String getValue(MarkerItem item) {
  IMarker marker = item.getMarker();
  if (marker != null) {
    IResource resource = marker.getResource();
    String name = resource.getName();
    return name;
  }
  return null;
}
 
Example 14
Source File: PackageFragment.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * @see Openable
 */
protected boolean buildStructure(OpenableElementInfo info, IProgressMonitor pm, Map newElements, IResource underlyingResource) throws JavaModelException {
	// add compilation units/class files from resources
	HashSet vChildren = new HashSet();
	int kind = getKind();
	try {
	    PackageFragmentRoot root = getPackageFragmentRoot();
		char[][] inclusionPatterns = root.fullInclusionPatternChars();
		char[][] exclusionPatterns = root.fullExclusionPatternChars();
		IResource[] members = ((IContainer) underlyingResource).members();
		int length = members.length;
		if (length > 0) {
			IJavaProject project = getJavaProject();
			String sourceLevel = project.getOption(JavaCore.COMPILER_SOURCE, true);
			String complianceLevel = project.getOption(JavaCore.COMPILER_COMPLIANCE, true);
			for (int i = 0; i < length; i++) {
				IResource child = members[i];
				if (child.getType() != IResource.FOLDER
						&& !Util.isExcluded(child, inclusionPatterns, exclusionPatterns)) {
					IJavaElement childElement;
					if (kind == IPackageFragmentRoot.K_SOURCE && Util.isValidCompilationUnitName(child.getName(), sourceLevel, complianceLevel)) {
						childElement = new CompilationUnit(this, child.getName(), DefaultWorkingCopyOwner.PRIMARY);
						vChildren.add(childElement);
					} else if (kind == IPackageFragmentRoot.K_BINARY && Util.isValidClassFileName(child.getName(), sourceLevel, complianceLevel)) {
						childElement = getClassFile(child.getName());
						vChildren.add(childElement);
					}
				}
			}
		}
	} catch (CoreException e) {
		throw new JavaModelException(e);
	}

	if (kind == IPackageFragmentRoot.K_SOURCE) {
		// add primary compilation units
		ICompilationUnit[] primaryCompilationUnits = getCompilationUnits(DefaultWorkingCopyOwner.PRIMARY);
		for (int i = 0, length = primaryCompilationUnits.length; i < length; i++) {
			ICompilationUnit primary = primaryCompilationUnits[i];
			vChildren.add(primary);
		}
	}

	IJavaElement[] children = new IJavaElement[vChildren.size()];
	vChildren.toArray(children);
	info.setChildren(children);
	return true;
}
 
Example 15
Source File: EditorAction.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 4 votes vote down vote up
public void run(IAction action) {
  if (targetEditor == null) {
    GWTPluginLog.logWarning("targetEditor is null");
    return;
  }

  IEditorInput editorInput = targetEditor.getEditorInput();
  IResource resource = (IResource) editorInput.getAdapter(IResource.class);
  ITextEditor javaEditor = (ITextEditor) targetEditor;
  ITextSelection sel = (ITextSelection) javaEditor.getSelectionProvider().getSelection();
  IDocument document = javaEditor.getDocumentProvider().getDocument(
      javaEditor.getEditorInput());

  IDocumentExtension3 document3 = (IDocumentExtension3) document;
  IDocumentPartitioner gwtPartitioner = document3.getDocumentPartitioner(GWTPartitions.GWT_PARTITIONING);

  String[] partitionings = document3.getPartitionings();
  String partitioning = (gwtPartitioner != null
      ? GWTPartitions.GWT_PARTITIONING : IJavaPartitions.JAVA_PARTITIONING);

  ITypedRegion[] types;
  try {
    types = TextUtilities.computePartitioning(document, partitioning,
        sel.getOffset(), sel.getLength(), false);
  } catch (BadLocationException e) {
    GWTPluginLog.logError(e);
    return;
  }

  String msg = "File: " + resource.getName();

  msg += "\nPartitionings: ";
  for (String part : partitionings) {
    msg += "\n" + part;
  }

  msg += "\n\nContent types: ";
  for (ITypedRegion type : types) {
    msg += "\n" + type.getType();
  }

  msg += "\n\nSelection range: (offset = " + sel.getOffset() + ", length = "
      + sel.getLength() + ")";

  MessageDialog.openInformation(targetEditor.getSite().getShell(),
      "Selection Info", msg);
}
 
Example 16
Source File: PackageFragmentRootInfo.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Starting at this folder, create non-java resources for this package fragment root
 * and add them to the non-java resources collection.
 *
 * @exception JavaModelException  The resource associated with this package fragment does not exist
 */
static Object[] computeFolderNonJavaResources(IPackageFragmentRoot root, IContainer folder, char[][] inclusionPatterns, char[][] exclusionPatterns) throws JavaModelException {
	IResource[] nonJavaResources = new IResource[5];
	int nonJavaResourcesCounter = 0;
	try {
		IResource[] members = folder.members();
		int length = members.length;
		if (length > 0) {
			// if package fragment root refers to folder in another IProject, then
			// folder.getProject() is different than root.getJavaProject().getProject()
			// use the other java project's options to verify the name
			IJavaProject otherJavaProject = JavaCore.create(folder.getProject());
			String sourceLevel = otherJavaProject.getOption(JavaCore.COMPILER_SOURCE, true);
			String complianceLevel = otherJavaProject.getOption(JavaCore.COMPILER_COMPLIANCE, true);
			JavaProject javaProject = (JavaProject) root.getJavaProject();
			IClasspathEntry[] classpath = javaProject.getResolvedClasspath();
			nextResource: for (int i = 0; i < length; i++) {
				IResource member = members[i];
				switch (member.getType()) {
					case IResource.FILE :
						String fileName = member.getName();

						// ignore .java files that are not excluded
						if (Util.isValidCompilationUnitName(fileName, sourceLevel, complianceLevel) && !Util.isExcluded(member, inclusionPatterns, exclusionPatterns))
							continue nextResource;
						// ignore .class files
						if (Util.isValidClassFileName(fileName, sourceLevel, complianceLevel))
							continue nextResource;
						// ignore .zip or .jar file on classpath
						if (isClasspathEntry(member.getFullPath(), classpath))
							continue nextResource;
						break;

					case IResource.FOLDER :
						// ignore valid packages or excluded folders that correspond to a nested pkg fragment root
						if (Util.isValidFolderNameForPackage(member.getName(), sourceLevel, complianceLevel)
								&& (!Util.isExcluded(member, inclusionPatterns, exclusionPatterns)
										|| isClasspathEntry(member.getFullPath(), classpath)))
							continue nextResource;
						break;
				}
				if (nonJavaResources.length == nonJavaResourcesCounter) {
					// resize
					System.arraycopy(nonJavaResources, 0, (nonJavaResources = new IResource[nonJavaResourcesCounter * 2]), 0, nonJavaResourcesCounter);
				}
				nonJavaResources[nonJavaResourcesCounter++] = member;
			}
		}
		if (ExternalFoldersManager.isInternalPathForExternalFolder(folder.getFullPath())) {
			IJarEntryResource[] jarEntryResources = new IJarEntryResource[nonJavaResourcesCounter];
			for (int i = 0; i < nonJavaResourcesCounter; i++) {
				jarEntryResources[i] = new NonJavaResource(root, nonJavaResources[i]);
			}
			return jarEntryResources;
		} else if (nonJavaResources.length != nonJavaResourcesCounter) {
			System.arraycopy(nonJavaResources, 0, (nonJavaResources = new IResource[nonJavaResourcesCounter]), 0, nonJavaResourcesCounter);
		}
		return nonJavaResources;
	} catch (CoreException e) {
		throw new JavaModelException(e);
	}
}
 
Example 17
Source File: AltConfigWizard.java    From CogniCrypt with Eclipse Public License 2.0 4 votes vote down vote up
/**
 * This method is called once the user selects an instance. It writes the instance to an xml file and calls the code generation.
 *
 * @return <code>true</code>/<code>false</code> if writing instance file and code generation are (un)successful
 */
@Override
public boolean performFinish() {
	boolean ret = false;
	final CodeGenerators genKind = selectedTask.getCodeGen();
	CodeGenerator codeGenerator = null;
	String additionalResources = selectedTask.getAdditionalResources();
	final LocatorPage currentPage = (LocatorPage) getContainer().getCurrentPage();
	IResource targetFile = (IResource) currentPage.getSelectedResource().getFirstElement();

	String taskName = selectedTask.getName();
	JOptionPane optionPane = new JOptionPane("CogniCrypt is now generating code that implements " + selectedTask.getDescription() + "\ninto file " + ((targetFile != null)
		? targetFile.getName()
		: "Output.java") + ". This should take no longer than a few seconds.", JOptionPane.INFORMATION_MESSAGE, JOptionPane.DEFAULT_OPTION, null, new Object[] {}, null);
	JDialog waitingDialog = optionPane.createDialog("Generating Code");
	waitingDialog.setModal(false);
	waitingDialog.setVisible(true);
	Configuration chosenConfig = null;
	try {
		switch (genKind) {
			case CrySL:
				CrySLBasedCodeGenerator.clearParameterCache();
				File templateFile = CodeGenUtils.getResourceFromWithin(selectedTask.getCodeTemplate()).listFiles()[0];
				codeGenerator = new CrySLBasedCodeGenerator(targetFile);
				String projectRelDir = Constants.outerFileSeparator + codeGenerator.getDeveloperProject()
					.getSourcePath() + Constants.outerFileSeparator + Constants.PackageName + Constants.outerFileSeparator;
				String pathToTemplateFile = projectRelDir + templateFile.getName();
				String resFileOSPath = "";

				IPath projectPath = targetFile.getProject().getRawLocation();
				if (projectPath == null) {
					projectPath = targetFile.getProject().getLocation();
				}
				resFileOSPath = projectPath.toOSString() + pathToTemplateFile;

				Files.createDirectories(Paths.get(projectPath.toOSString() + projectRelDir));
				Files.copy(templateFile.toPath(), Paths.get(resFileOSPath), StandardCopyOption.REPLACE_EXISTING);
				codeGenerator.getDeveloperProject().refresh();

				resetAnswers();
				chosenConfig = new CrySLConfiguration(resFileOSPath, ((CrySLBasedCodeGenerator) codeGenerator).setUpTemplateClass(pathToTemplateFile));
				break;
			case XSL:
				this.constraints = (this.constraints != null) ? this.constraints : new HashMap<>();
				final InstanceGenerator instanceGenerator = new InstanceGenerator(CodeGenUtils.getResourceFromWithin(selectedTask.getModelFile())
					.getAbsolutePath(), "c0_" + taskName, selectedTask.getDescription());
				instanceGenerator.generateInstances(this.constraints);

				// Initialize Code Generation
				codeGenerator = new XSLBasedGenerator(targetFile, selectedTask.getCodeTemplate());
				chosenConfig = new XSLConfiguration(instanceGenerator.getInstances().values().iterator()
					.next(), this.constraints, codeGenerator.getDeveloperProject().getProjectPath() + Constants.innerFileSeparator + Constants.pathToClaferInstanceFile);
				break;
			default:
				return false;
		}
		ret = codeGenerator.generateCodeTemplates(chosenConfig, additionalResources);

		try {
			codeGenerator.getDeveloperProject().refresh();
		} catch (CoreException e1) {
			Activator.getDefault().logError(e1);
		}

	} catch (Exception ex) {
		Activator.getDefault().logError(ex);
	} finally {

		waitingDialog.setVisible(false);
		waitingDialog.dispose();
	}

	return ret;
}
 
Example 18
Source File: TmfExperimentFolder.java    From tracecompass with Eclipse Public License 2.0 3 votes vote down vote up
/**
 * Finds the experiment element for a given resource
 *
 * @param resource
 *            the resource to search for
 * @return the experiment element if found else null
 * @since 2.0
 */
public @Nullable TmfExperimentElement getExperiment(@NonNull IResource resource) {
    String name = resource.getName();
    if (name != null) {
        return getExperiment(name);
    }
    return null;
}
 
Example 19
Source File: FindBugsAction.java    From spotbugs with GNU Lesser General Public License v2.1 2 votes vote down vote up
/**
 * Run a FindBugs analysis on the given resource, displaying a progress
 * monitor.
 *
 * @param part
 *
 * @param resources
 *            The resource to run the analysis on.
 */
protected void work(IWorkbenchPart part, final IResource resource, final List<WorkItem> resources) {
    FindBugsJob runFindBugs = new StartedFromViewJob("Finding bugs in " + resource.getName() + "...", resource, resources, part);
    runFindBugs.scheduleInteractive();
}
 
Example 20
Source File: JavaElementLabels.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 2 votes vote down vote up
/**
 * Returns the styled string for the given resource.
 * The returned label is BiDi-processed with {@link TextProcessor#process(String, String)}.
 *
 * @param resource the resource
 * @return the styled string
 * @since 3.4
 */
private static StyledString getStyledResourceLabel(IResource resource) {
	StyledString result= new StyledString(resource.getName());
	return Strings.markLTR(result);
}