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

The following examples show how to use org.eclipse.core.resources.IResource#getFileExtension() . These examples are extracted from open source projects. 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
private void addMembersOfFolderToClasspath(String path, IProgressMonitor monitor, IJavaProject javaProject) throws CoreException, JavaModelException {
	IFolder folder = javaProject.getProject().getFolder(path);
	 if (folder != null && folder.exists())
	 {
		 for (IResource res : folder.members())
		 {
			 if (res.getFileExtension() != null && res.getFileExtension().equals("jar") && res.exists())
			 {
				 // check if this Resource is on the classpath
				 if (!javaProject.isOnClasspath(res)) {
					 if (DEBUG)
						 Activator.log("Adding library [" + res.getFullPath() + "] to classpath for project [" + javaProject.getProject().getName() + "]");
					 FixProjectsUtils.addToClassPath(res, IClasspathEntry.CPE_LIBRARY, javaProject, monitor);
				 }
			 }
		 }
	 }
}
 
Example 2
public static IFile getProjectFile(IContainer container) {
	if (container != null) {
		try {
			for (IResource projResource : container.members()) {
				if (projResource.getFileExtension() != null && (projResource.getFileExtension().equals("csproj") //$NON-NLS-1$
						|| projResource.getName().equals("project.json"))) { //$NON-NLS-1$
					return (IFile) projResource;
				}
			}
		} catch (CoreException e) {
		}
	}
	return null;
}
 
Example 3
/**
 * @param resource the input file to be processed
 * @return the arguments to give to the external program
 */
protected String getArguments(IResource resource) {
    String args = getProgramArguments();
    if (args == null) {
        return null;
    }
    String ext = resource.getFileExtension();
    String name = resource.getName();
    String baseName = name.substring(0, name.length() - ext.length());
    String inputName = baseName + getInputFormat();
    String outputName = baseName + getOutputFormat();
    if (baseName.indexOf(' ') >= 0) {
        inputName = "\"" + inputName + "\"";
        outputName = "\"" + outputName + "\"";
    }
    
    if (args.indexOf("%input") >= 0) {
        args = args.replaceAll("%input", inputName);
    }
    if (args.indexOf("%output") >= 0) {
        args = args.replaceAll("%output", outputName);
    }
    if (args.indexOf("%fullinput") >= 0) {
        args = args.replaceAll("%fullinput",
                resource.getParent().getLocation().toFile().getAbsolutePath()
                + File.separator + inputName);
    }
    if (args.indexOf("%fulloutput") >= 0) {
        args = args.replaceAll("%fulloutput",
                resource.getParent().getLocation().toFile().getAbsolutePath()
                + File.separator + outputName);
    }
    return args;
}
 
Example 4
Source Project: xds-ide   File: ResourceUtils.java    License: Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Gets extension of the resource
 * @param resource
 * @param isLowercase if true and resource has an extension then it will be converted to lowercase
 * @return extension or null (i.e. resource passed is null  or it has no extension)
 */
public static String getExtension(IResource resource, boolean isLowercase) {
	if (resource == null){
		return null;
	}
	String ext = resource.getFileExtension();
	if (ext != null && isLowercase) {
		ext = ext.toLowerCase();
	}
	return ext;
}
 
Example 5
/**
 * Checks whether the given resource is a Java class file.
 *
 * @param resource
 *            The resource to check.
 * @return <code>true</code> if the given resource is a class file,
 *         <code>false</code> otherwise.
 */
public static boolean isClassFile(IResource resource) {
    if (resource == null || (resource.getType() != IResource.FILE)) {
        return false;
    }
    String ex = resource.getFileExtension();
    return "class".equalsIgnoreCase(ex); //$NON-NLS-1$

}
 
