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

The following examples show how to use org.eclipse.core.resources.IFolder#create() . 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: AbstractWorkbenchTestCase.java    From Pydev with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Creates a source folder and configures the project to use it and the junit.jar
 *
 * @param addNature if false, no nature will be initially added to the project (if true, the nature will be added)
 */
protected IFolder createSourceFolder(IProgressMonitor monitor, IProject project, boolean addNature,
        boolean isJython)
        throws CoreException {
    IFolder sourceFolder = project.getFolder(new Path("src"));
    if (!sourceFolder.exists()) {
        sourceFolder.create(true, true, monitor);
    }
    if (addNature) {
        String name = project.getName();
        if (isJython) {
            PythonNature.addNature(project, monitor, PythonNature.JYTHON_VERSION_2_5, "/" + name +
                    "/src|/" + name
                    +
                    "/grinder.jar", null, null, null);
        } else {
            PythonNature.addNature(project, monitor, PythonNature.PYTHON_VERSION_2_6, "/" + name +
                    "/src", null,
                    null, null);
        }
    }
    return sourceFolder;
}
 
Example 2
Source File: EclipseBasedProjectModelSetup.java    From n4js with Eclipse Public License 1.0 6 votes vote down vote up
private void createProject(N4JSProjectName projectName, String string)
		throws CoreException, UnsupportedEncodingException {
	IProject project = workspace.getProject(projectName.toEclipseProjectName().getRawName());
	IFile projectDescriptionFile = project.getFile(PROJECT_DESCRIPTION_FILENAME);
	@SuppressWarnings("resource")
	StringInputStream content = new StringInputStream(string, Charsets.UTF_8.name());
	projectDescriptionFile.create(content, false, null);
	projectDescriptionFile.setCharset(Charsets.UTF_8.name(), null);

	IFolder src = project.getFolder("src");
	src.create(false, true, null);
	IFolder sub = src.getFolder("sub");
	sub.create(false, true, null);
	IFolder leaf = sub.getFolder("leaf");
	leaf.create(false, true, null);
	src.getFile("A.js").create(new ByteArrayInputStream(new byte[0]), false, null);
	src.getFile("B.js").create(new ByteArrayInputStream(new byte[0]), false, null);
	sub.getFile("B.js").create(new ByteArrayInputStream(new byte[0]), false, null);
	sub.getFile("C.js").create(new ByteArrayInputStream(new byte[0]), false, null);
	leaf.getFile("D.js").create(new ByteArrayInputStream(new byte[0]), false, null);

	ProjectTestsUtils.createDummyN4JSRuntime(project);
}
 
Example 3
Source File: UIResourceChangeRegistryTest.java    From xtext-xtend with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void testFolderChildren() {
  try {
    final IProject project = WorkbenchTestHelper.createPluginProject("foo");
    final String folderPath = "/foo/bar";
    this.resourceChangeRegistry.registerGetChildren(folderPath, this.uri);
    Assert.assertTrue(this.resourceChangeRegistry.getChildrenListeners().containsKey(folderPath));
    final IFolder folder = project.getFolder("bar");
    final WorkspaceModifyOperation _function = new WorkspaceModifyOperation() {
      @Override
      protected void execute(final IProgressMonitor it) throws CoreException, InvocationTargetException, InterruptedException {
        folder.create(true, true, null);
      }
    };
    this.modifyWorkspace(_function);
    Assert.assertFalse(this.resourceChangeRegistry.getChildrenListeners().containsKey(folderPath));
    Assert.assertEquals(1, this.resourceChangeRegistry.queuedURIs.size());
  } catch (Throwable _e) {
    throw Exceptions.sneakyThrow(_e);
  }
}
 
Example 4
Source File: FileUtils.java    From gama with GNU General Public License v3.0 6 votes vote down vote up
private static IFolder createExternalFolder(final URI workspaceResource) {
	if (workspaceResource == null || !isFileExistingInWorkspace(workspaceResource)) { return null; }
	final IFile root = getWorkspaceFile(workspaceResource);
	final IProject project = root.getProject();
	if (!project.exists()) { return null; }
	final IFolder folder = project.getFolder(EXTERNAL_FOLDER_PATH);
	if (!folder.exists()) {
		try {
			folder.create(true, true, null);
		} catch (final CoreException e) {
			e.printStackTrace();
			return null;
		}
	}
	return folder;
}
 
Example 5
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 6
Source File: ImportProjectWizardPage2.java    From tmxeditor8 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * 获取指定节点被选择的子节点
 * @param parentResource 树节点的父节点
 * @param parentFolder 项目空间的父文件夹
 * @return
 */
