Java Code Examples for org.eclipse.core.runtime.IPath#getFileExtension()

The following examples show how to use org.eclipse.core.runtime.IPath#getFileExtension() . 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: EclipseUtil.java    From APICloud-Studio with GNU General Public License v3.0 6 votes vote down vote up
public boolean accept(File dir, String name)
{
	IPath path = Path.fromOSString(dir.getAbsolutePath()).append(name);
	name = path.removeFileExtension().lastSegment();
	String ext = path.getFileExtension();
	if (Platform.OS_MACOSX.equals(Platform.getOS()))
	{
		if (!"app".equals(ext)) //$NON-NLS-1$
		{
			return false;
		}
	}
	for (String launcherName : LAUNCHER_NAMES)
	{
		if (launcherName.equalsIgnoreCase(name))
		{
			return true;
		}
	}
	return false;
}
 
Example 2
Source File: IndexApi.java    From Pydev with Eclipse Public License 1.0 6 votes vote down vote up
private Document createDocument(IPath filepath, long modifiedTime, Map<String, String> additionalStringFields) {
    Document doc = new Document();

    doc.add(new StringField(IFields.FILEPATH, filepath.toPortableString(), Field.Store.YES)); // StringField is not analyzed
    doc.add(new StringField(IFields.MODIFIED_TIME, String.valueOf(modifiedTime), Field.Store.YES));

    String lastSegment = filepath.removeFileExtension().lastSegment();
    if (lastSegment == null) {
        lastSegment = "";
    }
    doc.add(new StringField(IFields.FILENAME, lastSegment, Field.Store.YES)); // StringField is not analyzed
    String fileExtension = filepath.getFileExtension();
    if (fileExtension == null) {
        fileExtension = "";
    }

    if (additionalStringFields != null) {
        Set<Entry<String, String>> entrySet = additionalStringFields.entrySet();
        for (Entry<String, String> entry : entrySet) {
            doc.add(new StringField(entry.getKey(), entry.getValue(), Field.Store.YES));
        }
    }

    doc.add(new StringField(IFields.EXTENSION, fileExtension, Field.Store.YES)); // StringField is not analyzed
    return doc;
}
 
Example 3
Source File: RouteResourcesHelper.java    From tesb-studio-se with Apache License 2.0 6 votes vote down vote up
private static String getFileName(Item item) {
	String label = item.getProperty().getLabel();
	String selectedVersion = item.getProperty().getVersion();

	if ("Latest".equals(selectedVersion)) {
		return label;
	}

	IPath path = new Path(label);
	String fileExtension = path.getFileExtension();
	String fileName = path.removeFileExtension().toPortableString();
	fileName = fileName + "_" + selectedVersion;
	if (fileExtension != null && !fileExtension.isEmpty()) {
		fileName = fileName + "." + fileExtension;
	}
	return fileName;
}
 
Example 4
Source File: ExternalFoldersManager.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Returns <code>true</code> if the provided path is a folder external to the project.
 */
public static boolean isExternalFolderPath(IPath externalPath) {
	if (externalPath == null)
		return false;
	String firstSegment = externalPath.segment(0);
	if (firstSegment != null && ResourcesPlugin.getWorkspace().getRoot().getProject(firstSegment).exists())
		return false;
	JavaModelManager manager = JavaModelManager.getJavaModelManager();
	if (manager.isExternalFile(externalPath) || manager.isAssumedExternalFile(externalPath))
		return false;
	File externalFolder = externalPath.toFile();
	if (externalFolder.isFile()) {
		manager.addExternalFile(externalPath);
		return false;
	}
	if (externalPath.getFileExtension() != null/*likely a .jar, .zip, .rar or other file*/ && !externalFolder.exists()) {
		manager.addAssumedExternalFile(externalPath);
		return false;
	}
	return true;
}
 
Example 5
Source File: ArchiveFileFilter.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public static boolean isArchivePath(IPath path, boolean allowAllAchives) {
	if (allowAllAchives)
		return true;

	String ext= path.getFileExtension();
	if (ext != null && ext.length() != 0) {
		return isArchiveFileExtension(ext);
	}
	return false;
}
 
Example 6
Source File: IDECPListLabelProvider.java    From birt with Eclipse Public License 1.0 5 votes vote down vote up
public static boolean isArchivePath(IPath path, boolean allowAllAchives) {
	if (allowAllAchives)
		return true;

	String ext= path.getFileExtension();
	if (ext != null && ext.length() != 0) {
		return isArchiveFileExtension(ext);
	}
	return false;
}
 
