@Test public void shouldNotShowIgnoredFiles() throws Exception { // given resetRepositoryToCreateInitialTag(); String ignoredName = "to-be-ignored.txt"; IProject proj = ResourcesPlugin.getWorkspace().getRoot().getProject(PROJ1); IFile ignoredFile = proj.getFile(ignoredName); ignoredFile.create( new ByteArrayInputStream("content of ignored file".getBytes(proj.getDefaultCharset())), false, null); IFile gitignore = proj.getFile(".gitignore"); gitignore.create( new ByteArrayInputStream(ignoredName.getBytes(proj.getDefaultCharset())), false, null); proj.refreshLocal(IResource.DEPTH_INFINITE, null); // when launchSynchronization(INITIAL_TAG, HEAD, true); // then SWTBotTree syncViewTree = bot.viewByTitle("Synchronize").bot().tree(); SWTBotTreeItem projectTree = waitForNodeWithText(syncViewTree, PROJ1); projectTree.expand(); assertEquals(1, projectTree.getItems().length); }
private void verifyModifyAndSaveBothSidesOfCompareEditor(String extention) throws InterruptedException, InvocationTargetException, IllegalArgumentException, SecurityException, IllegalAccessException, NoSuchFieldException, CoreException { // create files to compare IFile file1 = project.getFile("CompareFile1." + extention); IFile file2 = project.getFile("CompareFile2." + extention); file1.create(new ByteArrayInputStream(fileContents1.getBytes()), true, null); file2.create(new ByteArrayInputStream(fileContents2.getBytes()), true, null); // prepare comparison SaveablesCompareEditorInput input = new SaveablesCompareEditorInput( null, SaveablesCompareEditorInput.createFileElement(file1), SaveablesCompareEditorInput.createFileElement(file2), PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage()); input.run(null); // open CompareEditor CompareEditor editor = (CompareEditor) PlatformUI.getWorkbench() .getActiveWorkbenchWindow() .getActivePage() .openEditor(input, COMPARE_EDITOR, true); CompareViewerSwitchingPane pane = (CompareViewerSwitchingPane) ReflectionUtils.getField(input, "fContentInputPane", true); Viewer viewer = pane.getViewer(); MergeSourceViewer left = (MergeSourceViewer) ReflectionUtils.getField(viewer, "fLeft", true); MergeSourceViewer right = (MergeSourceViewer) ReflectionUtils.getField(viewer, "fRight", true); // modify both sides of CompareEditor StyledText leftText = left.getSourceViewer().getTextWidget(); StyledText rightText = right.getSourceViewer().getTextWidget(); leftText.append(appendFileContents); rightText.append(appendFileContents); // save both sides editor.doSave(null); assertFalse(editor.isDirty()); PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().closeEditor(editor, false); // validate if both sides where saved assertTrue( compareContent( new ByteArrayInputStream((fileContents1 + appendFileContents).getBytes()), file1.getContents())); assertTrue( compareContent( new ByteArrayInputStream((fileContents2 + appendFileContents).getBytes()), file2.getContents())); }
@Override protected void execute(IProgressMonitor monitor) throws CoreException { try { IncQueryGeneratorModel generatorModel = genmodelProvider.getGeneratorModel(project, resourceSetProvider.get(project)); EList<GeneratorModelReference> genmodelRefs = generatorModel.getGenmodels(); for (GenModel ecoreGenmodel : genmodels) { GeneratorModelReference ref = GeneratorModelFactory.eINSTANCE.createGeneratorModelReference(); ref.setGenmodel(ecoreGenmodel); genmodelRefs.add(ref); } if (genmodelRefs.isEmpty()) { IFile file = project.getFile(ViatraQueryNature.IQGENMODEL); file.create(new StringInputStream(""), false, new SubProgressMonitor(monitor, 1)); } else { genmodelProvider.saveGeneratorModel(project, generatorModel); } } catch (IOException e) { throw new CoreException( new Status( IStatus.ERROR, ViatraQueryGUIPlugin.PLUGIN_ID, "Cannot create generator model: " + e.getMessage(), e)); } }
/** * @param IFile theFile that will be written out * @param Writer the String Writer that will be writen out * @modelguid {32B1885D-A8E1-4267-B66E-4D3ABA83DC69} */ private void saveDocumentAsResource(IFile theFile, OutputStream writer) { if (theFile == null) { return; } InputStream input = null; try { // read the bytes in the outputStreamWriter input = new ByteArrayInputStream(((ByteArrayOutputStream) writer).toByteArray()); if (theFile.exists()) { if (theFile.isReadOnly()) { // Check out the file - ME TODO if (true) { theFile.setContents(input, true, true, null); } } else { theFile.setContents(input, true, true, null); } } else { theFile.create(input, false, null); } } catch (Exception e) { } finally { try { input.close(); } catch (Exception e) { } } }
@Before public void setUp() throws Exception { System.setProperty("disableStartupRunner", "true"); PHPCoreTests.waitForIndexer(); PHPCoreTests.waitForAutoBuild(); project1 = FileUtils.createProject("project1", PHPVersion.PHP5_3); IFolder folder = project1.getFolder("src"); if (!folder.exists()) { folder.create(true, true, new NullProgressMonitor()); } file = folder.getFile("test00294081.php"); InputStream source = new ByteArrayInputStream( "<?php class MyClass{const constant = 'constant value';function showCons1tant() {echo self::constant;}}$class = new MyClass ();$class->showConstant ();echo $class::constant;?>" .getBytes()); if (!file.exists()) { file.create(source, true, new NullProgressMonitor()); } else { file.setContents(source, IFile.FORCE, new NullProgressMonitor()); } PHPCoreTests.waitForIndexer(); PHPCoreTests.waitForAutoBuild(); }
private void generateServicesFile(IFolder srcGenFolder, String filePath, String fileName) throws Exception { StringBuilder sb = new StringBuilder(); InputStream inp = new FileInputStream(filePath); Workbook wb = WorkbookFactory.create(inp); sb.append("Package " + fileName + ".Services {"); sb.append("\n"); sb.append("\n"); sb.append("import " + fileName + ".Privatedata.*"); sb.append("\n"); sb.append("\n"); generateServicesRegion(wb, sb); sb.deleteCharAt(sb.length() - 1); sb.append("}"); IFile file = srcGenFolder.getFile(fileName + ".Services.rslil4privacy"); InputStream source = new ByteArrayInputStream(sb.toString().getBytes()); if (!file.exists()) { file.create(source, IResource.FORCE, null); } else { file.setContents(source, IResource.FORCE, null); } }
private void generateSingleFile(IFolder srcGenFolder, String filePath, String fileName) throws Exception { StringBuilder sb = new StringBuilder(); InputStream inp = new FileInputStream(filePath); Workbook wb = WorkbookFactory.create(inp); sb.append("Package " + fileName + " {"); sb.append("\n"); sb.append("\n"); generateMetadataRegion(wb, sb); generateStatementsRegion(wb, sb); generatePrivateDataRegion(wb, sb); generateRecipientsRegion(wb, sb); generateServicesRegion(wb, sb); generateEnforcementsRegion(wb, sb); sb.deleteCharAt(sb.length() - 1); sb.append("}"); IFile file = srcGenFolder.getFile(fileName + ".rslil4privacy"); InputStream source = new ByteArrayInputStream(sb.toString().getBytes()); if (!file.exists()) { file.create(source, IResource.FORCE, new NullProgressMonitor()); } else { file.setContents(source, IResource.FORCE, new NullProgressMonitor()); } }
/** * Creates the complete package path given by the user (all filled with __init__) and returns the * last __init__ module created. */ public static IFile createPackage( IProgressMonitor monitor, IContainer validatedSourceFolder, String packageName) throws CoreException { IFile lastFile = null; if (validatedSourceFolder == null) { return null; } IContainer parent = validatedSourceFolder; for (String packagePart : StringUtils.dotSplit(packageName)) { IFolder folder = parent.getFolder(new Path(packagePart)); if (!folder.exists()) { folder.create(true, true, monitor); } parent = folder; IFile file = parent.getFile( new Path("__init__" + FileTypesPreferencesPage.getDefaultDottedPythonExtension())); if (!file.exists()) { file.create(new ByteArrayInputStream(new byte[0]), true, monitor); } lastFile = file; } return lastFile; }
protected void addConnectorDefinition( ConnectorImplementation impl, List<IResource> resourcesToExport) throws FileNotFoundException, CoreException { final IRepositoryStore store = getDefinitionStore(); ConnectorDefinition def = ((IDefinitionRepositoryStore) store) .getDefinition(impl.getDefinitionId(), impl.getDefinitionVersion()); EMFFileStore file = (EMFFileStore) store.getChild(URI.decode(def.eResource().getURI().lastSegment())); if (file != null && !file.canBeShared()) { File f = new File(file.getEMFResource().getURI().toFileString()); if (f.exists()) { IFile defFile = store.getResource().getFile(f.getName()); defFile.create(new FileInputStream(f), true, Repository.NULL_PROGRESS_MONITOR); resourcesToExport.add(defFile); cleanAfterExport.add(defFile); } } else if (file != null) { resourcesToExport.add(file.getResource()); } addDefinitionIcons(resourcesToExport, store, def); addDefinitionPropertiesFile(resourcesToExport, store, def); }
@Test public void testAddToPlugin() throws Exception { pluginProjectFactory.setProjectName("test"); pluginProjectFactory.addFolders(Collections.singletonList("src")); pluginProjectFactory.addBuilderIds( JavaCore.BUILDER_ID, "org.eclipse.pde.ManifestBuilder", "org.eclipse.pde.SchemaBuilder", XtextProjectHelper.BUILDER_ID); pluginProjectFactory.addProjectNatures( JavaCore.NATURE_ID, "org.eclipse.pde.PluginNature", XtextProjectHelper.NATURE_ID); IProject project = pluginProjectFactory.createProject(null, null); IJavaProject javaProject = JavaCore.create(project); JavaProjectSetupUtil.makeJava5Compliant(javaProject); IFile file = project.getFile("src/Foo.xtend"); file.create( new StringInputStream( "import org.eclipse.xtend.lib.annotations.Accessors class Foo { @Accessors int bar }"), true, null); syncUtil.waitForBuild(null); markerAssert.assertErrorMarker(file, IssueCodes.XBASE_LIB_NOT_ON_CLASSPATH); adder.addLibsToClasspath(javaProject, null); waitForAutoBuild(); markerAssert.assertNoErrorMarker(file); }
public void addNotationInfo(RootContainer rootContainer, IEditorInput input) { try { IFile file = getNotationInfoFile(((FileEditorInput) input).getFile()); if (file.exists()) { Element notationInfo = documentBuilderFactory .newDocumentBuilder() .parse(file.getContents()) .getDocumentElement(); Element changedInfo = convertCheck(notationInfo); processRootContainer(rootContainer, changedInfo == null ? notationInfo : changedInfo); if (changedInfo != null) { file.setContents( new ByteArrayInputStream(toNotationInfoXml(rootContainer).getBytes()), true, true, null); } } else { file.create( new ByteArrayInputStream(createInitialNotationInfo().toString().getBytes()), true, null); } } catch (Exception e) { Logger.logError("Problem adding notation info", e); throw new RuntimeException(e); } }
private static IFileEditorInput getFileStorage(int index) throws CoreException { String filename = getBatchDateString(); filename += (index > 0 ? "_" + index : "") + ".tcl"; IFolder templateFolder = SicsVisualBatchViewer.getProjectFolder( SicsVisualBatchViewer.EXPERIMENT_PROJECT, FOLDER_TEMPLATE); IFile templateFile = templateFolder.getFile(FILE_TEMPLATE); IFolder folder = SicsVisualBatchViewer.getProjectFolder( SicsVisualBatchViewer.EXPERIMENT_PROJECT, SicsVisualBatchViewer.AUTOSAVE_FOLDER); IFileEditorInput input = new FileEditorInput(folder.getFile(filename)); if (input.exists()) { return getFileStorage(index++); } else { try { byte[] read = null; if (templateFile.exists()) { long size = EFS.getStore(templateFile.getLocationURI()).fetchInfo().getLength(); // long size = templateFolder.getLocation().toFile().length(); read = new byte[(int) size]; InputStream inputStream = templateFile.getContents(); inputStream.read(read); } else { read = new byte[0]; templateFile.create(new ByteArrayInputStream(read), IResource.ALLOW_MISSING_LOCAL, null); } input.getFile().create(new ByteArrayInputStream(read), IResource.ALLOW_MISSING_LOCAL, null); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } return input; }
public static void openFile(IWorkbenchPage page, IFile destinationFile, byte[] initialContent) { try { if (destinationFile != null) { // TODO: prompt to create the file ? I say no, why would you try the shortcut if you didn't // want it created if (!destinationFile.exists()) { IPath fullPath = destinationFile.getLocation(); if (fullPath.toFile().getParentFile().mkdirs()) { // create Eclipse resource so that the create file doesn't blow chunks destinationFile .getProject() .getFile(destinationFile.getParent().getProjectRelativePath()) .refreshLocal(IFile.DEPTH_ZERO, null); } destinationFile.create(new ByteArrayInputStream(initialContent), false, null); } if (destinationFile.exists()) { IDE.openEditor(page, destinationFile); } } } catch (CoreException e) { String clazz = destinationFile.getName(); System.err.println("OpenCakeFile can not open file: " + clazz); e.printStackTrace(); } }
@Before public void setUp() throws Exception { PHPCoreTests.waitForIndexer(); PHPCoreTests.waitForAutoBuild(); project1 = FileUtils.createProject("project1"); IFolder folder = project1.getFolder("src"); if (!folder.exists()) { folder.create(true, true, new NullProgressMonitor()); } file = folder.getFile("test23.php"); InputStream source = new ByteArrayInputStream( "<?php class Item { public $title;} class ItemEx extends Item{public $title;} $a=new ItemEx(); $a->title;?>" .getBytes()); if (!file.exists()) { file.create(source, true, new NullProgressMonitor()); } else { file.setContents(source, IFile.FORCE, new NullProgressMonitor()); } PHPCoreTests.waitForIndexer(); PHPCoreTests.waitForAutoBuild(); }
@Override protected void execute(IFile file, ImportSpec importSpec, IContainer target) throws ExecutionException { Importer importer = new Importer(importSpec); IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot(); importer.setRootContainer(root); importer.importResources(); URI uri = URI.createURI("temp.emfs"); Resource emfResource = Resource.Factory.Registry.INSTANCE.getFactory(uri).createResource(uri); emfResource.getContents().addAll(importSpec.getResources()); ByteArrayOutputStream output = new ByteArrayOutputStream(); try { emfResource.save(output, null); IFile emfsFile = target.getFile(new Path(file.getName() + ".emfs")); ByteArrayInputStream input = new ByteArrayInputStream(output.toByteArray()); if (!emfsFile.exists()) { emfsFile.create(input, IResource.FORCE, null); } else { emfsFile.setContents(input, IResource.FORCE, null); } } catch (IOException e) { System.err.println(e); } catch (CoreException e) { System.err.println(e); } }
public void createDefaultFile(IContainer container, String version, String id, String name) { if (container == null || id == null || name == null) { return; } try { final Path path = new Path("WEB-INF/" + ILiferayConstants.LIFERAY_LOOK_AND_FEEL_XML_FILE); // $NON-NLS-1$ final IFile lookAndFeelFile = container.getFile(path); final String descriptorVersion = getDescriptorVersionFromPortalVersion(version); CoreUtil.prepareFolder((IFolder) lookAndFeelFile.getParent()); String contents = MessageFormat.format( DEFUALT_FILE_TEMPLATE, descriptorVersion, descriptorVersion.replace('.', '_')); contents = contents .replaceAll("__VERSION__", version + "+") .replaceAll("__ID__", id) .replaceAll( //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ "__NAME__", name); // $NON-NLS-1$ lookAndFeelFile.create(new ByteArrayInputStream(contents.getBytes()), true, null); } catch (CoreException e) { ThemeCore.logError("Error creating default descriptor file", e); // $NON-NLS-1$ } }
/** * Populate the project using rpmstubby based on the eclipse-feature or maven-pom choice of user * * @param InputType type of the stubby project * @param File the external xml file uploaded from file system * @throws CoreException * @throws FileNotFoundException */ public void create(InputType inputType, File stubby) throws FileNotFoundException, CoreException { IFile stubbyFile = project.getFile(stubby.getName()); stubbyFile.create(new FileInputStream(stubby), false, monitor); Generator specfilegGenerator = new Generator(inputType); specfilegGenerator.generate(stubbyFile); }
protected IFile createFile(IProject project, String fileName, String contents) throws CoreException { IFile file = project.getFile(fileName); ByteArrayInputStream source = new ByteArrayInputStream(contents.getBytes()); file.create(source, true, new NullProgressMonitor()); return file; }
protected void addConnectorImplementation( ConnectorImplementation impl, List<IResource> resourcesToExport, boolean includeSources) throws FileNotFoundException, CoreException { final IRepositoryStore store = getImplementationStore(); String fileName = NamingUtils.getEResourceFileName(impl, true); final EMFFileStore fileStore = (EMFFileStore) store.getChild(fileName); if (!fileStore.canBeShared()) { File f = new File(fileStore.getEMFResource().getURI().toFileString()); if (f.exists()) { IFile implFile = store.getResource().getFile(f.getName()); implFile.create(new FileInputStream(f), true, Repository.NULL_PROGRESS_MONITOR); resourcesToExport.add(implFile); cleanAfterExport.add(implFile); } } else { implBackup = EcoreUtil.copy(impl); String jarName = NamingUtils.toConnectorImplementationFilename( impl.getImplementationId(), impl.getImplementationVersion(), false) + ".jar"; if (!impl.getJarDependencies().getJarDependency().contains(jarName)) { impl.getJarDependencies().getJarDependency().add(jarName); } impl.setHasSources(includeSources); IRepositoryFileStore file = store.getChild(fileName); file.save(EcoreUtil.copy(impl)); resourcesToExport.add(file.getResource()); } }
private void replaceContent(IFile f, String content) { try { f.delete(true, new NullProgressMonitor()); } catch (CoreException ce) { LOGGER.log(Level.WARNING, ce.getMessage(), ce); } InputStream is = null; try { is = EAPFromWSDLTest.class.getResourceAsStream(content); f.create(is, true, new NullProgressMonitor()); } catch (CoreException ce) { LOGGER.log(Level.WARNING, ce.getMessage(), ce); } finally { if (is != null) { try { is.close(); } catch (IOException ioe) { // ignore } } } try { ResourcesPlugin.getWorkspace() .getRoot() .refreshLocal(IWorkspaceRoot.DEPTH_INFINITE, new NullProgressMonitor()); } catch (CoreException e) { LOGGER.log(Level.WARNING, e.getMessage(), e); } util.waitForNonIgnoredJobs(); }
/** * This operation writes a launcher to an Item XML file * * @param launcher the launcher to write * @param file the file where the launcher should be written */ private void writeLauncherItemToFile(JobLauncher launcher, IFile file) { // Create an input stream for the file by first writing it to an // output stream ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); // Use the JAXB handler to dump this to a file ICEJAXBHandler xmlHandler = new ICEJAXBHandler(); ICEJAXBClassProvider classProvider = new ICEJAXBClassProvider(); ArrayList<Class> classList = (ArrayList<Class>) classProvider.getClasses(); try { // Write the file to the output stream xmlHandler.write(launcher, classList, outputStream); // Write the file to the input stream. ByteArrayInputStream fileInputStream = new ByteArrayInputStream(outputStream.toByteArray()); // Write the file contents if (file.exists()) { file.setContents(fileInputStream, IResource.FORCE, null); } else { // Write the file file.create(fileInputStream, false, null); } } catch (NullPointerException | JAXBException | IOException | CoreException e1) { // Complain logger.error(getClass().getName() + " Exception!", e1); } }
public void overwriteTemplate(Template template) throws CoreException { try { // get the directory String projectName = folderSelected.getProject().getName(); IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot(); IProject project = root.getProject(projectName); IPath pathFolder = folderSelected.getProjectRelativePath(); String templateFileName = template.getFileName(); DataHandler dh = template.getContent(); InputStream is = dh.getInputStream(); IPath pathNewFile = pathFolder.append(templateFileName); IFile newFile = project.getFile(pathNewFile); // create new File if (newFile.exists()) { newFile.delete(true, null); } newFile.create(is, true, null); // set the dirty property to true newFile.setPersistentProperty(SpagoBIStudioConstants.DIRTY_MODEL, "true"); } catch (IOException e1) { MessageDialog.openError( PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(), "Error", "Error in writing the file"); logger.error("Error in writing the file", e1); return; } }
/** @see ActionDelegate#run(IAction) */ public void run(IAction action) { if (this.selection instanceof StructuredSelection) { StructuredSelection selection = (StructuredSelection) this.selection; if (!selection.isEmpty()) { IWorkbench workbench = PlatformUI.getWorkbench(); Shell shell = workbench.getActiveWorkbenchWindow().getShell(); IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot(); InputDialog inputDialog = new InputDialog( Activator.getDefault().getWorkbench().getWorkbenchWindows()[0].getShell(), "Ingreso de version", "Ingrese la version a generar", "", null); int manual = inputDialog.open(); if (manual == 0) { String value = inputDialog.getValue(); IFolder folder = (IFolder) selection.getFirstElement(); try { IFolder folder1 = folder.getFolder(new Path(value)); folder1.create(true, false, new NullProgressMonitor()); IFile file = folder1.getFile(new Path("000_db_version_insert.sql")); file.create( new ByteArrayInputStream(VERSION_SCRIPT.replace("DBVERSION", value).getBytes()), true, new NullProgressMonitor()); } catch (CoreException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } }
public static void createEmptyFile(IFile newFile) throws CoreException { if (newFile.getParent() instanceof IFolder) { prepareFolder((IFolder) newFile.getParent()); } newFile.create(new ByteArrayInputStream(new byte[0]), true, null); }
private void importFile(File file, IProject project, List<IBuildpathEntry> entries) { try { level++; // handle windows path separators String path = file.getAbsolutePath().replace("\\", "/").replace(symfonyPath, ""); // import the directory if (file.isDirectory() && !file.isHidden()) { IFolder folder = project.getFolder(path); if (!folder.exists()) { folder.create(true, true, null); } // add root folders to buildpath if (level == 1 && !folder.getFullPath().toString().endsWith("bin")) { IPath[] exclusion = {}; if (folder.getName().equals(SymfonyCoreConstants.APP_PATH)) { exclusion = new IPath[] { new Path(SymfonyCoreConstants.CACHE_PATH), new Path(SymfonyCoreConstants.LOG_PATH) }; } else if (folder.getName().equals(SymfonyCoreConstants.VENDOR_PATH)) { exclusion = new IPath[] {new Path(SymfonyCoreConstants.SKELETON_PATH)}; } IBuildpathEntry entry = DLTKCore.newSourceEntry(folder.getFullPath(), exclusion); entries.add(entry); } // now import recursively for (File f : file.listFiles()) { importFile(f, project, entries); } // create the project file } else if (file.isFile() && ".gitkeep".equals(file.getName()) == false) { FileInputStream fis = new FileInputStream(file); IFile iFile = project.getFile(path); iFile.create(fis, true, null); } level--; } catch (CoreException e) { e.printStackTrace(); Logger.logException(e); } catch (FileNotFoundException e) { e.printStackTrace(); Logger.logException(e); } }
private void copyFile(final String from, final IContainer container, final String fileName) throws CoreException { IPath path = new Path(fileName); IFile file = container.getFile(path); if (!file.exists()) { file.create(getFileStream(from), true, null); } }
public static IFile createFile(final String name, final String contents, final IFolder folder) throws CoreException { final IFile file = folder.getFile(name); final File f = new File(file.getLocation().toOSString()); f.delete(); file.create(new ByteArrayInputStream(contents.getBytes(Charset.defaultCharset())), true, null); return file; }
private void createNotationInfoFile(IFile notationInfoFile) { try { notationInfoFile.create( new ByteArrayInputStream(createInitialNotationInfo().toString().getBytes()), true, null); } catch (CoreException e) { Logger.logError(e); } }
/** * (non-Javadoc) * * @see org.eclipse.ice.core.iCore.ICore#importFile(java.net.URI, * org.eclipse.core.resources.IProject) */ @Override public void importFile(URI file, IProject project) { // Only do this if the file is good if (file != null) { // Get the file handle IPath path = (new Path(file.toString())); IFile fileInProject = project.getFile(path.lastSegment()); // Get the paths and convert them to strings IPath fullPathInProject = fileInProject.getLocation(); String path1 = path.toString(), path2 = fullPathInProject.toString(); // Remove devices ids and other such things from the path strings path1 = path1.substring(path1.lastIndexOf(":") + 1); path2 = path2.substring(path2.lastIndexOf(":") + 1); // Only manipulate the file if it is not already in the workspace. // It is completely reasonable to stick the file in the workspace // and then "import" it, so a simple check here relieves some // heartburn I would no doubt otherwise endure. if (!path1.equals(path2)) { // If the project space contains a file by the same name, but // with a different absolute path, delete that file. if (fileInProject.exists()) { try { fileInProject.delete(true, null); } catch (CoreException e) { // Complain and don't do anything else. logger.info("Core Message: " + "Unable to import file."); logger.error(getClass().getName() + " Exception!", e); return; } } try { // Open a stream of the file FileInputStream fileStream = new FileInputStream(new File(file)); // Import the file fileInProject.create(fileStream, true, null); } catch (FileNotFoundException e) { // Complain and don't do anything else. logger.info("Core Message: " + "Unable to import file."); logger.error(getClass().getName() + " Exception!", e); return; } catch (CoreException e) { // Complain and don't do anything else. logger.info("Core Message: " + "Unable to import file."); logger.error(getClass().getName() + " Exception!", e); return; } } // Refresh all of the Items itemManager.reloadItemData(); // Drop some debug info. if (System.getProperty("DebugICE") != null) { logger.info("Core Message: " + "Imported file " + file.toString()); } } else { logger.info("File could not be imported into project because the File URI was not valid."); } }
public static IErlModule createErlModule( final IErlProject erlProject, final String moduleName, final String moduleContents) throws CoreException { final IProject project = erlProject.getProject(); final IFolder folder = project.getFolder("src"); final IFile file = folder.getFile(moduleName); file.create(new ByteArrayInputStream(moduleContents.getBytes()), true, null); return ErlangCore.getModel().findModule(file); }