private Set<String> outputFoldersForProject(final IJavaProject project) { final Set<String> outputFolders = new HashSet<String>(); final IPath projectLocation = projectLocationPath(project); try { final IPath defaultOutputLocation = project.getOutputLocation(); if (defaultOutputLocation != null) { final IPath fullPath = appendPathTo(projectLocation, defaultOutputLocation); if (fullPath.toFile().exists()) { outputFolders.add(fullPath.toOSString()); } } for (final IClasspathEntry entry : project.getRawClasspath()) { if (entry.getEntryKind() == IClasspathEntry.CPE_SOURCE) { final IPath outputLocation = entry.getOutputLocation(); if (outputLocation != null) { final IPath fullPath = appendPathTo(projectLocation, outputLocation); if (fullPath.toFile().exists()) { outputFolders.add(fullPath.toOSString()); } } } } } catch (final JavaModelException ex) { FeatureEditorPlugin.instance() .warn("Could not get output folder location for project " + project.getElementName()); } return outputFolders; }
public static String getLiferayWorkspaceProjectModulesDir(final IProject project) { String retval = null; if (project != null) { final IPath projectLocation = project.getLocation(); if (projectLocation != null) { final IPath gradlePropertiesLocation = projectLocation.append("gradle.properties"); if (gradlePropertiesLocation.toFile().exists()) { try { String modulesDir = CoreUtil.readPropertyFileValue( gradlePropertiesLocation.toFile(), "liferay.workspace.modules.dir"); if (modulesDir == null) { modulesDir = "modules"; } retval = modulesDir; } catch (IOException e) { ProjectCore.logError("Can't read gradle properties from workspaceProject. ", e); } } } } return retval; }
@Override public IStatus transferSettings(IPath newWorkspaceRoot) { IPath currentWorkspace = Platform.getLocation(); File srcDir = new File( currentWorkspace.toFile(), ".metadata/.plugins/org.eclipse.core.runtime/.settings"); File destDir = new File( newWorkspaceRoot.toFile(), ".metadata/.plugins/org.eclipse.core.runtime/.settings"); File[] srcSettings = srcDir.listFiles(); if (!destDir.exists()) { if (!destDir.mkdirs()) return new Status(IStatus.ERROR, LiferayUIPlugin.PLUGIN_ID, "can't create dirs"); } for (File src : srcSettings) { File destSetting = new File(destDir.getAbsolutePath(), src.getName()); if (destSetting.exists()) { if (!destSetting.delete()) { return new Status(IStatus.ERROR, LiferayUIPlugin.PLUGIN_ID, "can't delete settings file"); } } FileUtil.copyFile(src, destSetting); } return Status.OK_STATUS; }
public static File getDependencyPath(URL resource, boolean isRelativePath) { if (resource!=null) { IPath path = Activator.getDefault().getStateLocation(); IPath libFolder = path.append("lib"); String[] paths = resource.getFile().split("/"); IPath library = libFolder.append(paths[paths.length - 1]); File libraryFile = library.toFile(); if (!libraryFile.exists()) { try { writeToFile(libraryFile, resource.openStream()); } catch (IOException e) { log.error(e); return null; } } if (isRelativePath) { IPath relativePath = EclipseUtils .getWorkspaceRelativePath(library); relativePath = new Path(Constants.ECLIPSE_WORKSPACE_PATH) .append(relativePath); return relativePath.toFile(); } else { return library.toFile(); } } else{ log.error("the requested resource does not exist in library path"); return null; } }
public static File getCurrentWorkspace() { IWorkspace workspace = ResourcesPlugin.getWorkspace(); IWorkspaceRoot root = workspace.getRoot(); IPath location = root.getLocation(); location.toFile(); return location.toFile(); }
public void testMoveProjectWithVirtualFolder() { IPath fileLocation = getRandomLocation(); IPath folderLocation = getRandomLocation(); IFile file = existingVirtualFolderInExistingProject.getFile(getUniqueString()); IFolder folder = existingVirtualFolderInExistingProject.getFolder(getUniqueString()); IFile childFile = folder.getFile(getUniqueString()); IResource[] oldResources = new IResource[] {existingProject, file, folder, childFile}; try { assertDoesNotExistInWorkspace("1.0", new IResource[] {folder, file, childFile}); try { createFileInFileSystem(fileLocation); folderLocation.toFile().mkdir(); folder.createLink(folderLocation, IResource.NONE, getMonitor()); file.createLink(fileLocation, IResource.NONE, getMonitor()); childFile.create(getRandomContents(), true, getMonitor()); } catch (CoreException e) { fail("2.0", e); } // move the project IProject destinationProject = getWorkspace().getRoot().getProject("MoveTargetProject"); assertDoesNotExistInWorkspace("3.0", destinationProject); try { existingProject.move(destinationProject.getFullPath(), IResource.SHALLOW, getMonitor()); } catch (CoreException e) { fail("4.0", e); } IFile newFile = destinationProject.getFile(file.getProjectRelativePath()); IFolder newFolder = destinationProject.getFolder(folder.getProjectRelativePath()); IFile newChildFile = newFolder.getFile(childFile.getName()); IResource[] newResources = new IResource[] {destinationProject, newFile, newFolder, newChildFile}; assertExistsInWorkspace("5.0", newResources); assertDoesNotExistInWorkspace("6.1", oldResources); assertTrue("7.0", existingProject.isSynchronized(IResource.DEPTH_INFINITE)); assertTrue("8.0", destinationProject.isSynchronized(IResource.DEPTH_INFINITE)); assertTrue("9.0", newFile.getParent().isVirtual()); assertTrue("10.0", newFile.isLinked()); assertTrue("11.0", newFolder.isLinked()); assertTrue("12.0", newFolder.getParent().isVirtual()); } finally { Workspace.clear(fileLocation.toFile()); Workspace.clear(folderLocation.toFile()); } }
private void publishArchiveModule( String jarURI, Properties p, List status, IProgressMonitor monitor) { IPath path = server.getModuleDeployDirectory(module[0]); boolean moving = false; // Get URI used for previous publish, if known String oldURI = (String) p.get(module[1].getId()); if (oldURI != null) { // If old URI found, detect if jar is moving or changing its name if (jarURI != null) { moving = !oldURI.equals(jarURI); } } // If we don't have a jar URI, make a guess so we have one if we need it if (jarURI == null) { jarURI = "WEB-INF/lib/" + module[1].getName(); // $NON-NLS-1$ } IPath jarPath = path.append(jarURI); // Make our best determination of the path to the old jar IPath oldJarPath = jarPath; if (oldURI != null) { oldJarPath = path.append(oldURI); } // Establish the destination directory path = jarPath.removeLastSegments(1); // Remove if requested or if previously published and are now serving without publishing if (moving || kind == IServer.PUBLISH_CLEAN || deltaKind == ServerBehaviourDelegate.REMOVED || server.getTomcatServer().isServeModulesWithoutPublish()) { File file = oldJarPath.toFile(); if (file.exists()) { file.delete(); } p.remove(module[1].getId()); if (deltaKind == ServerBehaviourDelegate.REMOVED || server.getTomcatServer().isServeModulesWithoutPublish()) return; } if (!moving && kind != IServer.PUBLISH_CLEAN && kind != IServer.PUBLISH_FULL) { // avoid changes if no changes to module since last publish IModuleResourceDelta[] delta = server.getPublishedResourceDelta(module); if (delta == null || delta.length == 0) return; } // make directory if it doesn't exist if (!path.toFile().exists()) path.toFile().mkdirs(); IModuleResource[] mr = server.getResources(module); IStatus[] stat = helper.publishToPath(mr, jarPath, monitor); addArrayToList(status, stat); p.put(module[1].getId(), jarURI); }
public static String[] execute(String args) throws BladeCLIException { final IPath bladeCLIPath = getBladeCLIPath(); if (bladeCLIPath == null || !bladeCLIPath.toFile().exists()) { throw new BladeCLIException("Could not get blade cli jar."); } final Project project = new Project(); final Java javaTask = new Java(); javaTask.setProject(project); javaTask.setFork(true); javaTask.setFailonerror(true); javaTask.setJar(bladeCLIPath.toFile()); javaTask.setArgs(args); final DefaultLogger logger = new DefaultLogger(); project.addBuildListener(logger); final StringBufferOutputStream out = new StringBufferOutputStream(); logger.setOutputPrintStream(new PrintStream(out)); logger.setMessageOutputLevel(Project.MSG_INFO); int returnCode = javaTask.executeJava(); final List<String> lines = new ArrayList<>(); final Scanner scanner = new Scanner(out.toString()); while (scanner.hasNextLine()) { lines.add(scanner.nextLine().replaceAll(".*\\[null\\] ", "")); } scanner.close(); boolean hasErrors = false; final StringBuilder errors = new StringBuilder(); for (String line : lines) { if (line.startsWith("Error")) { hasErrors = true; } else if (hasErrors) { errors.append(line); } } if (returnCode != 0 || hasErrors) { throw new BladeCLIException(errors.toString()); } return lines.toArray(new String[0]); }
public String getFrameworkJarPath() { IPath installPath = getServer().getRuntime().getLocation(); IPath plugins = installPath.append("plugins"); if (plugins.toFile().exists()) { File[] files = plugins.toFile().listFiles(); for (File file : files) { if (file.getName().indexOf("org.eclipse.osgi_") > -1) { return file.getAbsolutePath(); } } } return null; }
private void setClassLoader() { IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot(); IJavaProject javaProject = getJavaProject(); try { if (javaProject != null) { List<URL> entries = new ArrayList<URL>(); IPath path = javaProject.getOutputLocation(); IResource iResource = root.findMember(path); path = iResource.getLocation(); path = path.addTrailingSeparator(); entries.add(path.toFile().toURL()); IClasspathEntry[] cpEntries = javaProject.getRawClasspath(); for (IClasspathEntry cpEntry : cpEntries) { switch (cpEntry.getEntryKind()) { case IClasspathEntry.CPE_SOURCE: path = cpEntry.getOutputLocation(); if (path != null) { iResource = root.findMember(path); path = iResource.getLocation(); path = path.addTrailingSeparator(); entries.add(path.toFile().toURL()); } break; case IClasspathEntry.CPE_LIBRARY: iResource = root.findMember(cpEntry.getPath()); if (iResource == null) { // resource is not in workspace, must be an external JAR path = cpEntry.getPath(); } else { path = iResource.getLocation(); } entries.add(path.toFile().toURL()); break; } } ClassLoader oldCl = Thread.currentThread().getContextClassLoader(); URL[] entryArray = new URL[entries.size()]; entries.toArray(entryArray); ClassLoader newCl = new URLClassLoader(entryArray, oldCl); Thread.currentThread().setContextClassLoader(newCl); oldClassLoader = oldCl; } } catch (Exception e) { // ignore - something too complex is wrong ; } }
/** * Prints a list of module name, version, path to the given file, to be used by the runtime * launcher, because passing it as an argument/environment would easily exceed the OS size limits. */ private void writeModuleInfoFile(File tmpFile, ILaunchConfiguration configuration) throws IOException, CoreException { FileWriter writer = new FileWriter(tmpFile); IJavaProject javaProject = getJavaProject(configuration); IProject project = javaProject.getProject(); Context context = getProjectTypeChecker(project).getContext(); RepositoryManager provider = context.getRepositoryManager(); Set<Module> modulesToAdd = context.getModules().getListOfModules(); boolean seenDefault = false; for (Module module : modulesToAdd) { String name = module.getNameAsString(); if (JDKUtils.isJDKModule(name) || JDKUtils.isOracleJDKModule(name)) { continue; } if (module.isDefault()) seenDefault = true; IPath modulePath = getModuleArchive(provider, module); if (modulePath != null && modulePath.toFile().exists()) { String path = modulePath.toOSString(); System.err.println( "Adding module: " + module.getNameAsString() + "/" + module.getVersion() + ": " + path); // print module name + NL (+ version + NL)? + path + NL writer.append(module.getNameAsString()); writer.append(System.lineSeparator()); if (!module.isDefault()) { writer.append(module.getVersion()); writer.append(System.lineSeparator()); } writer.append(path); writer.append(System.lineSeparator()); } } // for some reason the default module can be missing from the list of modules if (!seenDefault) { IPath modulesFolder = getCeylonModulesOutputFolder(project).getLocation(); IPath defaultCar = modulesFolder.append("default").append("default.car"); if (defaultCar.toFile().exists()) { String path = defaultCar.toOSString(); Module module = context.getModules().getDefaultModule(); System.err.println("Adding default module: " + module.getNameAsString() + ": " + path); // print module name + NL + path + NL writer.append(module.getNameAsString()); writer.append(System.lineSeparator()); writer.append(path); writer.append(System.lineSeparator()); } } writer.flush(); writer.close(); }
/** @since 2.4 */ @Override public Pair<URI, URI> getURIMapping(IPackageFragmentRoot root) throws JavaModelException { PackageFragmentRootData data = getData(root); if (data.uriPrefix == null) return null; IPath path = root.isExternal() ? root.getPath() : root.getUnderlyingResource().getLocation(); URI physical = null; if (root.isArchive()) { String archiveScheme = "zip".equalsIgnoreCase(root.getPath().getFileExtension()) ? "zip" : "jar"; physical = URI.createURI(archiveScheme + ":file:" + path.toFile().getPath() + "!/"); } else { physical = URI.createFileURI(path.toFile().getPath() + "/"); } return Tuples.create(data.uriPrefix, physical); }
/** * Tries to infer a file location from given object, using various strategies * * @param o an object * @return a {@link File} associated to this object, or null. */ public static File toFile(Object o) { if (o instanceof File) { return (File) o; } else if (o instanceof IResource) { IPath location = ((IResource) o).getLocation(); return location == null ? null : location.toFile(); } else if (o instanceof IAdaptable) { IResource resource = ((IAdaptable) o).getAdapter(IResource.class); if (resource != null) { IPath location = resource.getLocation(); return location == null ? null : location.toFile(); } } return null; }
/** * Creates new symbolic file system link from file or folder to another filesystem file. The * target path has to be present on disk. * * @param linkPath - filesystem path of the link being created. * @param realPath - file or folder on the file system, the target of the link. * @throws UnsupportedOperationException on Windows where links are not supported. * @throws IOException if execution of the command fails. */ public static void createSymbolicLink(IPath linkPath, IPath realPath) throws IOException { if (!isSymbolicLinkSupported()) { throw new UnsupportedOperationException("Windows links .lnk are not supported."); } String command = "ln -s " + realPath.toOSString() + ' ' + linkPath.toOSString(); Process process = Runtime.getRuntime().exec(command); // Wait for up to 2.5s... for (int i = 0; i < 5; i++) { try { Assert.assertTrue("ln process exited with non-zero status", process.waitFor() == 0); // If exitValue succeeded, then the process has exitted successfully. break; } catch (InterruptedException e) { // Clear interrupted state, see Java bug http://bugs.sun.com/view_bug.do?bug_id=6420270 Thread.interrupted(); } // wait for a 500ms before checking again try { Thread.sleep(500); } catch (InterruptedException e) { /*don't care*/ } } Assert.assertTrue( "Symbolic link not created, command=[" + command + "]", linkPath.toFile().exists()); }
/** * Install an extension using linked method * * @param extensionURL * @param extensionID * @param dir * @return boolean */ public static boolean installLinkedExtension(URL extensionURL, String extensionID, File dir) { File file = new File(dir, extensionID); if (file.exists() && file.isDirectory()) { return true; } IPath base = CorePlugin.getDefault().getStateLocation().addTrailingSeparator(); boolean result = installExtension(extensionURL, extensionID, base.toFile()); if (result) { String linkedPath = base.append(extensionID).toOSString(); FileOutputStream out = null; try { out = new FileOutputStream(file); out.write(linkedPath.getBytes()); } catch (IOException e) { IdeLog.logError(CorePlugin.getDefault(), e.getMessage(), e); } finally { if (out != null) { try { out.close(); } catch (IOException e) { } } } } return result; }
/** Tests creating a linked folder under a virtual folder */ public void testCreateLinkedFolderUnderVirtualFolder() { // get a non-existing location IPath location = getRandomLocation(); IFolder linkedFolder = existingVirtualFolderInExistingProject.getFolder(getUniqueString()); try { linkedFolder.createLink(location, IResource.ALLOW_MISSING_LOCAL, getMonitor()); } catch (CoreException e) { fail("1.0", e); } assertTrue("2.0", linkedFolder.exists()); assertEquals("3.0", location, linkedFolder.getLocation()); assertTrue("4.0", !location.toFile().exists()); // getting children should succeed (and be empty) try { assertEquals("5.0", 0, linkedFolder.members().length); } catch (CoreException e) { fail("6.0", e); } // delete should succeed try { linkedFolder.delete(IResource.NONE, getMonitor()); } catch (CoreException e) { fail("7.0", e); } }
/** * Returns the location of the Javadoc. * * @param element whose Javadoc location has to be found * @param isBinary <code>true</code> if the Java element is from a binary container * @return the location URL of the Javadoc or <code>null</code> if the location cannot be found * @throws JavaModelException thrown when the Java element cannot be accessed * @since 3.9 */ public static String getBaseURL(IJavaElement element, boolean isBinary) throws JavaModelException { if (isBinary) { // Source attachment usually does not include Javadoc resources // => Always use the Javadoc location as base: URL baseURL = JavaUI.getJavadocLocation(element, false); if (baseURL != null) { if (baseURL.getProtocol().equals(JAR_PROTOCOL)) { // It's a JarURLConnection, which is not known to the browser widget. // Let's start the help web server: URL baseURL2 = PlatformUI.getWorkbench().getHelpSystem().resolve(baseURL.toExternalForm(), true); if (baseURL2 != null) { // can be null if org.eclipse.help.ui is not available baseURL = baseURL2; } } return baseURL.toExternalForm(); } } else { IResource resource = element.getResource(); if (resource != null) { /* * Too bad: Browser widget knows nothing about EFS and custom URL handlers, * so IResource#getLocationURI() does not work in all cases. * We only support the local file system for now. * A solution could be https://bugs.eclipse.org/bugs/show_bug.cgi?id=149022 . */ IPath location = resource.getLocation(); if (location != null) return location.toFile().toURI().toString(); } } return null; }
private void saveConfigInfoIntoCache(String configType, String configInfo, IPath portalDir) { IPath versionsInfoPath = null; if (configType.equals(CONFIG_TYPE_VERSION)) { versionsInfoPath = LiferayServerCore.getDefault().getStateLocation().append("version.properties"); } else if (configType.equals(CONFIG_TYPE_SERVER)) { versionsInfoPath = LiferayServerCore.getDefault().getStateLocation().append("serverInfos.properties"); } if (versionsInfoPath != null) { File versionInfoFile = versionsInfoPath.toFile(); if (configInfo != null) { String portalDirKey = CoreUtil.createStringDigest(portalDir.toPortableString()); Properties properties = new Properties(); try (FileInputStream fileInput = new FileInputStream(versionInfoFile)) { properties.load(fileInput); } catch (Exception e) { } try (FileOutputStream fileOutput = new FileOutputStream(versionInfoFile)) { properties.put(portalDirKey, configInfo); properties.store(fileOutput, StringPool.EMPTY); } catch (Exception e) { LiferayServerCore.logError(e); } } } }
/** * Search in plugin folder in .metadata and zip all files * * @throws ArchiveException */ private static File createZip() throws ArchiveException { // Get all log xml files IPath pluginSaveFolder = FeedbackUtils.getFeedbackSaveFolder(); java.io.File source = pluginSaveFolder.toFile(); List<java.io.File> fileList = FileHelper.listAll(source); List<File> logFiles = new ArrayList<File>(); for (java.io.File f : fileList) { if (f.getName().endsWith(FeedbackUtils.END_FILE_NAME)) { logFiles.add(new File(f)); } } // Zip creation File zipFile = new File(source, FeedbackActivator.ZIP_FILE_NAME); zipFile.mkdir(); // Add them to the zip for (File f : logFiles) { File zipEntry = new File(zipFile, f.getName(), ArchiveDetector.NULL); f.copyTo(zipEntry); if (zipFile.archiveCopyAllFrom(f)) { System.err.println("Copied " + f.getName()); } else { System.err.println("Error in copy " + f.getName()); } } File.update(); return zipFile; }
/** * Returns a status for this library describing any error states * * @return */ IStatus validate() { if (!getSystemLibraryPath().toFile().exists()) { return new Status( IStatus.ERROR, IJavaDebugUIConstants.PLUGIN_ID, IJavaDebugUIConstants.INTERNAL_ERROR, "System library does not exist: " + getSystemLibraryPath().toOSString(), null); //$NON-NLS-1$ } IPath path = getSystemLibrarySourcePath(); if (!path.isEmpty()) { if (!path.toFile().exists()) { // check for workspace resource IResource resource = ResourcesPlugin.getWorkspace().getRoot().findMember(path); if (resource == null || !resource.exists()) { return new Status( IStatus.ERROR, IJavaDebugUIConstants.PLUGIN_ID, IJavaDebugUIConstants.INTERNAL_ERROR, "Source attachment does not exist: " + path.toOSString(), null); //$NON-NLS-1$ } } } return Status.OK_STATUS; }
@SuppressWarnings({"rawtypes", "unchecked", "resource"}) @Override public Object createExecutableExtension(String propertyName) throws CoreException { try { String className = attributes.get(propertyName); IProject project = getProject(); IJavaProject javaProject = JavaCore.create(project); String[] classPathEntries = JavaRuntime.computeDefaultRuntimeClassPath(javaProject); List<URL> urlList = new ArrayList<URL>(); for (int i = 0; i < classPathEntries.length; i++) { String entry = classPathEntries[i]; IPath path = new Path(entry); URL url = path.toFile().toURI().toURL(); urlList.add(url); } ClassLoader parentClassLoader = javaProject.getClass().getClassLoader(); URL[] urls = (URL[]) urlList.toArray(new URL[urlList.size()]); URLClassLoader classLoader = new URLClassLoader(urls, parentClassLoader); ClassLoader cl = classLoader.getParent(); Class clazz = classLoader.loadClass(className); return clazz.getConstructor().newInstance(); } catch (Exception ex) { ex.printStackTrace(); throw new CoreException(new Status(IStatus.ERROR, Activator.PLUGIN_ID, ex.getMessage())); } }
@Override @SuppressWarnings("rawtypes") protected void publishModules( int kind, List modules, List deltaKind2, MultiStatus multi, IProgressMonitor monitor) { @SuppressWarnings("unchecked") final List<IModule[]> myModules = modules; IPath confDir = getBaseDirectory(); FrameworkInstanceConfiguration jonasConfiguration; try { jonasConfiguration = getJonasRuntimeInstance().getJonasConfiguration(); IPath deployDir = confDir.append("/jonasbase/tmp"); IPath installDir = confDir.append("/jonasbase/deploy"); File deployPath = deployDir.toFile(); if (!deployPath.exists()) { deployPath.mkdir(); } publishHelper.exportBundles(myModules, jonasConfiguration, installDir, deployDir); getJonasVersionHandler() .prepareFrameworkConfigurationFile( deployDir, publishHelper.getServerModules(myModules, "reference:file:", " "), publishHelper.getTargetBundles(jonasConfiguration, "reference:file:", " ")); } catch (CoreException e) { Trace.trace(Trace.SEVERE, "Publishing failed", e); } }
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(); } }
/** Initialize this index with information from the user libraries. */ private boolean indexUserLibraries() { boolean librariesIndexed = true; try { AnalysisServer analysisServer = PackageLibraryManagerProvider.getDefaultAnalysisServer(); SavedContext savedContext = analysisServer.getSavedContext(); DartModel model = DartCore.create(ResourcesPlugin.getWorkspace().getRoot()); for (DartProject project : model.getDartProjects()) { for (DartLibrary library : project.getDartLibraries()) { CompilationUnit compilationUnit = library.getDefiningCompilationUnit(); if (compilationUnit == null) { continue; } IResource libraryResource = compilationUnit.getResource(); if (libraryResource == null) { continue; } IPath libraryLocation = libraryResource.getLocation(); if (libraryLocation == null) { continue; } File libraryFile = libraryLocation.toFile(); savedContext.resolve(libraryFile, null); } } } catch (Exception exception) { librariesIndexed = false; DartCore.logError("Could not index user libraries", exception); } return librariesIndexed; }
private void searchForRuntimes( List<RuntimeDefinition> runtimeCollector, IPath path, IProgressMonitor monitor) { File[] files = null; if (path != null) { File root = path.toFile(); if (root.isDirectory()) files = new File[] {root}; else return; } else files = File.listRoots(); if (files != null) { int size = files.length; monitor.beginTask("Searching " + path.toOSString(), size * 100); int work = 100 / size; for (int i = 0; i < size; i++) { if (monitor.isCanceled()) return; if (files[i] != null && files[i].isDirectory()) searchDirectory(files[i], runtimeCollector, DEPTH, new SubProgressMonitor(monitor, 80)); monitor.worked(20); } monitor.done(); } else { monitor.beginTask("Searching " + path.toOSString(), 1); monitor.worked(1); monitor.done(); } }
/** * Copy the content in the directory with the given name located in the <code>test_data</code> * directory in the plug-in with the given id into the specified target directory. * * @param pluginId the id of the plug-in containing the project * @param projectName the name of the directory containing the project * @param targetDirectory the directory into which the content is copied. This directory is * created if it does not already exist * @throws IOException if a required file cannot be accessed */ public static void copyPluginRelativeContent( String pluginId, String projectName, File targetDirectory) throws IOException { URL pluginInstallUri = PluginUtilities.getInstallUrl(pluginId); URL sourceUrl = new URL(pluginInstallUri, PROJECT_DIRECTORY_NAME + "/" + projectName); IPath sourcePath = new Path(FileLocator.toFileURL(sourceUrl).getPath()); FileUtilities.copyDirectoryContents(sourcePath.toFile(), targetDirectory); }
/** * Test sample project with a virtual folder that points to configure scripts. Tests Bug 434275 - * Autotools configuration in subfolder not found * * @throws Exception */ @Test public void testAutotoolsVirtualFolder() throws Exception { Path p = new Path("zip/project2.zip"); IWorkspaceRoot root = ProjectTools.getWorkspaceRoot(); IPath rootPath = root.getLocation(); IPath configPath = rootPath.append("config"); File configDir = configPath.toFile(); configDir.deleteOnExit(); assertTrue(configDir.mkdir()); ProjectTools.createLinkedFolder( testProject, "src", URIUtil.append(root.getLocationURI(), "config")); ProjectTools.addSourceContainerWithImport(testProject, "src", p); assertTrue(testProject.hasNature(AutotoolsNewProjectNature.AUTOTOOLS_NATURE_ID)); assertTrue(exists("src/ChangeLog")); ProjectTools.setConfigDir(testProject, "src"); ProjectTools.markExecutable(testProject, "src/autogen.sh"); assertFalse(exists("src/configure")); assertFalse(exists("src/Makefile.in")); assertFalse(exists("src/sample/Makefile.in")); assertFalse(exists("src/aclocal.m4")); assertTrue(ProjectTools.build()); assertTrue(exists("src/configure")); assertTrue(exists("src/Makefile.in")); assertTrue(exists("src/sample/Makefile.in")); assertTrue(exists("src/aclocal.m4")); assertTrue(exists("config.status")); assertTrue(exists("Makefile")); String extension = Platform.getOS().equals(Platform.OS_WIN32) ? ".exe" : ""; assertTrue(exists("sample/a.out" + extension)); assertTrue(exists("sample/Makefile")); }
public static IWorkbench getMockWorkbench(String file) { IWorkbench workbench = mock(IWorkbench.class); IWorkbenchWindow window = mock(IWorkbenchWindow.class); IWorkbenchPage page = mock(IWorkbenchPage.class); ITextEditor editor = mock(ITextEditor.class); IDocumentProvider docProvider = mock(IDocumentProvider.class); IDocument doc = mock(IDocument.class); IPath ipath = mock(IPath.class); File afile = mock(File.class); IFile inputFile = mock(IFile.class); IFileEditorInput editorInput = mock(IFileEditorInput.class); when(workbench.getWorkbenchWindows()).thenReturn(new IWorkbenchWindow[] {window}); when(window.getActivePage()).thenReturn(page); when(page.getActiveEditor()).thenReturn(editor); when(editor.getEditorInput()).thenReturn(editorInput); when(editor.getDocumentProvider()).thenReturn(docProvider); when(editorInput.getFile()).thenReturn(inputFile); when(docProvider.getDocument(any())).thenReturn(doc); when(inputFile.getLocation()).thenReturn(ipath); when(inputFile.getName()).thenReturn(file); when(ipath.toFile()).thenReturn(afile); when(afile.length()).thenReturn(33l); return workbench; }
/** * ************************************************************************ Get the database path * for this project * * @return *********************************************************************** */ @SuppressWarnings("unchecked") public String getDatabasePath() { HashMap<QualifiedName, Object> properties = null; try { properties = new HashMap<QualifiedName, Object>(m_project.getPersistentProperties()); } catch (CoreException e1) { System.err.println( "Cannot retrieve persistent properties for project " + m_project.getName()); return null; } if (!properties.containsKey(ProjectDatabaseProperty.GCS_DATABASE.getKey())) { restoreProjectProperties(ProjectDatabaseProperty.GCS_DATABASE); } try { String path = m_project.getPersistentProperty(ProjectDatabaseProperty.GCS_DATABASE.getKey()); // Relative path boolean absolute = true; if (!path.isEmpty()) { absolute = new File(path).isAbsolute(); } if (!path.isEmpty() && !absolute) { IPath projAbsolute = m_project.getLocation(); String projectPath = projAbsolute.toFile().getAbsolutePath(); path = projectPath + File.separator + path; } return path; } catch (CoreException e) { return null; } }
/** * Remove xml files and zipFile. * * @param zipFile */ private static void removeSendedFiles(File zipFile) { IPath pluginSaveFolder = FeedbackUtils.getFeedbackSaveFolder(); java.io.File source = pluginSaveFolder.toFile(); List<java.io.File> fileList = FileHelper.listAll(source); for (java.io.File f : fileList) { if (f.getName().endsWith(FeedbackUtils.END_FILE_NAME)) { f.delete(); } } try { File.umount(true); } catch (ArchiveException e) { e.printStackTrace(); } // Delete with trueZip function doesn't work java.io.File testFile = new java.io.File(source, FeedbackActivator.ZIP_FILE_NAME); if (testFile.exists()) { try { testFile.delete(); } catch (Exception e) { e.printStackTrace(); } } }