Example 7
Source File: FatJarPackageWizardPage.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Stores the widget values in the JAR package.
 */
@Override
protected void updateModel() {
	super.updateModel();

	String comboText= fAntScriptNamesCombo.getText();
	IPath path= Path.fromOSString(comboText);
	if (path.segmentCount() > 0 && ensureAntScriptFileIsValid(path.toFile()) && path.getFileExtension() == null)
		path= path.addFileExtension(ANTSCRIPT_EXTENSION);

	fAntScriptLocation= getAbsoluteLocation(path);
}
 
Example 8
Source File: FixedFatJarExportPage.java    From sarl with Apache License 2.0 5 votes vote down vote up
/**
 * Stores the widget values in the JAR package.
 */
@Override
protected void updateModel() {
	super.updateModel();

	String comboText= fAntScriptNamesCombo.getText();
	IPath path= Path.fromOSString(comboText);
	if (path.segmentCount() > 0 && ensureAntScriptFileIsValid(path.toFile()) && path.getFileExtension() == null)
		path= path.addFileExtension(ANTSCRIPT_EXTENSION);

	fAntScriptLocation= getAbsoluteLocation(path);
}
 
Example 9
Source File: CPListLabelProvider.java    From birt with Eclipse Public License 1.0 5 votes vote down vote up
public static boolean isArchivePath( IPath path, boolean allowAllAchives )
{
	if ( allowAllAchives )
		return true;

	String ext = path.getFileExtension( );
	if ( ext != null && ext.length( ) != 0 )
	{
		return isArchiveFileExtension( ext );
	}
	return false;
}
 
Example 10
Source File: PlatformTools.java    From depan with Apache License 2.0 5 votes vote down vote up
/**
 * Guess a filename for a new file.  For example, if an initial filename
 * of {@code Tree.dgi} already exist, the first guess will be
 * {@code Tree (1).dgi}.
 * 
 * This is best-effort heuristic, and is not guaranteed to actually be an
 * unused filename.  If the application wishes to ensure that no existing
 * file is overwritten, additional checks are required in the application.
 * 
 * The implemented heuristic follows these lines:
 * <ol>
 * <li>if the initial proposal is unused, provide that filename.</li>
 * <li>for a limited number of trials, insert a sequence number before the
 *     filename's extension. If this modified filename is unused, provide it
 *     as the result.</li>
 * </ol>
 * In all other cases, return the initial proposal.
 * 
 * Since the filename guessing heuristic is non-atomic with the actual file
 * creation, the filename may exist by the time the application tries to
 * create the file.  Additionally, if the heuristic gives up, the returned
 * filename may exist anyway.
 * 
 * The numbered trials names begin with {@code start}, and end before the
 * {@code limit} is reached.  Thus, a start of 1 and limit of 10 will 
 * try the values 1 through 9.  If the limit is less then the start value,
 * no variants are checked.
 * 
 * @param container intended parent of new file
 * @param newFilename initial proposal for new filename
 * @param start lowest number to use for filename variants
 * @param limit stopping number for file variants
 * @return the recommended filename to use
 */
public static String guessNewFilename(
    IContainer container, String newFilename, int start, int limit) {
  // Quick exit if container is no help
  if (null == container) {
    return newFilename;
  }

  // No point in testing if no variants are allowed
  if (limit < start) {
    return newFilename;
  }

  // Quick exit if proposed name does not exist
  IPath newPath = buildPath(newFilename);
  if (!container.exists(newPath)) {
    return newFilename;
  }

  // Try to find an unused numbered variant
  int trial = 1;
  String ext = newPath.getFileExtension();
  String base = fromPath(newPath.removeFileExtension());
  do {
    newPath = buildPath(base + " (" + trial + ")")
        .addFileExtension(ext);
    if (!container.exists(newPath)) {
      return fromPath(newPath);
    }
    ++trial;
  } while (trial < limit);

  // Fall back to the bare filename
  return newFilename;
}
 
Example 11
Source File: ScriptMainTab.java    From birt with Eclipse Public License 1.0 5 votes vote down vote up
private boolean isJarFile( IPath path )
{
	String str = path.getFileExtension( );
	for ( int i = 0; i < FILETYPE.length; i++ )
	{
		if ( FILETYPE[i].equals( str ) )
		{
			return true;
		}
	}
	return false;
}
 