private void createCurProjectResource(ProjectResource parentResource, IFolder parentContainer) throws Exception{
	if (parentResource == null || parentContainer == null) {
		return;
	}
	for(Object obj : selectContentProvider.getChildren(parentResource)){
		if (obj instanceof ProjectResource) {
			ProjectResource proResource = (ProjectResource) obj;
			if (!selectElementTree.getChecked(proResource)) {
				continue;
			}
			
			// 如果是文件夹,如果没有创建,直接创建
			if (proResource.isFolder()) {
				IFolder childFolder = parentContainer.getFolder(proResource.getLabel());
				if (!childFolder.exists()) {
					childFolder.create(true, true, null);
				}
				createCurProjectResource(proResource, childFolder);
			}else {
				// 如果是文件,则判断是否需要覆盖,若是,则直接覆盖
				if (proResource.isNeedCover()) {
					IFile iFile = parentContainer.getFile(proResource.getLabel());
					InputStream inputStream = proResource.getInputStream();
					if (inputStream != null) {
						if (iFile.exists()) {
							closeOpenedFile(iFile);
							iFile.delete(true, null);
						}
						iFile.create(inputStream, true, null);
					}
				}
			}
		}
	}
}
 
Example 7
Source File: NewHostPageWizard.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public boolean performFinish() {
  IFolder folder = ResourcesPlugin.getWorkspace().getRoot().getFolder(
      wizardPage.getPath());
  if (!folder.exists()) {
    try {
      folder.create(true, true, null);
    } catch (CoreException e) {
      GWTPluginLog.logError(e);
      return false;
    }
  }

  return super.performFinish();
}
 
Example 8
Source File: JavaProjectSetupUtil.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
public static IFolder createExternalFolder(String folderName) throws CoreException {
		IPath externalFolderPath = new Path(folderName);
		IProject externalFoldersProject = JavaModelManager.getExternalManager().getExternalFoldersProject();
		if (!externalFoldersProject.isAccessible()) {
			if (!externalFoldersProject.exists())
				externalFoldersProject.create(monitor());
			externalFoldersProject.open(monitor());
		}
		IFolder result = externalFoldersProject.getFolder(externalFolderPath);
		result.create(true, false, null);
//		JavaModelManager.getExternalManager().addFolder(result.getFullPath());
		return result;
	}
 
Example 9
Source File: ProjectHelper.java    From eclipse-extras with Eclipse Public License 1.0 5 votes vote down vote up
public IFolder createFolder( String name ) throws CoreException {
  initializeProject();
  String[] segments = new Path( name ).segments();
  IContainer container = project;
  for( String segment : segments ) {
    IFolder newFolder = container.getFolder( new Path( segment ) );
    if( !newFolder.exists() ) {
      newFolder.create( true, true, newProgressMonitor() );
    }
    container = newFolder;
  }
  return project.getFolder( new Path( name ) );
}
 
Example 10
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 11
Source File: BirtWizardUtil.java    From birt with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Make Directory
 * 
 * @param folder
 * @throws CoreException
 */
public static void mkdirs( final IFolder folder ) throws CoreException
{
	if ( !folder.exists( ) )
	{
		if ( folder.getParent( ) instanceof IFolder )
		{
			mkdirs( (IFolder) folder.getParent( ) );
		}

		folder.create( true, true, null );
	}
}
 
Example 12
Source File: NewProjectWizard.java    From tmxeditor8 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * 创建子目录
 * @param parentFolder
 *            父目录
 * @param childrenFolderNames
 *            子目录名称
 * @throws CoreException
 *             ;
 */
private void createChildrenFoders(IFolder parentFolder, String[] childrenFolderNames) throws CoreException {
	if (parentFolder.exists()) {
		for (String childName : childrenFolderNames) {
			IFolder folder = parentFolder.getFolder(childName);
			if (!folder.exists()) {
				folder.create(true, true, null);
			}
		}
	}
}
 
Example 13
Source File: CheckProjectFactory.java    From dsl-devkit with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Overridden in order to change BundleVendor. {@inheritDoc}
 */