Example 6
/**
 * 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 7
private String getContentType(IResource resource) {
	String extension = resource.getFileExtension();
	if (FileUtils.JS_EXTENSION.equals(extension)) {
		return "org.eclipse.wst.jsdt.core.jsSource";
	}
	return new StringBuilder("ts.eclipse.ide.core.").append(extension).append("Source").toString();
}
 
Example 8
/**
 * 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 9
public void resourceChanged(IResourceChangeEvent event) {
            // @TODO: need to filter resource events!
            try {
                IResourceDeltaVisitor visitor = new IResourceDeltaVisitor() {
                    
                    boolean keepVisiting = true;
                    
                    public boolean visit(IResourceDelta delta) {
                        
                        if (!keepVisiting || null == designerProject)
                            return false;
                        
                        int k = delta.getKind();
                        if ( ! (IResourceDelta.ADDED == k || 
                                IResourceDelta.REMOVED == k || 
                                IResourceDelta.CHANGED == k) )  // an update could be a name change
                           return true;

//                       if ((delta.getFlags() ...?
                       IResource resource = delta.getResource();
                       if (resource.getType() == IResource.FILE && resource.getProject().equals(designerProject.getProject())) {
                           String resExt = resource.getFileExtension();
                           String typeExt = extForType(); 
                           if (typeExt.length() > 0 && resExt.length() > 0 &&
                               typeExt.equalsIgnoreCase(resExt)) {
                               keepVisiting = false;
                               updateDesignElements();
                           }
                       }
                       return keepVisiting;
                    }
                 };
                 
                 event.getDelta().accept(visitor);
            }
            catch(Exception e) {
                ExtLibToolingLogger.EXT_LIB_TOOLING_LOGGER.error(e, e.toString());            }
        }
 
Example 10
private boolean containsSourceFile(final IFolder folder) throws CoreException {
    for (final IResource res : folder.members()) {
        if (res.getFileExtension() != null
                && (res.getFileExtension().equals("java") || res.getFileExtension().equals("groovy"))) {
            return true;
        }
    }
    return false;
}
 
Example 11
@Override
public Change createChange(IProgressMonitor monitor) throws CoreException {
	try {
		monitor.beginTask(RefactoringCoreMessages.RenameTypeRefactoring_creating_change, 4);
		String project = null;
		IJavaProject javaProject = fType.getJavaProject();
		if (javaProject != null) {
			project = javaProject.getElementName();
		}
		int flags = JavaRefactoringDescriptor.JAR_MIGRATION | JavaRefactoringDescriptor.JAR_REFACTORING | RefactoringDescriptor.STRUCTURAL_CHANGE;
		try {
			if (!Flags.isPrivate(fType.getFlags())) {
				flags |= RefactoringDescriptor.MULTI_CHANGE;
			}
			if (fType.isAnonymous() || fType.isLocal()) {
				flags |= JavaRefactoringDescriptor.JAR_SOURCE_ATTACHMENT;
			}
		} catch (JavaModelException exception) {
			JavaLanguageServerPlugin.log(exception);
		}
		final String description = Messages.format(RefactoringCoreMessages.RenameTypeProcessor_descriptor_description_short, BasicElementLabels.getJavaElementName(fType.getElementName()));
		final String header = Messages.format(RefactoringCoreMessages.RenameTypeProcessor_descriptor_description, new String[] { JavaElementLabels.getElementLabel(fType, JavaElementLabels.ALL_FULLY_QUALIFIED), getNewElementLabel() });
		final String comment = new JDTRefactoringDescriptorComment(project, this, header).asString();
		final RenameJavaElementDescriptor descriptor = RefactoringSignatureDescriptorFactory.createRenameJavaElementDescriptor(IJavaRefactorings.RENAME_TYPE);
		descriptor.setProject(project);
		descriptor.setDescription(description);
		descriptor.setComment(comment);
		descriptor.setFlags(flags);
		descriptor.setJavaElement(fType);
		descriptor.setNewName(getNewElementName());
		descriptor.setUpdateQualifiedNames(fUpdateQualifiedNames);
		descriptor.setUpdateTextualOccurrences(fUpdateTextualMatches);
		descriptor.setUpdateReferences(fUpdateReferences);
		if (fUpdateQualifiedNames && fFilePatterns != null && !"".equals(fFilePatterns)) {
			descriptor.setFileNamePatterns(fFilePatterns);
		}
		descriptor.setUpdateSimilarDeclarations(fUpdateSimilarElements);
		descriptor.setMatchStrategy(fRenamingStrategy);
		final DynamicValidationRefactoringChange result = new DynamicValidationRefactoringChange(descriptor, RefactoringCoreMessages.RenameTypeProcessor_change_name);

		if (fChangeManager.containsChangesIn(fType.getCompilationUnit())) {
			TextChange textChange = fChangeManager.get(fType.getCompilationUnit());
			if (textChange instanceof TextFileChange) {
				((TextFileChange) textChange).setSaveMode(TextFileChange.FORCE_SAVE);
			}
		}

		if (willRenameCU()) {
			IResource resource = fType.getCompilationUnit().getResource();
			if (resource != null && resource.isLinked()) {
				result.addAll(fChangeManager.getAllChanges());
				String ext = resource.getFileExtension();
				String renamedResourceName;
				if (ext == null) {
					renamedResourceName = getNewElementName();
				} else {
					renamedResourceName = getNewElementName() + '.' + ext;
				}
				result.add(new RenameResourceChange(fType.getCompilationUnit().getPath(), renamedResourceName));
			} else {
				addTypeDeclarationUpdate(fChangeManager);
				addConstructorRenames(fChangeManager);

				result.addAll(fChangeManager.getAllChanges());

				String renamedCUName = JavaModelUtil.getRenamedCUName(fType.getCompilationUnit(), getNewElementName());
				result.add(new RenameCompilationUnitChange(fType.getCompilationUnit(), renamedCUName));
			}
		} else {
			result.addAll(fChangeManager.getAllChanges());
		}

		monitor.worked(1);
		return result;
	} finally {
		fChangeManager = null;
	}
}
 
Example 12
public List<DiagramFileStore> getRecentChildren(final int nbResult) {
    if (!getResource().exists()) {
        return Collections.emptyList();
    }
    refresh();

    final List<DiagramFileStore> result = new ArrayList<>();
    final List<IResource> resources = new ArrayList<>();
    final IFolder folder = getResource();
    try {
        for (final IResource r : folder.members()) {
            if (r.getFileExtension() != null
                    && getCompatibleExtensions().contains(
                            r.getFileExtension())) {
                resources.add(r);
            }
        }
    } catch (final CoreException e) {
        BonitaStudioLog.error(e);
    }

    Collections.sort(resources, new Comparator<IResource>() {

        @Override
        public int compare(final IResource arg0, final IResource arg1) {
            final long lastModifiedArg1 = arg1.getLocation().toFile()
                    .lastModified();
            final long lastModifiedArg0 = arg0.getLocation().toFile()
                    .lastModified();
            return Long.valueOf(lastModifiedArg1).compareTo(
                    Long.valueOf(lastModifiedArg0));
        }
    });

    for (int i = 0; i < nbResult; i++) {
        if (resources.size() > i) {
            result.add(createRepositoryFileStore(resources.get(i).getName()));
        }
    }

    return result;
}
 
Example 13
@Override
public Change createChange(IProgressMonitor monitor) throws CoreException {
	try {
		monitor.beginTask(RefactoringCoreMessages.RenameTypeRefactoring_creating_change, 4);
		String project= null;
		IJavaProject javaProject= fType.getJavaProject();
		if (javaProject != null)
			project= javaProject.getElementName();
		int flags= JavaRefactoringDescriptor.JAR_MIGRATION | JavaRefactoringDescriptor.JAR_REFACTORING | RefactoringDescriptor.STRUCTURAL_CHANGE;
		try {
			if (!Flags.isPrivate(fType.getFlags()))
				flags|= RefactoringDescriptor.MULTI_CHANGE;
			if (fType.isAnonymous() || fType.isLocal())
				flags|= JavaRefactoringDescriptor.JAR_SOURCE_ATTACHMENT;
		} catch (JavaModelException exception) {
			JavaPlugin.log(exception);
		}
		final String description= Messages.format(RefactoringCoreMessages.RenameTypeProcessor_descriptor_description_short, BasicElementLabels.getJavaElementName(fType.getElementName()));
		final String header= Messages.format(RefactoringCoreMessages.RenameTypeProcessor_descriptor_description, new String[] { JavaElementLabels.getElementLabel(fType, JavaElementLabels.ALL_FULLY_QUALIFIED), getNewElementLabel()});
		final String comment= new JDTRefactoringDescriptorComment(project, this, header).asString();
		final RenameJavaElementDescriptor descriptor= RefactoringSignatureDescriptorFactory.createRenameJavaElementDescriptor(IJavaRefactorings.RENAME_TYPE);
		descriptor.setProject(project);
		descriptor.setDescription(description);
		descriptor.setComment(comment);
		descriptor.setFlags(flags);
		descriptor.setJavaElement(fType);
		descriptor.setNewName(getNewElementName());
		descriptor.setUpdateQualifiedNames(fUpdateQualifiedNames);
		descriptor.setUpdateTextualOccurrences(fUpdateTextualMatches);
		descriptor.setUpdateReferences(fUpdateReferences);
		if (fUpdateQualifiedNames && fFilePatterns != null && !"".equals(fFilePatterns)) //$NON-NLS-1$
			descriptor.setFileNamePatterns(fFilePatterns);
		descriptor.setUpdateSimilarDeclarations(fUpdateSimilarElements);
		descriptor.setMatchStrategy(fRenamingStrategy);
		final DynamicValidationRefactoringChange result= new DynamicValidationRefactoringChange(descriptor, RefactoringCoreMessages.RenameTypeProcessor_change_name);

		if (fChangeManager.containsChangesIn(fType.getCompilationUnit())) {
			TextChange textChange= fChangeManager.get(fType.getCompilationUnit());
			if (textChange instanceof TextFileChange) {
				((TextFileChange) textChange).setSaveMode(TextFileChange.FORCE_SAVE);
			}
		}
		result.addAll(fChangeManager.getAllChanges());
		if (willRenameCU()) {
			IResource resource= fType.getCompilationUnit().getResource();
			if (resource != null && resource.isLinked()) {
				String ext= resource.getFileExtension();
				String renamedResourceName;
				if (ext == null)
					renamedResourceName= getNewElementName();
				else
					renamedResourceName= getNewElementName() + '.' + ext;
				result.add(new RenameResourceChange(fType.getCompilationUnit().getPath(), renamedResourceName));
			} else {
				String renamedCUName= JavaModelUtil.getRenamedCUName(fType.getCompilationUnit(), getNewElementName());
				result.add(new RenameCompilationUnitChange(fType.getCompilationUnit(), renamedCUName));
			}
		}
		monitor.worked(1);
		return result;
	} finally {
		fChangeManager= null;
	}
}
 
Example 14
/**
 * Visits the resource delta tree determining which files to rebuild (*.py).
 *
 * Subclasses should only reimplement visitChanged, visitAdded and visitRemoved. This method will not be called
 * in the structure provided by pydev.
 *
 * @see org.eclipse.core.resources.IResourceDeltaVisitor#visit(org.eclipse.core.resources.IResourceDelta)
 */