Example 12
Source File: ProjectResourceControl.java    From depan with Apache License 2.0 5 votes vote down vote up
/**
 * Determine if the inputs are consistent.
 * 
 * @return error string if problems exist, or null if inputs are valid
 */
public static String validateInputs(String containerName, String fileName) {

  if (containerName.length() == 0) {
    return "File container must be specified";
  }

  IPath containerPath = PlatformTools.buildPath(containerName);
  IResource container = WorkspaceTools.buildWorkspaceResource(containerPath);
  if (container == null
      || (container.getType()
          & (IResource.PROJECT | IResource.FOLDER)) == 0) {
    return "File container must exist";
  }
  if (!container.isAccessible()) {
    return "Project must be writable";
  }
  if (fileName.length() == 0) {
    return "File name must be specified";
  }
  IPath filePath = PlatformTools.buildPath(fileName);
  if ((1 != filePath.segmentCount()) || (filePath.hasTrailingSeparator())) {
    return "File name cannot be a path";
  }
  filePath.getFileExtension();

  return null;
}
 
Example 13
Source File: RenameCompilationUnitChange.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
@Override
protected IPath createNewPath() {
	final IPath path= getResourcePath();
	if (path.getFileExtension() != null) {
		return path.removeFileExtension().removeLastSegments(1).append(getNewName());
	} else {
		return path.removeLastSegments(1).append(getNewName());
	}
}
 
Example 14
Source File: ModuleSpecifierSelectionDialog.java    From n4js with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public String isValid(String newText) {
	IPath path = new Path(newText);
	String fileExtension = path.getFileExtension();
	String moduleName = path.removeFileExtension().lastSegment();

	if (path.removeFileExtension().segmentCount() < 1 || moduleName.isEmpty()) {
		return "The module name must not be empty.";
	}

	if (!isValidFolderName(path.removeFileExtension().toString())) {
		return "The module name is not a valid file system name.";
	}

	if (fileExtension == null) {
		return "The module name needs to have a valid N4JS file extension.";
	}
	if (!(fileExtension.equals(N4JSGlobals.N4JS_FILE_EXTENSION) ||
			fileExtension.equals(N4JSGlobals.N4JSD_FILE_EXTENSION))) {
		return "Invalid file extension.";
	}
	if (!isModuleFileSpecifier(path)) {
		return "Invalid module file specifier.";
	}
	if (path.segmentCount() > 1) {
		return IPath.SEPARATOR + " is not allowed in a module file specifier.";
	}
	if (treeViewer.getStructuredSelection().getFirstElement() == null) {
		return "Please select a module container";
	}

	return null;
}
 
Example 15
Source File: Repository.java    From bonita-studio with GNU General Public License v2.0 4 votes vote down vote up
private boolean isFile(final IPath resourcePath) {
    return resourcePath.getFileExtension() != null;
}
 
Example 16
Source File: WizardSaveAsPage.java    From birt with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Get the saving path
 * 
 * @return the saving path
 */
public IPath getResult( )
{

	IPath path = resourceGroup.getContainerFullPath( )
			.append( resourceGroup.getResource( ) );

	// If the user does not supply a file extension and if the save
	// as dialog was provided a default file name append the extension
	// of the default filename to the new name
	if ( path.getFileExtension( ) == null )
	{
		if ( originalFile != null
				&& originalFile.getFileExtension( ) != null )
			path = path.addFileExtension( originalFile.getFileExtension( ) );
		else if ( originalName != null )
		{
			int pos = originalName.lastIndexOf( '.' );
			if ( ++pos > 0 && pos < originalName.length( ) )
				path = path.addFileExtension( originalName.substring( pos ) );
		}
	}

	// If the path already exists then confirm overwrite.
	IFile file = ResourcesPlugin.getWorkspace( ).getRoot( ).getFile( path );

	if ( file.exists( ) )
	{
		String[] buttons = new String[]{
				IDialogConstants.YES_LABEL,
				IDialogConstants.NO_LABEL,
				IDialogConstants.CANCEL_LABEL
		};
		String question = Messages.getFormattedString( "WizardSaveAsPage.OverwriteQuestion", //$NON-NLS-1$
				new Object[]{
					path.toOSString( )
				} );
		MessageDialog d = new MessageDialog( getShell( ),
				Messages.getString( "WizardSaveAsPage.Question" ), //$NON-NLS-1$
				null,
				question,
				MessageDialog.QUESTION,
				buttons,
				0 );
		int overwrite = d.open( );
		switch ( overwrite )
		{
			case 0 : // Yes
				break;
			case 1 : // No
				return null;
			case 2 : // Cancel
			default :
				return Path.EMPTY;
		}
	}

	return path;
}
 
