Java Code Examples for org.eclipse.core.resources.IFolder#exists()

The following examples show how to use org.eclipse.core.resources.IFolder#exists() . 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: AbstractSarlMavenTest.java    From sarl with Apache License 2.0 6 votes vote down vote up
@Override
protected void createFolders(IProject project, SubMonitor subMonitor,
		Shell shell) throws CoreException {
	if (this.folders != null) {
		for (final String folderName : this.folders) {
			IPath path = Path.fromPortableString(folderName);
			IPath tmpPath = Path.EMPTY;
			for (String segment : path.segments()) {
				tmpPath = tmpPath.append(segment);
				IFolder folder = project.getFolder(tmpPath.toPortableString());
				if (!folder.exists()) {
					folder.create(false, true, subMonitor.newChild(1));
				}
			}
		}
	}
}
 
Example 2
Source File: ResourceUtils.java    From google-cloud-eclipse with Apache License 2.0 6 votes vote down vote up
/**
 * Create the components of the provided folder as required. Assumes the containing project
 * already exists.
 *
 * @param folder the path to be created if it does not already exist
 * @param monitor may be {@code null}
 * @throws CoreException on error
 */
public static void createFolders(IContainer folder, IProgressMonitor monitor)
    throws CoreException {

  IPath path = folder.getProjectRelativePath();
  IContainer current = folder.getProject();
  SubMonitor progress = SubMonitor.convert(monitor, path.segmentCount());
  for (String segment : path.segments()) {
    IFolder child = current.getFolder(new Path(segment));
    if (!child.exists()) {
      child.create(true, true, progress.newChild(1));
    } else {
      progress.worked(1);
    }
    current = child;
  }
}
 
Example 3
Source File: JavaProjectHelper.java    From spotbugs with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * Adds a source container to a IJavaProject.
 *
 * @param jproject
 *            The parent project
 * @param containerName
 *            The name of the new source container
 * @param inclusionFilters
 *            Inclusion filters to set
 * @param exclusionFilters
 *            Exclusion filters to set
 * @return The handle to the new source container
 * @throws CoreException
 *             Creation failed
 */
public static IPackageFragmentRoot addSourceContainer(IJavaProject jproject, String containerName, IPath[] inclusionFilters,
        IPath[] exclusionFilters) throws CoreException {
    IProject project = jproject.getProject();
    IContainer container = null;
    if (containerName == null || containerName.length() == 0) {
        container = project;
    } else {
        IFolder folder = project.getFolder(containerName);
        if (!folder.exists()) {
            CoreUtility.createFolder(folder, false, true, null);
        }
        container = folder;
    }
    IPackageFragmentRoot root = jproject.getPackageFragmentRoot(container);

    IClasspathEntry cpe = JavaCore.newSourceEntry(root.getPath(), inclusionFilters, exclusionFilters, null);
    addToClasspath(jproject, cpe);
    return root;
}
 
Example 4
Source File: DiagramFileStore.java    From bonita-studio with GNU General Public License v2.0 6 votes vote down vote up
@Override
public IStatus build(IPath buildPath, IProgressMonitor monitor) {
    IPath processFolderPath = buildPath.append("process");
    IFolder processFolder = getRepository().getProject()
            .getFolder(processFolderPath.makeRelativeTo(getRepository().getProject().getLocation()));
    if (!processFolder.exists()) {
        try {
            processFolder.create(true, true, new NullProgressMonitor());
        } catch (CoreException e) {
           return e.getStatus();
        }
    }

    Map<String, Object> parameters = new HashMap<>();
    parameters.put("fileName", getName());
    parameters.put("destinationPath", processFolder.getLocation().toOSString());
    parameters.put("process", null);
    monitor.subTask(String.format(Messages.buildingDiagram, getDisplayName()));
    IStatus buildStatus = (IStatus) executeCommand(BUILD_DIAGRAM_COMMAND, parameters);
    if (Objects.equals(buildStatus.getSeverity(), IStatus.ERROR)) {
       return parseStatus(buildStatus);
    }
    return ValidationStatus.ok();
}
 
Example 5
Source File: CodeGenerator.java    From CogniCrypt with Eclipse Public License 2.0 6 votes vote down vote up
/**
 *
 * @param fileToBeAdded
 *        file that ought to be added to the dev project
 * @return <CODE>true</CODE>/<CODE>false</CODE> if file was added successfully (or not).
 * @throws IOException
 * @throws CoreException
 */