@SuppressWarnings("PMD.InsufficientStringBufferDeclaration")
@Override
protected void createManifest(final IProject project, final IProgressMonitor progressMonitor) throws CoreException {
  final StringBuilder content = new StringBuilder("Manifest-Version: 1.0\n");
  content.append("Bundle-ManifestVersion: 2\n");
  content.append("Bundle-Name: " + projectName + "\n");
  content.append("Bundle-Vendor: %Bundle-Vendor\n");
  content.append("Bundle-Version: 1.0.0.qualifier\n");
  content.append("Bundle-SymbolicName: " + projectName + ";singleton:=true\n");
  if (null != activatorClassName) {
    content.append("Bundle-Activator: " + activatorClassName + "\n");
  }
  content.append("Bundle-ActivationPolicy: lazy\n");

  addToContent(content, requiredBundles, "Require-Bundle");
  addToContent(content, exportedPackages, "Export-Package");
  addToContent(content, importedPackages, "Import-Package");

  content.append("Bundle-RequiredExecutionEnvironment: JavaSE-1.7\n");

  final IFolder metaInf = project.getFolder("META-INF");
  SubMonitor subMonitor = SubMonitor.convert(progressMonitor, 2);
  try {
    if (metaInf.exists()) {
      metaInf.delete(false, progressMonitor);
    }
    metaInf.create(false, true, subMonitor.newChild(1));
    createFile("MANIFEST.MF", metaInf, content.toString(), subMonitor.newChild(1));
  } finally {
    subMonitor.done();
  }
}
 
Example 14
Source File: ProjectArtifactHandler.java    From developer-studio with Apache License 2.0 5 votes vote down vote up
protected IFile getTargetArchive(IProject project, String version, String ext) throws Exception {
	String finalName = String.format("%s.%s", project.getName() + "_" + version, ext);
	IFolder binaries = project.getFolder("target");
	if (!binaries.exists()) {
		binaries.create(true, true, getProgressMonitor());
		binaries.setHidden(true);
	}
	IFile archive = project.getFile("target" + File.separator + finalName);
	return archive;
}
 
Example 15
Source File: AbstractBuilderParticipantTest.java    From n4js with Eclipse Public License 1.0 5 votes vote down vote up
/***/
protected IFolder createFolder(IFolder superFolder, String path) throws CoreException {
	IFolder folder = superFolder.getFolder(path);
	if (!folder.exists()) {
		createParentFolder(folder);
		folder.create(true, true, null);
	}
	return folder;
}
 
Example 16
Source File: DriverProcessor.java    From neoscada with Eclipse Public License 1.0 4 votes vote down vote up
@Override
public void process ( final String phase, final IFolder baseDir, final IProgressMonitor monitor, final Map<String, String> properties ) throws Exception
{
    if ( phase != null && !"process".equals ( phase ) )
    {
        return;
    }

    final String name = makeName ();

    final IFolder output = baseDir.getFolder ( new Path ( name ) );
    output.create ( true, true, null );

    final IFile exporterFile = output.getFile ( "exporter.xml" ); //$NON-NLS-1$
    final IFile propFile = output.getFile ( "application.properties" ); //$NON-NLS-1$

    final DocumentRoot root = ExporterFactory.eINSTANCE.createDocumentRoot ();

    final ConfigurationType cfg = ExporterFactory.eINSTANCE.createConfigurationType ();
    root.setConfiguration ( cfg );

    final HiveType hive = ExporterFactory.eINSTANCE.createHiveType ();
    cfg.getHive ().add ( hive );
    hive.setRef ( getHiveId () );

    final HiveConfigurationType hiveCfg = ExporterFactory.eINSTANCE.createHiveConfigurationType ();
    hive.setConfiguration ( hiveCfg );

    addConfiguration ( hiveCfg );

    for ( final Endpoint ep : this.driver.getEndpoints () )
    {
        addEndpoint ( hive, ep );
    }

    // write exporter file
    new ModelWriter ( root ).store ( URI.createPlatformResourceURI ( exporterFile.getFullPath ().toString (), true ) );
    exporterFile.refreshLocal ( 1, monitor );

    // write application properties
    if ( propFile.exists () )
    {
        propFile.delete ( true, monitor );
    }
    final Properties p = new Properties ();
    fillProperties ( p );
    if ( !p.isEmpty () )
    {
        try (FileOutputStream fos = new FileOutputStream ( propFile.getRawLocation ().toOSString () ))
        {
            p.store ( fos, "Created by the Eclipse SCADA world generator" );
        }
        propFile.refreshLocal ( 1, monitor );
    }
}
 
Example 17
Source File: UIUtil.java    From birt with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Creates a folder resource given the folder handle.
 * 
 * @param folderHandle
 *            the folder handle to create a folder resource for
 * @param monitor
 *            the progress monitor to show visual progress with
 * @exception CoreException
 *                if the operation fails
 * @exception OperationCanceledException
 *                if the operation is canceled
 */
