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

The following examples show how to use org.eclipse.core.resources.IFile#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: SarlClassPathDetector.java    From sarl with Apache License 2.0 6 votes vote down vote up
/** Visit the given Java compilation unit.
 *
 * @param jfile the compilation unit.
 */
protected void visitJavaCompilationUnit(IFile jfile) {
	final ICompilationUnit cu = JavaCore.createCompilationUnitFrom(jfile);
	if (cu != null) {
		final ASTParser parser = ASTParser.newParser(IASTSharedValues.SHARED_AST_LEVEL);
		parser.setSource(cu);
		parser.setFocalPosition(0);
		final CompilationUnit root = (CompilationUnit) parser.createAST(null);
		final PackageDeclaration packDecl = root.getPackage();

		final IPath packPath = jfile.getParent().getFullPath();
		final String cuName = jfile.getName();
		if (packDecl == null) {
			addToMap(this.sourceFolders, packPath, new Path(cuName));
		} else {
			final IPath relPath = new Path(packDecl.getName().getFullyQualifiedName().replace('.', '/'));
			final IPath folderPath = getFolderPath(packPath, relPath);
			if (folderPath != null) {
				addToMap(this.sourceFolders, folderPath, relPath.append(cuName));
			}
		}
	}
}
 
Example 2
Source File: PyOpenPythonFileAction.java    From Pydev with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * @return whether the current selection enables this action (not considering selected containers).
 */
public boolean isEnabledForSelectionWithoutContainers() {
    fillSelections();
    if (filesSelected.size() > 0) {
        for (IFile f : filesSelected) {
            String name = f.getName();
            if (name.indexOf('.') == -1) {
                //Always add this menu if there's some file that doesn't have an extension.
                return true;
            }
        }
    }
    if (nodesSelected.size() > 0 || pythonPathFilesSelected.size() > 0 || pythonPathZipFilesSelected.size() > 0) {
        return true;
    }
    return false;
}
 
Example 3
Source File: ModulaSearchResultPage.java    From xds-ide with Eclipse Public License 1.0 6 votes vote down vote up
private String getMIName(ModelItem mi) {
    IFile iFile= mi.getIFile();
          IXdsElement ixe = mi.getIXdsElement();
          String res = "9";
          if (ixe != null) {
              if (ixe instanceof IXdsProject) {
                  res = "1";
              } else if (ixe instanceof IXdsExternalDependenciesContainer) {
                  res = "2";
              } else if (ixe instanceof IXdsSdkLibraryContainer) {
                  res = "3";
              } else if (ixe instanceof IXdsContainer) {
                  res = "4";
              }
          }
          
    if (iFile != null) {
        res += iFile.getName();
    }
    if (ixe != null) {
        res += ixe.getElementName();
    }
    return res;
}
 
Example 4
Source File: PyEdit.java    From Pydev with Eclipse Public License 1.0 6 votes vote down vote up
private void checkAddInvalidModuleNameMarker(IDocument doc, IFile file) {
    try {
        String name = file.getName();
        int i = name.lastIndexOf('.');
        if (i > 0) {
            String modName = name.substring(0, i);
            if (!PythonPathHelper.isValidModuleLastPart(modName)) {
                addInvalidModuleMarker(doc, file, "Invalid name for Python module: " + modName
                        + " (it'll not be analyzed)");
                return;

            } else if (!PythonPathHelper.isValidSourceFile(name)) {
                addInvalidModuleMarker(doc, file, "Module: " + modName
                        + " does not have a valid Python extension (it'll not be analyzed).");
                return;
            }
        }
        //if it still hasn't returned, remove any existing marker (i.e.: rename operation)
        removeInvalidModuleMarkers(file);
    } catch (Exception e) {
        Log.log(e);
    }
}
 
Example 5
Source File: AbstractRepositoryStore.java    From bonita-studio with GNU General Public License v2.0 6 votes vote down vote up
@Override
public void migrate(final IProgressMonitor monitor) throws CoreException, MigrationException {
    List<IFile> filesToMigrate = getChildren().stream()
            .filter(fs -> !fs.isReadOnly())
            .filter(IRepositoryFileStore::canBeShared)
            .map(IRepositoryFileStore::getResource)
            .filter(IFile.class::isInstance)
            .map(IFile.class::cast)
            .filter(IFile::exists)
            .collect(Collectors.toList());

    for (IFile file : filesToMigrate) {
        monitor.subTask(file.getName());
        InputStream newIs;
        try (final InputStream is = file.getContents()) {
            newIs = handlePreImport(file.getName(), is);
            if (!is.equals(newIs)) {
                file.setContents(newIs, IResource.FORCE, monitor);
                file.refreshLocal(IResource.DEPTH_ONE, monitor);
            }
        } catch (final IOException e) {
            throw new MigrationException("Cannot migrate resource " + file.getName() + " (not a valid file)", e);
        }
    }
}
 