protected boolean addAddtionalFile(final File fileToBeAdded) throws IOException, CoreException {
	final IFolder libFolder = this.project.getFolder(Constants.pathsForLibrariesInDevProject);
	if (!libFolder.exists()) {
		libFolder.create(true, true, null);
	}

	final Path memberPath = fileToBeAdded.toPath();
	Files
		.copy(
			memberPath, new File(this.project
				.getProjectPath() + Constants.outerFileSeparator + Constants.pathsForLibrariesInDevProject + Constants.outerFileSeparator + memberPath.getFileName()).toPath(),
			StandardCopyOption.REPLACE_EXISTING);
	final String filePath = fileToBeAdded.toString();
	final String cutPath = filePath.substring(filePath.lastIndexOf(Constants.outerFileSeparator));
	if (Constants.JAR.equals(cutPath.substring(cutPath.indexOf(".")))) {
		if (!this.project.addJar(Constants.pathsForLibrariesInDevProject + Constants.outerFileSeparator + fileToBeAdded.getName())) {
			return false;
		}
	}
	return true;
}
 
Example 6
Source File: WebAppUtilities.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Sets the project's default output directory to the WAR output directory's
 * WEB-INF/classes folder. If the WAR output directory does not have a WEB-INF
 * directory, this method returns without doing anything.
 *
 * @throws CoreException if there's a problem setting the output directory
 */
public static void setOutputLocationToWebInfClasses(IJavaProject javaProject,
    IProgressMonitor monitor) throws CoreException {
  IProject project = javaProject.getProject();

  IFolder webInfOut = getWebInfOut(project);
  if (!webInfOut.exists()) {
    // If the project has no output <WAR>/WEB-INF directory, don't touch the
    // output location
    return;
  }

  IPath oldOutputPath = javaProject.getOutputLocation();
  IPath outputPath = webInfOut.getFullPath().append("classes");

  if (!outputPath.equals(oldOutputPath)) {
    IWorkspaceRoot workspaceRoot = ResourcesPlugin.getWorkspace().getRoot();

    // Remove old output location and contents
    IFolder oldOutputFolder = workspaceRoot.getFolder(oldOutputPath);
    if (oldOutputFolder.exists()) {
      try {
        removeOldClassfiles(oldOutputFolder);
      } catch (Exception e) {
        CorePluginLog.logError(e);
      }
    }

    // Create the new output location if necessary
    IFolder outputFolder = workspaceRoot.getFolder(outputPath);
    if (!outputFolder.exists()) {
      // TODO: Could move recreate this in a utilities class
      CoreUtility.createDerivedFolder(outputFolder, true, true, null);
    }

    javaProject.setOutputLocation(outputPath, monitor);
  }
}
 
Example 7
Source File: CreateGhidraScriptWizardPage.java    From ghidra with Apache License 2.0 5 votes vote down vote up
/**
 * Validates the fields on the page and updates the page's status.
 * Should be called every time a field on the page changes.
 */
private void validate() {

	final String BAD = GhidraProjectUtils.ILLEGAL_FILENAME_CHARS;
	final String BAD_START = GhidraProjectUtils.ILLEGAL_FILENAME_START_CHARS;


	String message = null;
	IFolder scriptFolder = getScriptFolder();
	String scriptName = scriptNameText.getText();


	if (scriptFolder == null) {
		message = "Script folder must be specified";
	}
	else if (!scriptFolder.exists()) {
		message = "Script folder does not exist";
	}
	else if (scriptName.isEmpty()) {
		message = "Script name must be specified";
	}
	else if ((BAD_START + BAD).chars().anyMatch(ch -> scriptName.charAt(0) == ch)) {
		message = "Script name cannot start with an invalid character:\n " + BAD_START + BAD;
	}
	else if (BAD.chars().anyMatch(ch -> scriptName.indexOf(ch) != -1)) {
		message = "Script name cannot contain invalid characters:\n " + BAD;
	}
	else if (scriptFolder.getFile(getScriptName()).exists()) {
		message = "Script already exists";
	}

	setErrorMessage(message);
	setPageComplete(message == null);
}
 