@Override
public boolean visit(IResourceDelta delta) throws CoreException {
    if (delta == null) {
        return true;
    }

    final IResource resource = delta.getResource();

    if (resource == null) {
        return true;
    }

    int type = resource.getType();

    //related bug https://sourceforge.net/tracker/index.php?func=detail&aid=1238850&group_id=85796&atid=577329

    //the team-support plugins of eclipse use the IResource
    //method setTeamPrivateMember to indicate resources
    //that are only in the project for the team-stuff (e.g. .svn or
    //.cvs or _darcs directories).
    if (resource.isTeamPrivateMember()) {
        return true;
    }

    if (type == IResource.FOLDER) {
        switch (delta.getKind()) {
            case IResourceDelta.REMOVED:
                memo.put(PyDevBuilderVisitor.DOCUMENT_TIME, System.currentTimeMillis());
                visitRemovedResource(resource, null, monitor);
                break;
            //for folders, we don't have to do anything if added or changed (we just treat their children, that should
            //resolve for modules -- we do, however have to treat __init__.py differently).
        }

    } else if (type == IResource.FILE) {
        String ext = resource.getFileExtension();
        if (ext == null) { //resource.getFileExtension() may return null if it has none.
            if (resource instanceof IFile) {
                CorePlugin.markAsPyDevFileIfDetected((IFile) resource);
            }
            return true;
        }

        //only analyze projects with the python nature...
        IProject project = resource.getProject();
        PythonNature nature = PythonNature.getPythonNature(project);

        if (project != null && nature != null) {
            //we just want to make the visit if it is a valid python file and it is in the pythonpath
            if (PythonPathHelper.isValidSourceFile("." + ext)) {
                onVisitDelta(delta);

            } else if (ext.equals("pyc")) {
                if (delta.getKind() == IResourceDelta.ADDED) {
                    handleAddedPycFiles(resource, nature);
                }
            }
        }
    }

    return true;
}
 