Example 6
Source File: NewPackageWizardPage.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private boolean packageDocumentationAlreadyExists(IPackageFragment pack) throws JavaModelException {
	ICompilationUnit packageInfoJava= pack.getCompilationUnit(PACKAGE_INFO_JAVA_FILENAME);
	if (packageInfoJava.exists()) {
		return true;
	}
	Object[] nonJavaResources= pack.getNonJavaResources();
	for (int i= 0; i < nonJavaResources.length; i++) {
		Object resource= nonJavaResources[i];
		if (resource instanceof IFile) {
			IFile file= (IFile) resource;
			String fileName= file.getName();
			if (PACKAGE_HTML_FILENAME.equals(fileName)) {
				return true;
			}
		}
	}
	return false;
}
 
Example 7
Source File: TLAFilteredItemsSelectionDialog.java    From tlaplus with MIT License 5 votes vote down vote up
public String getText(final Object element) {
	if (element == null) {
		return null;
	}
	if (element instanceof Spec) {
		final Spec spec = (Spec) element;
		final IFile root = spec.getRootFile();
		if (root == null) {
			return null;
		}
		return spec.getName() + " [ " + root.getName() + " ]";
	} else if (element instanceof Module) {
		return ((Module) element).getModuleName();
	} else if (element instanceof Model) {
		final Model model = (Model) element;
		try {
			String attribute = model.getComments();
			if (toggleShowConstantsAction.isChecked() && EMPTY_STRING.equals(attribute)) {
				attribute = ModelHelper.prettyPrintConstants(model, ", ");
			}
			if (!EMPTY_STRING.equals(attribute)) {
				if (attribute.contains("\n")) {
					attribute = attribute.split("\n")[0];
				}
				return model.getName() + DELIM + " " + attribute;
			}
		} catch (CoreException e) {
		}
		return model.getName();
	} else if (element instanceof ItemsListSeparator) {
		final ItemsListSeparator ils = (ItemsListSeparator) element;
		return ils.getName();
	}
	return null;
}
 
Example 8
Source File: GenerateXpectReportShortcut.java    From n4js with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Launch an file, using the file information, which means using default launch configurations.
 */
protected void generateBug(IFile fileSelectedToRun) {
	String content = "";

	try {
		content = new String(Files.readAllBytes(Paths.get(fileSelectedToRun.getRawLocationURI())));
	} catch (IOException e) {
		throw new RuntimeException("Cannot read provided file " + fileSelectedToRun.getName(), e);
	}

	System.out.println(content);
	generateAndDisplayReport(fileSelectedToRun.getName(), content);
}
 
Example 9
Source File: StandardImportAndReadSmokeTest.java    From tracecompass with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Test import from a nested empty archive. This should not import anything.
 *
 * @throws Exception
 *             on error
 */
@Test
public void testNestedEmptyArchive() throws Exception {
    IProject project = getProjectResource();

    // Create the empty archive from an empty folder
    String testArchivePath = createEmptyArchive();

    // Rename archive so that we can create a new one with the same name
    project.refreshLocal(IResource.DEPTH_ONE, null);
    IFile[] files = project.getWorkspace().getRoot().findFilesForLocationURI(new File(testArchivePath).toURI());
    IFile archiveFile = files[0];
    String newEmptyArchiveName = "nested" + archiveFile.getName();
    IPath dest = archiveFile.getFullPath().removeLastSegments(1).append(newEmptyArchiveName);
    archiveFile.move(dest, true, null);
    IFile renamedArchiveFile = archiveFile.getWorkspace().getRoot().getFile(dest);

    createArchive(renamedArchiveFile);
    renamedArchiveFile.delete(true, null);

    openImportWizard();
    SWTBotImportWizardUtils.selectImportFromArchive(fBot, testArchivePath);
    selectFolder(ARCHIVE_ROOT_ELEMENT_NAME);
    SWTBotImportWizardUtils.setOptions(fBot, 0, ImportTraceWizardPage.TRACE_TYPE_AUTO_DETECT);
    importFinish();

    assertNoTraces();

    SWTBotUtils.clearTracesFolder(fBot, TRACE_PROJECT_NAME);
    Files.delete(Paths.get(testArchivePath));
}
 
