Java Code Examples for org.eclipse.core.runtime.IPath#toFile()

The following examples show how to use org.eclipse.core.runtime.IPath#toFile() . 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: LibraryUtils.java    From msf4j with Apache License 2.0 6 votes vote down vote up
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) {
				return null;
			}
		}
		if (isRelativePath) {
			IPath relativePath = EclipseUtils.getWorkspaceRelativePath(library);
			relativePath = new Path("ECLIPSE_WORKSPACE").append(relativePath);
			return relativePath.toFile();
		} else {
			return library.toFile();
		}
	} else {
		return null;
	}
}
 
Example 2
Source File: XmlUtilsTest.java    From tracecompass with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Test the {@link XmlUtils#addXmlFile(File)} method
 */
@Test
public void testXmlAddFile() {
    /* Check the file does not exist */
    IPath xmlPath = XmlUtils.getXmlFilesPath().addTrailingSeparator().append("test_valid.xml");
    File destFile = xmlPath.toFile();
    assertFalse(destFile.exists());

    /* Add test_valid.xml file */
    File testXmlFile = TmfXmlTestFiles.VALID_FILE.getFile();
    if ((testXmlFile == null) || !testXmlFile.exists()) {
        fail("XML test file does not exist");
    }

    XmlUtils.addXmlFile(testXmlFile);
    assertTrue(destFile.exists());
}
 
Example 3
Source File: InvisibleProjectImporter.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
public static String getPackageName(IPath javaFile, IPath workspaceRoot, IJavaProject javaProject, String[][] srcPrefixes) {
	File nioFile = javaFile.toFile();
	try {
		String content = com.google.common.io.Files.toString(nioFile, StandardCharsets.UTF_8);
		if (StringUtils.isBlank(content)) {
			File found = findNearbyNonEmptyFile(nioFile);
			if (found == null) {
				return inferPackageNameFromPath(javaFile, workspaceRoot, srcPrefixes);
			}

			nioFile = found;
		}
	} catch (IOException e) {
	}

	return JDTUtils.getPackageName(javaProject, nioFile.toURI());
}
 
Example 4
Source File: Util.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Returns the names of the validation jars that are co-located with the GWT
 * SDK's core jars. If the validation jars are present, there should be two of
 * them: <code>validation-api-<version>.jar</code> and
 * <code>validation-api-<version>-sources.jar</code>.
 *
 * If the validation jars are not present (i.e. this is a pre-GWT 2.3 SDK),
 * then an empty array is returned.
 */
public static String[] getValidationJarNames(IPath sdkLocation) {
  File sdkDir = sdkLocation.toFile();
  if (!sdkDir.exists()) {
    return null;
  }

  String[] validationJarNames = sdkDir.list(new FilenameFilter() {
    @Override
    public boolean accept(File file, String fileName) {
      if (fileName.startsWith(GwtSdk.VALIDATION_API_JAR_PREFIX)
          && fileName.endsWith(".jar")
          && file.exists()) {
        return true;
      }
      return false;
    }
  });

  return validationJarNames;
}
 
Example 5
Source File: N4JSProjectExplorerHelper.java    From n4js with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Returns with {@code true} if the folder argument represents a node_modules folder in its container project.
 * Otherwise returns with {@code false}.
 *
 * @param container
 *            the folder to test whether it is an output folder or not.
 * @return {@code true} if the folder is detected as an node_modules folder in the project, otherwise returns with
 *         {@code false}.
 */
public boolean isNodeModulesFolder(IContainer container) {
	if (N4JSGlobals.NODE_MODULES.equals(container.getName()) && container instanceof IFolder) {
		IPath path = container.getLocation();
		FileURI locURI = new FileURI(path.toFile());
		if (prefStore.getNodeModulesLocations().contains(locURI)) {
			return true;
		}
	}
	return false;
}
 
Example 6
Source File: XmlUtilsTest.java    From tracecompass with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Test various invalid files and make sure they are invalid
 */
@Test
public void testXmlValidateInvalid() {
    IPath path = Activator.getAbsolutePath(PATH_INVALID);
    File file = path.toFile();

    File[] invalidFiles = file.listFiles();
    assertTrue(invalidFiles.length > 0);
    for (File f : invalidFiles) {
        assertFalse("File " + f.getName(), XmlUtils.xmlValidate(f).isOK());
    }
}
 
Example 7
Source File: XmlUtils.java    From tracecompass with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Get the path where the XML files are stored. Create it if it does not exist
 *
 * @return path to XML files
 */
public static IPath getXmlFilesPath() {
    IPath path = Activator.getDefault().getStateLocation();
    path = path.addTrailingSeparator().append(XML_DIRECTORY);

    /* Check if directory exists, otherwise create it */
    File dir = path.toFile();
    if (!dir.exists() || !dir.isDirectory()) {
        dir.mkdirs();
    }

    return path;
}
 
Example 8
Source File: ConnectionPointManager.java    From APICloud-Studio with GNU General Public License v3.0 5 votes vote down vote up
/**
 * loadState
 * 
 * @param path
 */
/* package */void loadState(IPath path)
{
	File file = path.toFile();
	if (file.exists())
	{
		connections.clear();
		unresolvedConnections.clear();

		addConnectionsFrom(path);
	}
}
 
Example 9
Source File: CordovaLibraryJsContainerInitializer.java    From thym with Eclipse Public License 1.0 5 votes vote down vote up
private IPath getLibraryRuntimeFolder(){
	IPath libraryRuntimePath = Platform.getStateLocation(Platform.getBundle(HybridCore.PLUGIN_ID)).append("cordovaJsLib");
	File libRuntimeFile = libraryRuntimePath.toFile();
	if(!libRuntimeFile.isDirectory()){
		libRuntimeFile.mkdir();
	}
	return libraryRuntimePath;

}
 
Example 10
Source File: EnableSarlMavenNatureAction.java    From sarl with Apache License 2.0 5 votes vote down vote up
/** Create the configuration job for a Maven project.
 *
 * @param project the project to configure.
 * @return the job.
 */
@SuppressWarnings("static-method")
protected Job createJobForMavenProject(IProject project) {
	return new Job(Messages.EnableSarlMavenNatureAction_0) {

		@Override
		protected IStatus run(IProgressMonitor monitor) {
			final SubMonitor mon = SubMonitor.convert(monitor, 3);
			try {
				// The project should be a Maven project.
				final IPath descriptionFilename = project.getFile(new Path(IProjectDescription.DESCRIPTION_FILE_NAME)).getLocation();
				final File projectDescriptionFile = descriptionFilename.toFile();
				final IPath classpathFilename = project.getFile(new Path(FILENAME_CLASSPATH)).getLocation();
				final File classpathFile = classpathFilename.toFile();
				// Project was open by the super class. Close it because Maven fails when a project already exists.
				project.close(mon.newChild(1));
				// Delete the Eclipse project and classpath definitions because Maven fails when a project already exists.
				project.delete(false, true, mon.newChild(1));
				if (projectDescriptionFile.exists()) {
					projectDescriptionFile.delete();
				}
				if (classpathFile.exists()) {
					classpathFile.delete();
				}
				// Import
				MavenImportUtils.importMavenProject(
						project.getWorkspace().getRoot(),
						project.getName(),
						true,
						mon.newChild(1));
			} catch (CoreException exception) {
				SARLMavenEclipsePlugin.getDefault().log(exception);
			}
			return Status.OK_STATUS;
		}
	};
}
 
Example 11
Source File: GlobalCheckConfigurationWorkingSet.java    From eclipse-cs with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Store the check configurations to the persistent state storage.
 */
private void storeToPersistence() throws CheckstylePluginException {

  try {

    IPath configPath = CheckstylePlugin.getDefault().getStateLocation();
    configPath = configPath.append(CheckConfigurationFactory.CHECKSTYLE_CONFIG_FILE);
    File configFile = configPath.toFile();

    ICheckConfiguration defaultConfig = mDefaultCheckConfig;

    // don't store as default when it's already the built-in default
    if (defaultConfig != null
            && defaultConfig.getName().equals(mDefaultBuiltInCheckConfig.getName())) {
      defaultConfig = null;
    }

    Document doc = createCheckConfigurationsDocument(mWorkingCopies, defaultConfig);

    // write to the file after the document creation was successful
    // prevents corrupted files in case of error
    byte[] data = XMLUtil.toByteArray(doc);
    Files.write(data, configFile);
  } catch (IOException e) {
    CheckstylePluginException.rethrow(e, Messages.errorWritingConfigFile);
  }
}
 
Example 12
Source File: XmlUtilsTest.java    From tracecompass with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Test various valid files and make sure they are valid
 */
@Test
public void testXmlValidateValid() {
    IPath path = Activator.getAbsolutePath(PATH_VALID);
    File file = path.toFile();

    File[] validFiles = file.listFiles();
    assertTrue(validFiles.length > 0);
    for (File f : validFiles) {
        assertTrue("File " + f.getName(), XmlUtils.xmlValidate(f).isOK());
    }
}
 
Example 13
Source File: EMFBasedPersister.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
protected File getBuilderStateLocation() {
	Activator activator = Activator.getDefault();
	if (activator == null) {
		if (cachedPath != null)
			return cachedPath.toFile();
		return null;
	}
	IPath path = activator.getStateLocation().append("builder.state");
	cachedPath = path;
	return path.toFile();
}
 
Example 14
Source File: BundleManager.java    From APICloud-Studio with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Return the bundle directory that contains the specified script. We traverse parents until we find a directory
 * that {@link #isValidBundleDirectory(File)}
 * 
 * @param script
 *            The descendant script used to locate the bundle directory. Null values are ignored
 * @return The bundle directory or null if the specified script was null
 */
public File getBundleDirectory(File script)
{
	File result = null;

	if (script != null)
	{
		IPath path = Path.fromOSString(script.getAbsolutePath());
		if (script.isFile())
		{
			// Cheat a little and skip to parent already if this is a file
			path = path.removeLastSegments(1);
		}
		// Search up the hierarchy until we hit the bundle dir
		File file = path.toFile();
		while (true)
		{
			if (isValidBundleDirectory(file))
			{
				return file;
			}
			if (path.segmentCount() == 0)
			{
				break;
			}
			path = path.removeLastSegments(1);
			file = path.toFile();
		}
	}

	return result;
}
 
Example 15
Source File: IndexSynchronizerPluginTest.java    From n4js with Eclipse Public License 1.0 4 votes vote down vote up
/***/
private void installDeregisterAndReregisterNpm(Consumer<IProject> build) throws Exception {

	File prjDir = new File(getResourceUri(PROBANDS, SUBFOLDER));
	IProject project = ProjectTestsUtils.importProject(prjDir, PROJECT_NAME);
	libraryManager.registerAllExternalProjects(new NullProgressMonitor());
	IResource packagejson = project.findMember(N4JSGlobals.PACKAGE_JSON);
	IResource abc = project.findMember("src/ABC.n4js");
	build.accept(project);

	assertIssues(packagejson, "line 6: Project does not exist with project ID: snafu.");
	assertIssues(abc,
			"line 12: Cannot resolve plain module specifier (without project name as first segment): no matching module found.");

	assertFalse(indexSynchronizer.findNpmsInIndex().containsKey(NPM_SNAFU));
	libraryManager.installNPM(NPM_SNAFU, new PlatformResourceURI(project).toFileURI(), new NullProgressMonitor());
	// waitForAutoBuild();
	assertTrue(indexSynchronizer.findNpmsInIndex().containsKey(NPM_SNAFU));

	assertIssues(packagejson);
	assertIssues(abc);

	N4JSExternalProject snafu = externalLibraryWorkspace.getProject(NPM_SNAFU);
	assertTrue(snafu != null);
	IPath location = snafu.getLocation();
	File file = location.toFile();
	assertTrue(file.exists());

	File tmpLocation = file.getParentFile().getParentFile();
	File oldCopy = tmpLocation.toPath().resolve(file.getName()).toFile();
	if (oldCopy.exists()) {
		FileUtils.deleteFileOrFolder(oldCopy);
	}
	Files.move(file.toPath(), oldCopy.toPath());
	assertFalse(file.exists());
	build.accept(project);

	assertIssues(packagejson, "line 6: Project does not exist with project ID: snafu.");
	assertIssues(abc,
			"line 12: Cannot resolve plain module specifier (without project name as first segment): no matching module found.");

	build.accept(project);
	assertIssues(packagejson, "line 6: Project does not exist with project ID: snafu.");
	assertIssues(abc,
			"line 12: Cannot resolve plain module specifier (without project name as first segment): no matching module found.");

	Files.move(oldCopy.toPath(), file.toPath());
	assertTrue(file.exists());
	build.accept(project);

	assertIssues(packagejson, "line 6: Project snafu is not registered.");
	assertIssues(abc,
			"line 12: Cannot resolve project import: no matching module found.");

	libraryManager.registerAllExternalProjects(new NullProgressMonitor());
	build.accept(project);

	assertIssues(packagejson);
	assertIssues(abc);
}
 
Example 16
Source File: FatJarRsrcUrlAntExporter.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
@Override
protected void buildANTScript(IPath antScriptLocation, String projectName, IPath absJarfile, String mainClass, SourceInfo[] sourceInfos) throws FileNotFoundException, IOException {
	File antScriptFile= antScriptLocation.toFile();
	buildANTScript(new FileOutputStream(antScriptFile), projectName, absJarfile, mainClass, sourceInfos);
	copyJarInJarLoader(new File(antScriptFile.getParentFile(), FatJarRsrcUrlBuilder.JAR_RSRC_LOADER_ZIP));
}
 
Example 17
Source File: ResourceUtils.java    From LogViewer with Eclipse Public License 2.0 4 votes vote down vote up
static public File toFile(IPath iPath)
{
	if (iPath != null)
		return iPath.toFile();
	return null;
}
 
Example 18
Source File: ControlViewTest.java    From tracecompass with Eclipse Public License 2.0 4 votes vote down vote up
private static void generateTrace(IPath path) {
    File traceParent = path.toFile();
    traceParent.mkdirs();
    LttngTraceGenerator.generateLttngTrace(path.append(ControlViewSwtBotUtil.KERNEL_TRACE_NAME).toFile());
}
 
Example 19
Source File: BasePublishOperation.java    From google-cloud-eclipse with Apache License 2.0 4 votes vote down vote up
protected void publishArchiveModule(String jarURI, Properties p, List<IStatus> statuses,
    IProgressMonitor monitor) {
  IPath path = 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();
  }
  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
      || isServeModulesWithoutPublish()) {
    File file = oldJarPath.toFile();
    if (file.exists()) {
      file.delete();
    }
    p.remove(module[1].getId());

    if (deltaKind == ServerBehaviourDelegate.REMOVED
        || isServeModulesWithoutPublish()) {
      return;
    }
  }
  if (!moving && kind != IServer.PUBLISH_CLEAN && kind != IServer.PUBLISH_FULL) {
    // avoid changes if no changes to module since last publish
    IModuleResourceDelta[] delta = 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 = getResources(module);
  IStatus[] status = helper.publishToPath(mr, jarPath, monitor);
  addArrayToList(statuses, status);
  p.put(module[1].getId(), jarURI);
}
 
Example 20
Source File: BasePublishOperation.java    From google-cloud-eclipse with Apache License 2.0 4 votes vote down vote up
protected void publishJar(String jarURI, Properties properties, List<IStatus> statuses,
    IProgressMonitor monitor) throws CoreException {
  IPath path = getModuleDeployDirectory(module[0]);
  boolean moving = false;
  // Get URI used for previous publish, if known
  String oldURI = (String) properties.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() + ".jar";
  }
  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
      || isServeModulesWithoutPublish()) {
    File file = oldJarPath.toFile();
    if (file.exists())
      file.delete();
    properties.remove(module[1].getId());

    if (deltaKind == ServerBehaviourDelegate.REMOVED
        || isServeModulesWithoutPublish())
      return;
  }
  if (!moving && kind != IServer.PUBLISH_CLEAN && kind != IServer.PUBLISH_FULL) {
    // avoid changes if no changes to module since last publish
    IModuleResourceDelta[] delta = 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 = getResources(module);
  IStatus[] status = helper.publishZip(mr, jarPath, monitor);
  addArrayToList(statuses, status);
  properties.put(module[1].getId(), jarURI);
}