Example 15
public Set<Locale> getExistingLocale(final ConnectorDefinition definition) {
    final Set<Locale> result = new HashSet<>();
    String defId = null;
    if (definition == null) {
        return result;
    }
    if (definition.eResource() == null) {
        defId = NamingUtils.toConnectorDefinitionFilename(definition.getId(), definition.getVersion(), false);
    } else {
        defId = URI.decode(definition.eResource().getURI().trimFileExtension().lastSegment());
    }
    try {
        for (final IResource r : store.getResource().members()) {
            if (r.getFileExtension() != null
                    && r.getFileExtension().equals("properties")) {
                final String resourceName = r.getName();
                if (resourceName.length() >= defId.length()) {
                    final String baseName = resourceName.substring(0,
                            defId.length());
                    if (baseName.equals(defId)) {
                        if (resourceName.substring(baseName.length())
                                .indexOf("_") != -1
                                && resourceName
                                        .substring(baseName.length())
                                        .indexOf(".") != -1) {
                            String language = resourceName
                                    .substring(baseName.length());
                            language = language.substring(1,
                                    language.lastIndexOf("."));
                            String country = null;
                            String variant = null;
                            if (language.indexOf("_") != -1) {
                                final String[] split = language.split("_");
                                language = split[0];
                                country = split[1];
                                if (split.length == 3) {
                                    variant = split[2];
                                }
                            }
                            result.add(new Locale(language,
                                    country == null ? "" : country,
                                    variant == null ? "" : variant));
                        }
                    }
                }
            }
        }
    } catch (final CoreException e) {
        BonitaStudioLog.error(e);
    }
    return result;
}
 