Example 10
Source File: CheckProjectHelper.java    From dsl-devkit with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Gets the catalog plugin path.
 *
 * @param catalog
 *          the catalog
 * @return the catalog plugin path
 */
public String getCatalogPluginPath(final CheckCatalog catalog) {
  final URI uri = EcoreUtil.getURI(catalog);
  IFile file = RuntimeProjectUtil.findFileStorage(uri, mapper);
  IJavaProject project = JavaCore.create(file.getProject());
  try {
    IPackageFragment packageFragment = project.findPackageFragment(file.getParent().getFullPath());
    String result = packageFragment.getElementName().replace('.', '/');
    return result + '/' + file.getName();
  } catch (JavaModelException e) {
    LOGGER.error("Could not determine plugin path for catalog " + catalog.getName(), e);
  }
  return null;
}
 
Example 11
Source File: BluemixUtil.java    From XPagesExtensionLibrary with Apache License 2.0 5 votes vote down vote up
public static String getXPageName(IFile file) {
    try {
        IDesignElement desEl = DominoResourcesPlugin.getDesignElement(file);
        if((desEl != null) && desEl.getMetaModelID().equals(IMetaModelConstants.XSPPAGES)) {
            return file.getName();
        }
    } catch (CoreException e) {
        if (BluemixLogger.BLUEMIX_LOGGER.isErrorEnabled()) {
            BluemixLogger.BLUEMIX_LOGGER.errorp(BluemixUtil.class, "getXPageName", e, "Failed to get design element"); // $NON-NLS-1$ $NLE-BluemixUtil.Failedtogetdesignelement-2$
        }
    }       
    
    return null;
}
 
Example 12
Source File: ResourceNameTemplateVariableResolver.java    From dsl-devkit with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public List<String> resolveValues(final TemplateVariable variable, final XtextTemplateContext templateContext) {
  final List<String> result = Lists.newArrayList();
  final IDocument document = templateContext.getDocument();
  final Object obj = variable.getVariableType().getParams().iterator().next();
  if (obj instanceof String) {
    final String variableName = (String) obj;
    final IXtextDocument xtextDocument = (IXtextDocument) document;
    final IFile file = xtextDocument.getAdapter(IFile.class);

    switch (variableName) {
    case "package": //$NON-NLS-1$
      if (document instanceof IXtextDocument && file != null && file.getParent() instanceof IFolder) {
        final IJavaProject javaProject = JavaCore.create(file.getProject());
        try {
          final IPackageFragment packageFragment = javaProject.findPackageFragment(file.getParent().getFullPath());
          result.add(packageFragment.getElementName());
        } catch (final JavaModelException e) {
          LOGGER.error("Could not determine package for file of given document"); //$NON-NLS-1$
        }
      }
      break;
    case "file": //$NON-NLS-1$
      final String fileName = file.getName();
      result.add(fileName.indexOf('.') > 0 ? fileName.substring(0, fileName.lastIndexOf('.')) : fileName);
    }
  }
  return Lists.newArrayList(Iterables.filter(result, Predicates.notNull()));
}
 
Example 13
Source File: NewQuestionnaireWizard.java    From slr-toolkit with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public boolean performFinish() {
	IFile f = pageFileName.createNewFile();
	if (f == null) {
		return false;
	}
	Questionnaire q = pageUseBase.getQuestionnaire();
	if (q == null) 
		q = new Questionnaire(f.getName());
	q.setName(f.getName());
	q.setDirty(true);
	QuestionnaireStorage.getInstance().persist(f, q);
	return true;
}
 
Example 14
Source File: InstantHandler.java    From txtUML with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Gets the FileName without extension
 * @param file - The File
 * @return - Filname without extension
 */
private String getFileNameWithOutExtension(IFile file){
	String name = file.getName();
	int pos = name.lastIndexOf(".");
	if (pos > 0) {
	    name = name.substring(0, pos);
	}
	return name;
}
 