public static void createFolder( IFolder folderHandle,
		IProgressMonitor monitor ) throws CoreException
{
	try
	{
		// Create the folder resource in the workspace
		// Update: Recursive to create any folders which do not exist
		// already
		if ( !folderHandle.exists( ) )
		{
			IPath path = folderHandle.getFullPath( );
			IWorkspaceRoot root = ResourcesPlugin.getWorkspace( ).getRoot( );
			int numSegments = path.segmentCount( );
			if ( numSegments > 2
					&& !root.getFolder( path.removeLastSegments( 1 ) )
							.exists( ) )
			{
				// If the direct parent of the path doesn't exist, try
				// to create the
				// necessary directories.
				for ( int i = numSegments - 2; i > 0; i-- )
				{
					IFolder folder = root.getFolder( path.removeLastSegments( i ) );
					if ( !folder.exists( ) )
					{
						folder.create( false, true, monitor );
					}
				}
			}
			folderHandle.create( false, true, monitor );
		}
	}
	catch ( CoreException e )
	{
		// If the folder already existed locally, just refresh to get
		// contents
		if ( e.getStatus( ).getCode( ) == IResourceStatus.PATH_OCCUPIED )
			folderHandle.refreshLocal( IResource.DEPTH_INFINITE,
					new SubProgressMonitor( monitor, 500 ) );
		else
			throw e;
	}

	if ( monitor.isCanceled( ) )
		throw new OperationCanceledException( );
}
 
Example 18
Source File: PyEditTitleTestWorkbench.java    From Pydev with Eclipse Public License 1.0 4 votes vote down vote up
public void testEditorTitle() throws Exception {
    NullProgressMonitor monitor = new NullProgressMonitor();
    IProject project = createProject(monitor, "pydev_title_project");

    IFile myFile = project.getFile("my_file.py");
    myFile.create(new ByteArrayInputStream("".getBytes()), true, monitor);

    IFolder folder = project.getFolder("folder");
    folder.create(true, true, null);

    IFile file2 = folder.getFile("my_file.py");
    file2.create(new ByteArrayInputStream("".getBytes()), true, monitor);

    project.refreshLocal(IResource.DEPTH_INFINITE, monitor);

    PyEdit editor2 = null;
    PyEdit editor = null;
    try {
        editor = (PyEdit) PyOpenEditor.doOpenEditor(myFile);
        final PyEdit editorRef = editor;
        String partName = editor.getPartName();
        assertEquals("my_file", partName);
        editor2 = (PyEdit) PyOpenEditor.doOpenEditor(file2);
        final PyEdit editor2final = editor2;
        //We may wait until 10 seconds for the condition to happen (we must not keep the ui-thread
        //otherwise it won't work).
        goToManual(10000, new ICallback<Boolean, Object>() {

            @Override
            public Boolean call(Object arg) {
                return "my_file (pydev_title_project)".equals(editorRef.getPartName())
                        && "my_file (folder)".equals(editor2final.getPartName());
            }
        });
    } finally {
        if (editor2 != null) {
            editor2.close(false);
        }
        if (editor != null) {
            editor.close(false);
        }
    }

}
 