Example 16
/**
 * Checks whether the given resource is a Java source file.
 *
 * @param resource
 *            The resource to check.
 * @return <code>true</code> if the given resource is a Java source file,
 *         <code>false</code> otherwise.
 */
public static boolean isJavaFile(IResource resource) {
    if (resource == null || (resource.getType() != IResource.FILE)) {
        return false;
    }
    String ex = resource.getFileExtension();
    return "java".equalsIgnoreCase(ex); //$NON-NLS-1$
}
 
Example 17
/**
 * Answers whether the given resource is a Java file.
 * The resource must be a file whose file name ends with ".java",
 * or an extension defined as Java source.
 *
 * @param file the file to test
 * @return a <code>true<code> if the given resource is a Java file
 */
private boolean isJavaFile(IResource file) {
	return file != null
		&& file.getType() == IResource.FILE
		&& file.getFileExtension() != null
		&& JavaCore.isJavaLikeFileName(file.getName());
}
 
Example 18
/**
 * Answers whether the given resource is a class file.
 * The resource must be a file whose file name ends with ".class".
 *
 * @param file the file to test
 * @return a <code>true<code> if the given resource is a class file
 */
private boolean isClassFile(IResource file) {
	return file != null
		&& file.getType() == IResource.FILE
		&& file.getFileExtension() != null
		&& file.getFileExtension().equalsIgnoreCase("class"); //$NON-NLS-1$
}
 
Example 19
/**
 * Returns true if the resource has an extension of <code>jsp</code> or <code>
 * html</code> .
 *
 * Note that the resource need not be an IFile.
 */
public static boolean hasJspOrHtmlExtension(IResource resource) {
  String extension = resource.getFileExtension();
  return ("jsp".equalsIgnoreCase(extension) || "html".equalsIgnoreCase(extension));
}
 
Example 20
Source Project: birt   File: ResourceSorter.java    License: Eclipse Public License 1.0 2 votes vote down vote up
/**
 * Returns the extension portion of the given resource.
 * 
 * @param resource
 *            the resource
 * @return the file extension, possibily the empty string
 */
private String getExtensionFor( IResource resource )
{
	String ext = resource.getFileExtension( );
	return ext == null ? "" : ext; //$NON-NLS-1$
}