Example 15
Source File: PlantUmlGenerator.java    From txtUML with Eclipse Public License 1.0 5 votes vote down vote up
private void createTargetFile(String compiledOutput, IFile targetFile) throws ExportRuntimeException {
	ByteArrayInputStream stream = new ByteArrayInputStream(compiledOutput.getBytes());

	try {
		targetFile.create(stream, true, null);
	} catch (Exception e) {
		throw new ExportRuntimeException(
				"Couldn't create target file: " + targetFile.getName() + "\n Reason: " + e.getMessage());
	}
}
 
Example 16
Source File: AbstractExportAction.java    From erflute with Apache License 2.0 5 votes vote down vote up
protected String getDiagramFileName(IEditorPart editorPart, GraphicalViewer viewer) {
    final IFile file = ((IFileEditorInput) editorPart.getEditorInput()).getFile();
    final String fileName = file.getName();
    final String pureName = fileName.substring(0, fileName.lastIndexOf("."));
    final Object diagram = extractDiagram(viewer);
    final String suffix;
    if (isUseVirtualDiagramSuffix() && diagram instanceof ERVirtualDiagram) {
        final String diagramName = ((ERVirtualDiagram) diagram).getName();
        suffix = "-" + diagramName;
    } else {
        suffix = "";
    }
    return pureName + suffix + getDefaultExtension();
}
 
Example 17
Source File: ResourceUtils.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Returns the filename without its file extension (if present). Note that
 * this only removes the last extension, in the case of multiple extensions.
 * Note that if the file has a leading dot (e.g. hidden files), this method
 * will return an empty string.
 */
public static String filenameWithoutExtension(IFile file) {
  String filename = file.getName();
  int extPos = filename.lastIndexOf('.');
  if (extPos == -1) {
    return filename;
  }
  return filename.substring(0, extPos);
}
 
Example 18
Source File: ClasspathResourceUtilities.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Returns the given file or JAR entry if it is on the given package fragment. The file can be a Java file, class
 * file, or a non-Java resource.
 * <p>
 * This method returns null for .java files or .class files inside JARs.
 *
 * @param fileName
 *          the file name
 * @param pckgFragment
 *          the package fragment to search
 * @return the file as an IResource or IJarEntryResource, or null
 * @throws JavaModelException
 */
public static IStorage resolveFileOnPackageFragment(String fileName, IPackageFragment pckgFragment)
    throws JavaModelException {

  boolean isJavaFile = JavaCore.isJavaLikeFileName(fileName);
  boolean isClassFile = ResourceUtils.endsWith(fileName, ".class");

  // Check the non-Java resources first
  Object[] nonJavaResources = pckgFragment.getNonJavaResources();
  for (Object nonJavaResource : nonJavaResources) {
    if (nonJavaResource instanceof IFile) {
      IFile file = (IFile) nonJavaResource;
      String resFileName = file.getName();

      if (ResourceUtils.areFilenamesEqual(resFileName, fileName)) {
        // Java source files that have been excluded from the build path
        // show up as non-Java resources, but we'll ignore them since
        // they're not available on the classpath.
        if (!JavaCore.isJavaLikeFileName(resFileName)) {
          return file;
        } else {
          return null;
        }
      }
    }

    // JAR resources are not IResource's, so we need to handle them
    // differently
    if (nonJavaResource instanceof IJarEntryResource) {
      IJarEntryResource jarEntry = (IJarEntryResource) nonJavaResource;
      if (jarEntry.isFile() && ResourceUtils.areFilenamesEqual(jarEntry.getName(), fileName)) {
        return jarEntry;
      }
    }
  }

  // If we're looking for a .java or .class file, we can use the regular
  // Java Model methods.

  if (isJavaFile) {
    ICompilationUnit cu = pckgFragment.getCompilationUnit(fileName);
    if (cu.exists()) {
      return (IFile) cu.getCorrespondingResource();
    }
  }

  if (isClassFile) {
    IClassFile cf = pckgFragment.getClassFile(fileName);
    if (cf.exists()) {
      return (IFile) cf.getCorrespondingResource();
    }
  }

  return null;
}
 
Example 19
Source File: AbstractCompareWithRouteActionHandler.java    From eip-designer with Apache License 2.0 4 votes vote down vote up
/**
 * The command has been executed, so extract the needed information
 * from the application context.
 */