Example 17
Source File: JavaProject.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * @param path IPath
 * @return A handle to the package fragment root identified by the given path.
 * This method is handle-only and the element may or may not exist. Returns
 * <code>null</code> if unable to generate a handle from the path (for example,
 * an absolute path that has less than 1 segment. The path may be relative or
 * absolute.
 */
public IPackageFragmentRoot getPackageFragmentRoot(IPath path) {
	if (!path.isAbsolute()) {
		path = getPath().append(path);
	}
	int segmentCount = path.segmentCount();
	if (segmentCount == 0) {
		return null;
	}
	if (path.getDevice() != null || JavaModel.getExternalTarget(path, true/*check existence*/) != null) {
		// external path
		return getPackageFragmentRoot0(path);
	}
	IWorkspaceRoot workspaceRoot = this.project.getWorkspace().getRoot();
	IResource resource = workspaceRoot.findMember(path);
	if (resource == null) {
		// resource doesn't exist in workspace
		if (path.getFileExtension() != null) {
			if (!workspaceRoot.getProject(path.segment(0)).exists()) {
				// assume it is an external ZIP archive
				return getPackageFragmentRoot0(path);
			} else {
				// assume it is an internal ZIP archive
				resource = workspaceRoot.getFile(path);
			}
		} else if (segmentCount == 1) {
			// assume it is a project
			String projectName = path.segment(0);
			if (getElementName().equals(projectName)) { // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=75814
				// default root
				resource = this.project;
			} else {
				// lib being another project
				resource = workspaceRoot.getProject(projectName);
			}
		} else {
			// assume it is an internal folder
			resource = workspaceRoot.getFolder(path);
		}
	}
	return getPackageFragmentRoot(resource);
}
 
Example 18
Source File: TraceForTypeRootProvider.java    From xtext-eclipse with Eclipse Public License 2.0 4 votes vote down vote up
protected boolean isZipFile(IPath path) {
	if (path.getFileExtension() == null)
		return false;
	String ext = path.getFileExtension();
	return "jar".equalsIgnoreCase(ext) || "zip".equalsIgnoreCase(ext);
}
 
Example 19
Source File: StorageLabelProvider.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
private Image getImageForJarEntry(IStorage element) {
	if (element instanceof IJarEntryResource && !((IJarEntryResource) element).isFile()) {
		return PlatformUI.getWorkbench().getSharedImages().getImage(ISharedImages.IMG_OBJ_FOLDER);
	}

	if (fJarImageMap == null)
		return getDefaultImage();

	if (element == null || element.getName() == null)
		return getDefaultImage();

	// Try to find icon for full name
	String name= element.getName();
	Image image= fJarImageMap.get(name);
	if (image != null)
		return image;
	IFileEditorMapping[] mappings= getEditorRegistry().getFileEditorMappings();
	int i= 0;
	while (i < mappings.length) {
		if (mappings[i].getLabel().equals(name))
			break;
		i++;
	}
	String key= name;
	if (i == mappings.length) {
		// Try to find icon for extension
		IPath path= element.getFullPath();
		if (path == null)
			return getDefaultImage();
		key= path.getFileExtension();
		if (key == null)
			return getDefaultImage();
		image= fJarImageMap.get(key);
		if (image != null)
			return image;
	}

	// Get the image from the editor registry
	ImageDescriptor desc= getEditorRegistry().getImageDescriptor(name);
	image= desc.createImage();

	fJarImageMap.put(key, image);

	return image;
}
 
Example 20
Source File: NewEditorHelper.java    From depan with Apache License 2.0 3 votes vote down vote up
/**
 * Ensure that we have a file extension on the file name.  This does not
 * overwrite an existing extension, but ensures that at least one extension
 * is present.
 * 
 * @param savePath Initial save path from user
 * @param defExt default extension to add if {@code savePath} lacks one
 * @return valid IFile with an extension.
 */
public static IFile buildNameWithExtension(IPath savePath, String defExt) {
  if (null == savePath.getFileExtension()) {
    savePath.addFileExtension(defExt);
  }
  return ResourcesPlugin.getWorkspace().getRoot().getFile(savePath);
}