Example 8
Source File: GwtLaunchTargetTester.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 9
Source File: WebProjectUtil.java    From google-cloud-eclipse with Apache License 2.0 5 votes vote down vote up
/**
 * Attempt to resolve the given file within the project's {@code WEB-INF}. Note that this method
 * may return a file that is in a build location (e.g.,
 * {@code target/m2e-wtp/web-resources/WEB-INF}) which may be frequently removed or regenerated.
 *
 * @return the file location or {@code null} if not found
 */
public static IFile findInWebInf(IProject project, IPath filePath) {
  // Try to obtain the directory as if it was a Dynamic Web Project
  IVirtualComponent component = ComponentCore.createComponent(project);
  if (component != null && component.exists()) {
    IVirtualFolder root = component.getRootFolder();
    // the root should exist, but the WEB-INF may not yet exist
    IVirtualFile file = root.getFolder(WEB_INF).getFile(filePath);
    if (file != null && file.exists()) {
      return file.getUnderlyingFile();
    }
    return null;
  }
  // Otherwise check the standard places
  for (String possibleWebInfContainer : DEFAULT_WEB_PATHS) {
    // check each directory component to simplify mocking in tests
    // so we can just say WEB-INF doesn't exist
    IFolder defaultLocation = project.getFolder(possibleWebInfContainer);
    if (defaultLocation != null && defaultLocation.exists()) {
      defaultLocation = defaultLocation.getFolder(WEB_INF);
      if (defaultLocation != null && defaultLocation.exists()) {
        IFile resourceFile = defaultLocation.getFile(filePath);
        if (resourceFile != null && resourceFile.exists()) {
          return resourceFile;
        }
      }
    }
  }
  return null;
}
 
Example 10
Source File: Model.java    From tlaplus with MIT License 5 votes vote down vote up
private IFile getFile(final String id) {
	final IFolder targetFolder = getTargetDirectory();
	if (targetFolder != null && targetFolder.exists()) {
		final IFile teFile = (IFile) targetFolder.findMember(id);
		if (teFile != null && teFile.exists()) {
			return teFile;
		}
	}
	return null;
}
 
Example 11
Source File: RemoteFetchLogWizardRemotePage.java    From tracecompass with Eclipse Public License 2.0 5 votes vote down vote up
private boolean validateProject() {
    if (fCombo != null) {
        int fProjectIndex = fCombo.getSelectionIndex();
        if (fProjectIndex < 0) {
            handleError(RemoteMessages.RemoteFetchLogWizardRemotePage_NoProjectSelectedError, null);
            return false;
        }

        IProject project = fProjects.get(fProjectIndex);
        TmfProjectElement projectElement = TmfProjectRegistry.getProject(project, true);
        TmfTraceFolder tracesFolderElement = projectElement.getTracesFolder();

        if (tracesFolderElement == null) {
            handleError(RemoteMessages.RemoteFetchLogWizardRemotePage_InvalidTracingProject, null);
            return false;
        }

        IFolder traceFolder = tracesFolderElement.getResource();

        if (!traceFolder.exists()) {
            handleError(RemoteMessages.RemoteFetchLogWizardRemotePage_InvalidTracingProject, null);
            return false;
        }

        try {
            if (project.hasNature(TmfProjectNature.ID)) {
                fTmfTraceFolder = projectElement.getTracesFolder();
                fExperimentFolderElement = projectElement.getExperimentsFolder();
            }
        } catch (CoreException ex) {
            handleError(RemoteMessages.RemoteFetchLogWizardRemotePage_InvalidTracingProject, ex);
            return false;
        }
    }
    return true;
}
 