Example 19
Source File: HttpTraceImportOperation.java    From tracecompass with Eclipse Public License 2.0 4 votes vote down vote up
@Override
protected void execute(IProgressMonitor monitor) throws CoreException, InvocationTargetException, InterruptedException {
    int importOptionFlags = ImportTraceWizardPage.OPTION_IMPORT_UNRECOGNIZED_TRACES | ImportTraceWizardPage.OPTION_OVERWRITE_EXISTING_RESOURCES |
            ImportTraceWizardPage.OPTION_PRESERVE_FOLDER_STRUCTURE;

    // Temporary directory to contain any downloaded files
    IFolder tempDestination = fDestinationFolder.getProject().getResource().getFolder(TRACE_HTTP_IMPORT_TEMP_FOLDER);
    String tempDestinationFolderPath = tempDestination.getLocation().toOSString();
    if (tempDestination.exists()) {
        tempDestination.delete(true, monitor);
    }
    tempDestination.create(IResource.HIDDEN, true, monitor);

    // Download trace/traces
    List<File> downloadedTraceList = new ArrayList<>();
    TraceDownloadStatus status = DownloadTraceHttpHelper.downloadTraces(fSourceUrl, tempDestinationFolderPath);
    if (status.isOk()) {
        List<TraceDownloadStatus> children = status.getChildren();
        for (TraceDownloadStatus traceDownloadStatus : children) {
            downloadedTraceList.add(traceDownloadStatus.getDownloadedFile());
        }
    } else if (status.isTimeout()) {
        if (tempDestination.exists()) {
            tempDestination.delete(true, monitor);
        }
        throw new InterruptedException();
    }

    boolean isArchive = false;
    if (!downloadedTraceList.isEmpty()) {
        isArchive = ArchiveUtil.isArchiveFile(downloadedTraceList.get(0));
    }

    FileSystemObjectImportStructureProvider provider = null;
    IFileSystemObject object = null;

    String archiveFolderName = null;
    if (isArchive) {
        // If it's an archive there is only 1 element in this list
        File downloadedTrace = downloadedTraceList.get(0);
        Pair<IFileSystemObject, FileSystemObjectImportStructureProvider> rootObjectAndProvider = ArchiveUtil.getRootObjectAndProvider(downloadedTrace, null);
        provider = rootObjectAndProvider.getSecond();
        object = rootObjectAndProvider.getFirst();
        archiveFolderName = downloadedTrace.getName();
    } else {
        provider = new FileSystemObjectImportStructureProvider(FileSystemStructureProvider.INSTANCE, null);
        object = provider.getIFileSystemObject(new File(tempDestinationFolderPath));
    }

    TraceFileSystemElement root = TraceFileSystemElement.createRootTraceFileElement(object, provider);

    List<TraceFileSystemElement> fileSystemElements = new ArrayList<>();
    root.getAllChildren(fileSystemElements);

    IPath sourceContainerPath = new Path(tempDestinationFolderPath);
    IPath destinationContainerPath = fDestinationFolder.getPath();

    TraceValidateAndImportOperation validateAndImportOperation = new TraceValidateAndImportOperation(null, fileSystemElements, null, sourceContainerPath, destinationContainerPath, isArchive, importOptionFlags, fDestinationFolder, null, null, archiveFolderName, false);
    validateAndImportOperation.run(monitor);
    provider.dispose();

    // Clean the temporary directory
    if (tempDestination.exists()) {
        tempDestination.delete(true, monitor);
    }
}
 
Example 20
Source File: JReFrameworker.java    From JReFrameworker with MIT License 4 votes vote down vote up
private static void configureProjectClasspath(IJavaProject jProject) throws CoreException, JavaModelException, IOException, URISyntaxException {
	// create bin folder
	try {
		IFolder binFolder = jProject.getProject().getFolder(BINARY_DIRECTORY);
		binFolder.create(false, true, null);
		jProject.setOutputLocation(binFolder.getFullPath(), null);
	} catch (Exception e){
		Log.warning("Could not created bin folder.", e);
	}
	
	// create a set of classpath entries
	List<IClasspathEntry> entries = new ArrayList<IClasspathEntry>(); 
	
	// adds classpath entry of: <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.8"/>
	String path = org.eclipse.jdt.launching.JavaRuntime.JRE_CONTAINER + "/" + org.eclipse.jdt.internal.launching.StandardVMType.ID_STANDARD_VM_TYPE + "/" + "JavaSE-1.8";
	entries.add(JavaCore.newContainerEntry(new Path(path)));
	
	//  add the jreframeworker annotations jar 
	addProjectAnnotationsLibrary(jProject);

	// have to create this manually instead of using JavaCore.newLibraryEntry because JavaCore insists the path be absolute
	IClasspathEntry relativeAnnotationsLibraryEntry = new ClasspathEntry(IPackageFragmentRoot.K_BINARY,
			IClasspathEntry.CPE_LIBRARY, new Path(JREF_PROJECT_RESOURCE_DIRECTORY + "/" + JRE_FRAMEWORKER_ANNOTATIONS_JAR), ClasspathEntry.INCLUDE_ALL, // inclusion patterns
			ClasspathEntry.EXCLUDE_NONE, // exclusion patterns
			null, null, null, // specific output folder
			false, // exported
			ClasspathEntry.NO_ACCESS_RULES, false, // no access rules to combine
			ClasspathEntry.NO_EXTRA_ATTRIBUTES);
	entries.add(relativeAnnotationsLibraryEntry);
	
	// create source folder and add it to the classpath
	IFolder sourceFolder = jProject.getProject().getFolder(SOURCE_DIRECTORY);
	sourceFolder.create(false, true, null);
	IPackageFragmentRoot sourceFolderRoot = jProject.getPackageFragmentRoot(sourceFolder);
	entries.add(JavaCore.newSourceEntry(sourceFolderRoot.getPath()));
	
	// set the class path
	jProject.setRawClasspath(entries.toArray(new IClasspathEntry[entries.size()]), null);
	
	if(JReFrameworkerPreferences.isVerboseLoggingEnabled()) Log.info("Successfully created JReFrameworker project: " + jProject.getProject().getName());
}