@Override
public Object execute(ExecutionEvent event) throws ExecutionException {
   ISelection currentSelection = HandlerUtil.getCurrentSelection(event);
   
   if (currentSelection != null && currentSelection instanceof IStructuredSelection) {
      // Retrieve file corresponding to current selection.
      IStructuredSelection selection = (IStructuredSelection)currentSelection;
      IFile selectionFile = (IFile)selection.getFirstElement();
      
      // Open compare target selection dialog.
      CompareTargetSelectionDialog dialog = new CompareTargetSelectionDialog(
            HandlerUtil.getActiveShellChecked(event), 
            selectionFile.getName());
      
      if (dialog.open() != Window.OK) {
         return null;
      }
      
      // Ask concrete subclass to parse source file and extract Route for comparison.
      Route left = extractRouteFromFile(selectionFile);
      
      // Retrieve EMF Object corresponding to selected reference Route.
      Route right = dialog.getSelectedRoute();
      
      // Cause Spring parser cannot retrieve route name, force it using those of the model.
      // TODO Find a fix later for that in the generator/parser couple
      left.setName(right.getName());
      
      // Launch EMFCompare UI with input.
      EMFCompareConfiguration configuration = new EMFCompareConfiguration(new CompareConfiguration());
      ICompareEditingDomain editingDomain = EMFCompareEditingDomain.create(left, right, null);
      AdapterFactory adapterFactory = new ComposedAdapterFactory(ComposedAdapterFactory.Descriptor.Registry.INSTANCE);
      EMFCompare comparator = EMFCompare.builder().setPostProcessorRegistry(EMFCompareRCPPlugin.getDefault().getPostProcessorRegistry()).build();
      IComparisonScope scope = new DefaultComparisonScope(left, right, null);
      
      CompareEditorInput input = new ComparisonScopeEditorInput(configuration, editingDomain, adapterFactory, comparator, scope);
      CompareUI.openCompareDialog(input);
   }
   
   return null;
}
 
Example 20
Source File: AppEngineProjectElement.java    From google-cloud-eclipse with Apache License 2.0 4 votes vote down vote up
/**
 * Update to the set of resource modifications in this project (added, removed, or changed).
 * Return {@code true} if there were changes.
 *
 * @throws AppEngineException when some error occurred parsing or interpreting some relevant file
 */
public boolean resourcesChanged(Collection<IFile> changedFiles) throws AppEngineException {
  Preconditions.checkNotNull(changedFiles);
  Preconditions.checkNotNull(descriptorFile);

  boolean layoutChanged = hasLayoutChanged(changedFiles); // files may be newly exposed or removed
  boolean hasNewDescriptor =
      (layoutChanged || hasAppEngineDescriptor(changedFiles))
          && !descriptorFile.equals(findAppEngineDescriptor(project));

  if (changedFiles.contains(descriptorFile) || hasNewDescriptor) {
    // reload everything: e.g., may no longer be "default"
    reload();
    return true;
  } else if (!descriptorFile.exists()) {
    // if our descriptor was removed then we're not really an App Engine project
    throw new AppEngineException(descriptorFile.getName() + " no longer exists");
  }
  // So descriptor is unchanged.

  if (!isDefaultService()) {
    // Only the default service carries ancilliary configuration files
    Preconditions.checkState(configurations.isEmpty());
    return false;
  } else if (layoutChanged) {
    // Reload as new configuration files may have become available or previous
    // configuration files may have disappeared
    return reloadConfigurationFiles();
  }

  // Since this is called on any file change to the project (e.g., to a java or text file),
  // we walk the files and see if they may correspond to an App Engine configuration file to
  // avoid unnecessary work. Since the layout hasn't changed then (1) reload any changed
  // configuration file models, (2) remove any deleted models, and (3) add models for new files.
  boolean changed = false;
  for (IFile file : changedFiles) {
    String baseName = file.getName();
    AppEngineResourceElement previous = configurations.get(baseName);
    if (previous != null) {
      // Since first file resolved wins check if this file was (and thus remains) the winner
      if (file.equals(previous.getFile())) {
        // Case 1 and 2: reload() returns null if underlying file no longer exists
        configurations.compute(baseName, (ignored, element) -> element.reload());
        changed = true;
      }
    } else if (elementFactories.containsKey(baseName)) {
      // Case 3: file has a recognized configuration file name
      AppEngineResourceElement current = configurations.compute(baseName, this::updateElement);
      // updateElement() returns null if file not resolved
      changed |= current != null;
    }
  }
  return changed;
}