Example 12
Source File: GWTProjectUtilities.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Returns the GWT-applicable source folder paths from a project (note: this
 * will not traverse into the project's dependencies, for this behavior, see
 * {@link #getGWTSourceFolderPathsFromProjectAndDependencies(IJavaProject, boolean)}
 * ).
 *
 * @param javaProject Reference to the project
 * @param sourceEntries The list to be filled with the entries corresponding
 *          to the source folder paths
 * @param includeTestSourceEntries Whether to include the entries for test
 *          source
 * @throws SdkException
 */
private static void fillGWTSourceFolderPathsFromProject(
    IJavaProject javaProject, Collection<? super IRuntimeClasspathEntry>
    sourceEntries, boolean includeTestSourceEntries) throws SdkException {

  assert (javaProject != null);

  if (GWTProjectsRuntime.isGWTRuntimeProject(javaProject)) {
    // TODO: Do we still need to handle this here since Sdk's report their
    // own runtime classpath entries?
    sourceEntries.addAll(GWTProjectsRuntime.getGWTRuntimeProjectSourceEntries(
        javaProject, includeTestSourceEntries));
  } else {
    try {
      for (IClasspathEntry curClasspathEntry : javaProject.getRawClasspath()) {
        if (curClasspathEntry.getEntryKind() == IClasspathEntry.CPE_SOURCE) {
          IPath sourcePath = curClasspathEntry.getPath();
          // If including tests, include all source, or if not including tests, ensure
          // it is not a test path
          if (includeTestSourceEntries || !GWTProjectUtilities.isTestPath(sourcePath)) {
            if (!isOptional(curClasspathEntry) || exists(sourcePath)) {
              sourceEntries.add(JavaRuntime.newArchiveRuntimeClasspathEntry(sourcePath));
            }
          }
        }
      }
      IFolder folder = javaProject.getProject().getFolder("super");
      if (folder.exists()) {
        sourceEntries.add(JavaRuntime.newArchiveRuntimeClasspathEntry(folder.getFullPath()));
      }
    } catch (JavaModelException jme) {
      GWTPluginLog.logError(jme,
          "Unable to retrieve raw classpath for project "
              + javaProject.getProject().getName());
    }
  }
}
 
Example 13
Source File: TmfCommonProjectElement.java    From tracecompass with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Returns the supplementary resources under the trace supplementary folder.
 *
 * @return array of resources under the trace supplementary folder.
 */
public IResource[] getSupplementaryResources() {
    IFolder supplFolder = getTraceSupplementaryFolder(getSupplementaryFolderPath());
    if (supplFolder.exists()) {
        try {
            return supplFolder.members();
        } catch (CoreException e) {
            Activator.getDefault().logError("Error deleting supplementary folder " + supplFolder, e); //$NON-NLS-1$
        }
    }
    return new IResource[0];
}
 
Example 14
Source File: LibraryClasspathContainerSerializer.java    From google-cloud-eclipse with Apache License 2.0 5 votes vote down vote up
private IFile getFile(IJavaProject javaProject, String id, boolean create)
    throws CoreException {
  IFolder settingsFolder = javaProject.getProject().getFolder(".settings"); //$NON-NLS-1$
  IFolder folder =
      settingsFolder.getFolder(FrameworkUtil.getBundle(getClass()).getSymbolicName());
  if (!folder.exists() && create) {
    ResourceUtils.createFolders(folder, null);
  }
  IFile containerFile = folder.getFile(id + ".container"); //$NON-NLS-1$
  return containerFile;
}
 
Example 15
Source File: FileUtils.java    From saros with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Creates the given folder. All parent folder may be created on demand if necessary.
 *
 * @param folder the folder to create
 * @throws CoreException
 */
public static void create(final IFolder folder) throws CoreException {
  if (folder.exists()) {
    log.warn("folder already exists: " + folder, new StackTrace());
    return;
  }

  mkdirs(folder);
  folder.create(false, true, null);
}
 
Example 16
Source File: WebFragmentRepositoryStore.java    From bonita-studio with GNU General Public License v2.0 5 votes vote down vote up
@Override
public WebFragmentFileStore createRepositoryFileStore(final String fileName) {
    IFolder folder = getResource().getFolder(fileName);
    if (folder.exists()) {
        return folder.getFile(fileName + ".json").exists() ? new WebFragmentFileStore(fileName, this) : null;
    }
    return new WebFragmentFileStore(fileName, this);
}
 
Example 17
Source File: SARLProjectConfigurator.java    From sarl with Apache License 2.0 5 votes vote down vote up
private static IFolder ensureOutputFolder(IProject project, String folderPath, boolean isIFolderRequired,
		boolean createFolder, IProgressMonitor monitor) throws CoreException {
	final IFolder folder = project.getFolder(Path.fromPortableString(folderPath));
	if (!folder.exists()) {
		if (createFolder) {
			CoreUtility.createFolder(folder, true, true, monitor);
		} else if (!isIFolderRequired) {
			monitor.done();
			return null;
		}
	}
	setDerived(folder);
	monitor.done();
	return folder;
}
 
Example 18
Source File: ProjectTestsUtils.java    From n4js with Eclipse Public License 1.0 5 votes vote down vote up
/** Applies the Xtext nature to the project and creates (if necessary) and returns the source folder. */
public static IFolder configureProjectWithXtext(IProject project, String sourceFolder) throws CoreException {
	addNature(project.getProject(), XtextProjectHelper.NATURE_ID);
	IFolder folder = project.getProject().getFolder(sourceFolder);
	if (!folder.exists()) {
		folder.create(true, true, null);
	}
	return folder;
}
 
Example 19
Source File: SavedModuleContributionItem.java    From tlaplus with MIT License 4 votes vote down vote up
protected IContributionItem[] getContributionItems()
{
    /*
     * Does nothing if the active editor is not a model editor. The
     * following code gets the config file for the active model editor (if
     * it is the active editor), gets the model folder for that config,
     * iterates through all members of the model folder, adding a
     * contribution item for each member that has extension .tla and is not
     * TE.tla or MC.tla.
     */
    IEditorPart editor = UIHelper.getActiveEditor();
    if (editor instanceof ModelEditor)
    {
        IFolder modelFolder = ((ModelEditor) editor).getModel().getTargetDirectory();
        if (modelFolder != null && modelFolder.exists())
        {
            try
            {
                /*
                 * The collection of command contribution items that will
                 * populate the menu and contain the command to be run when
                 * selected.
                 */
                final List<IContributionItem> contributions = new ArrayList<IContributionItem>();

                // get all resources in the model folder
                IResource[] members = modelFolder.members();
                for (int i = 0; i < members.length; i++)
                {
                    /*
                     * We add to the menu an option to open every file that
                     * has exists, has extension .tla, and is not the TE or
                     * MC file.
                     * 
                     * On Nov 2011, DR added a null check to members[i].getFileExtension() which
                     * can return null for directories.
                     */
                    if (members[i].exists() && members[i].getFileExtension() != null
                            && members[i].getFileExtension().equals(ResourceHelper.TLA_EXTENSION)
                            && !members[i].getName().equals(TLAConstants.Files.MODEL_CHECK_TLA_FILE)
                            && !members[i].getName().equals(ModelHelper.TE_FILE_TLA))
                    {
                        Map<String, String> parameters = new HashMap<String, String>(1);
                        parameters.put(OpenSavedModuleHandler.PARAM_MODULE_PATH, members[i].getRawLocation()
                                .toPortableString());
                        contributions.add(new CommandContributionItem(new CommandContributionItemParameter(UIHelper
                                .getActiveWindow(), "toolbox.command.model.open.savedModule.",
                                OpenSavedModuleHandler.COMMAND_ID, parameters, null, null, null, members[i]
                                        .getName(), null, "Opens the version saved in the last run of TLC.",
                                SWT.PUSH, null, true)));
                    }
                }

                return (IContributionItem[]) contributions.toArray(new IContributionItem[contributions.size()]);
            } catch (CoreException e)
            {
                TLCUIActivator.getDefault().logError("Error getting members of model folder " + modelFolder, e);
            }
        }
    }
    return new IContributionItem[0];
}
 
Example 20
Source File: ResourceUtil.java    From eclipse.jdt.ls with Eclipse Public License 2.0 3 votes vote down vote up
/**
 * Creates a folder and all parent folders if not existing. Project must exist.
 * <code> org.eclipse.ui.dialogs.ContainerGenerator</code> is too heavy (creates
 * a runnable)
 *
 * @param folder
 *            the folder to create
 * @param force
 *            a flag controlling how to deal with resources that are not in sync
 *            with the local file system
 * @param local
 *            a flag controlling whether or not the folder will be local after
 *            the creation
 * @param monitor
 *            the progress monitor
 * @throws CoreException
 *             thrown if the creation failed
 */
public static void createFolder(IFolder folder, boolean force, boolean local, IProgressMonitor monitor) throws CoreException {
	if (!folder.exists()) {
		IContainer parent = folder.getParent();
		if (parent instanceof IFolder) {
			createFolder((IFolder) parent, force, local, null);
		}
		folder.create(force, local, monitor);
	}
}