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

The following examples show how to use org.eclipse.core.runtime.IPath#toOSString() . 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: TopLevelFolder.java    From gama with GNU General Public License v3.0 6 votes vote down vote up
protected Location estimateLocation(final IPath location) {
	try {
		final URL old_url = new URL("platform:/plugin/" + GamaBundleLoader.CORE_MODELS.getSymbolicName() + "/");
		final URL new_url = FileLocator.toFileURL(old_url);
		// windows URL formating
		final URI resolvedURI = new URI(new_url.getProtocol(), new_url.getPath(), null).normalize();
		final URL urlRep = resolvedURI.toURL();
		final String osString = location.toOSString();
		final boolean isTest = osString.contains(GamaBundleLoader.REGULAR_TESTS_LAYOUT);
		if (!isTest && osString.startsWith(urlRep.getPath())) { return Location.CoreModels; }
		if (osString
				.startsWith(urlRep.getPath().replace(GamaBundleLoader.CORE_MODELS.getSymbolicName() + "/", ""))) {
			if (isTest) { return Location.Tests; }
			return Location.Plugins;
		}
		return Location.Other;
	} catch (final IOException | URISyntaxException e) {
		e.printStackTrace();
		return Location.Unknown;
	}
}
 
Example 2
Source File: HierarchicalDataModel.java    From dawnsci with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public IHierarchicalDataFileModel getFileModel(IFile file) {
	synchronized (cache) {
		if (file == null)
			return INVALID_FILE_MODEL;
		IPath rawLocation = file.getRawLocation();
		if (rawLocation == null)
			return INVALID_FILE_MODEL;
		final String fullPath = rawLocation.toOSString();
		if (cache.containsKey(fullPath)) {
			return cache.get(fullPath);
		}

		IHierarchicalDataFileModel model = getModel.createFileModel(fullPath);
		cache.put(fullPath, model);
		return model;
	}
}
 
Example 3
Source File: FindBugsWorker.java    From spotbugs with GNU Lesser General Public License v2.1 6 votes vote down vote up
private Map<String, Boolean> relativeToAbsolute(Map<String, Boolean> map) {
    Map<String, Boolean> resultMap = new TreeMap<>();
    for (Entry<String, Boolean> entry : map.entrySet()) {
        if (!entry.getValue().booleanValue()) {
            continue;
        }
        String filePath = entry.getKey();
        IPath path = getFilterPath(filePath, project);
        if (!path.toFile().exists()) {
            FindbugsPlugin.getDefault().logWarning("Filter not found: " + filePath);
            continue;
        }
        String filterName = path.toOSString();
        resultMap.put(filterName, Boolean.TRUE);
    }
    return resultMap;
}
 
Example 4
Source File: AnalysisPlugin.java    From Pydev with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Returns the directory that can be used to store things for some project
 */
public static File getStorageDirForProject(IProject p) {
    if (AnalysisPlugin.getDefault() == null) {
        return new File(".");
    }
    IPath location = p.getWorkingLocation("com.python.pydev.analysis");
    IPath path = location;

    File file = new File(path.toOSString());
    return file;
}
 
Example 5
Source File: GamlResourceServices.java    From gama with GNU General Public License v3.0 5 votes vote down vote up
public static String getModelPathOf(final Resource r) {
	// Likely in a headless scenario (w/o workspace)
	if (r.getURI().isFile()) {
		return new Path(r.getURI().toFileString()).toOSString();
	} else {
		final IPath path = getPathOf(r);
		final IFile file = ResourcesPlugin.getWorkspace().getRoot().getFile(path);
		final IPath fullPath = file.getLocation();
		return fullPath == null ? "" : fullPath.toOSString();
	}
}
 
Example 6
Source File: BasicElementLabels.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Returns the label of a path.
 *
 * @param path the path
 * @param isOSPath if <code>true</code>, the path represents an OS path, if <code>false</code> it is a workspace path.
 * @return the label of the path to be used in the UI.
 */
public static String getPathLabel(IPath path, boolean isOSPath) {
	String label;
	if (isOSPath) {
		label= path.toOSString();
	} else {
		label= path.makeRelative().toString();
	}
	return Strings.markLTR(label);
}
 
Example 7
Source File: IndexBasedHierarchyBuilder.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
protected IBinaryType createInfoFromClassFileInJar(Openable classFile) {
	String filePath = (((ClassFile)classFile).getType().getFullyQualifiedName('$')).replace('.', '/') + SuffixConstants.SUFFIX_STRING_class;
	IPackageFragmentRoot root = classFile.getPackageFragmentRoot();
	IPath path = root.getPath();
	// take the OS path for external jars, and the forward slash path for internal jars
	String rootPath = path.getDevice() == null ? path.toString() : path.toOSString();
	String documentPath = rootPath + IJavaSearchScope.JAR_FILE_ENTRY_SEPARATOR + filePath;
	IBinaryType binaryType = (IBinaryType)this.binariesFromIndexMatches.get(documentPath);
	if (binaryType != null) {
		this.infoToHandle.put(binaryType, classFile);
		return binaryType;
	} else {
		return super.createInfoFromClassFileInJar(classFile);
	}
}
 
Example 8
Source File: AbstractFileBasedRenamingTest.java    From sarl with Apache License 2.0 5 votes vote down vote up
/** Set up.
 * @throws Exception
 */
@Before
public void setUp() throws Exception {
	this.source = getFullSourceCode();
	this.expected = getFullExpectedCode();
	final String filename = getSourcePackageName() + ".unittest"; //$NON-NLS-1$
	this.filename = helper().generateFilename(filename.split("\\.")); //$NON-NLS-1$
	this.file = helper().createFile(this.filename, this.source);
	helper().openEditor(this.file);
	IPath path = WorkbenchTestHelper.path(getExpectedPackageName().split("\\.")); //$NON-NLS-1$
	String basename = this.file.getLocation().lastSegment();
	path = path.append(basename);
	this.newFilename = path.toOSString();
}
 
Example 9
Source File: AndroidSDKManager.java    From thym with Eclipse Public License 1.0 5 votes vote down vote up
public static AndroidSDKManager getManager() throws CoreException{
	String sdkDir = AndroidCore.getSDKLocation();
	if(sdkDir == null ){
		throw new CoreException(new HybridMobileStatus(IStatus.ERROR, AndroidCore.PLUGIN_ID, AndroidConstants.STATUS_CODE_ANDROID_SDK_NOT_DEFINED, 
				"Android SDK location is not defined", null));
	}
	Path path = new Path(sdkDir);
	IPath tools = path.append("tools").addTrailingSeparator();
	IPath platform = path.append("platform-tools").addTrailingSeparator();
	AndroidSDKManager sdk = new AndroidSDKManager(tools.toOSString(), platform.toOSString());
	return sdk;
}
 
Example 10
Source File: BasicElementLabels.java    From Pydev with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Returns the label of a path. 
 * 
 * @param path the path
 * @param isOSPath if <code>true</code>, the path represents an OS path, if <code>false</code> it is a workspace path.
 * @return the label of the path to be used in the UI.
 */
public static String getPathLabel(IPath path, boolean isOSPath) {
    String label;
    if (isOSPath) {
        label = path.toOSString();
    } else {
        label = path.makeRelative().toString();
    }
    return markLTR(label, "/\\:."); //$NON-NLS-1$
}
 
Example 11
Source File: IndexManager.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public synchronized IndexLocation computeIndexLocation(IPath containerPath) {
	IndexLocation indexLocation = (IndexLocation) this.indexLocations.get(containerPath);
	if (indexLocation == null) {
		String pathString = containerPath.toOSString();
		CRC32 checksumCalculator = new CRC32();
		checksumCalculator.update(pathString.getBytes());
		String fileName = Long.toString(checksumCalculator.getValue()) + ".index"; //$NON-NLS-1$
		if (VERBOSE)
			Util.verbose("-> index name for " + pathString + " is " + fileName); //$NON-NLS-1$ //$NON-NLS-2$
		// to share the indexLocation between the indexLocations and indexStates tables, get the key from the indexStates table
		indexLocation = (IndexLocation) getIndexStates().getKey(new FileIndexLocation(new File(getSavedIndexesDirectory(), fileName)));
		this.indexLocations.put(containerPath, indexLocation);
	}
	return indexLocation;
}
 
Example 12
Source File: ConversionResource.java    From tmxeditor8 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * 本类用于管理转换的资源
 * @param direction
 *            转换方向
 * @param location
 *            绝对路径
 * @throws CoreException
 */
public ConversionResource(String direction, IPath location) throws CoreException {
	this.direction = direction;
	file = root.getFileForLocation(location);
	if (file != null) {
		project = file.getProject();
		projectRelativePath = file.getProjectRelativePath();
		if (projectRelativePath.segmentCount() > 1) {
			projectRelativePath = projectRelativePath.removeFirstSegments(1); // 移除 project 下的第一级目录。
		}
	} else {
		throw new CoreException(new Status(IStatus.WARNING, Activator.PLUGIN_ID, "找不到该文件:" + location.toOSString()));
	}
}
 
Example 13
Source File: GwtSdk.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public String getName() {
  IPath installationPath = getInstallationPath();
  if (installationPath != null) {
    return installationPath.toOSString();
  } else {
    return "Unknown";
  }
}
 
Example 14
Source File: GwtWtpPlugin.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Return the launcher directory path.
 * 
 * The -launcherDir war/output/path is the war deployment directory
 * 
 * @param server
 * @param launchConfig
 * @param gwtFacetedProject
 * @return the launcher directory or war output path
 */
private String getLauncherDirectory(IServer server, ILaunchConfiguration launchConfig,
    IFacetedProject gwtFacetedProject) {
  String launcherDir = null;

  // The root module will be the server module
  // The root module may have children such as, client, shared
  // The root module may not have any children
  for (IModule[] module : getAllModules(server)) {
    if (module[module.length - 1].getProject() == gwtFacetedProject.getProject()) {
      // Child modules are overlaid or included in the root module
      IPath path = null;
      if (server instanceof IModulePublishHelper) {
        path = ((IModulePublishHelper) server).getPublishDirectory(new IModule[] { module[0] });
      } else {
        IModulePublishHelper helper = server.getAdapter(IModulePublishHelper.class);
        if (helper != null) {
          path = helper.getPublishDirectory(new IModule[] { module[0] });
        }
      }
      // example:
      // /Users/branflake2267/Documents/runtime-EclipseApplication/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/broyer-sandbox-server
      launcherDir = path == null ? null : path.toOSString();
      if (launcherDir != null) {
        return launcherDir;
      }
    }
  }

  // Get the the war output path from classic launch configuration working directory
  // Also used GaeServerBehaviour.setupLaunchConfig(...)
  try {
    launcherDir = launchConfig.getAttribute(IJavaLaunchConfigurationConstants.ATTR_WORKING_DIRECTORY, (String) null);
  } catch (CoreException e) {
    logMessage(
        "posiblyLaunchGwtSuperDevModeCodeServer: Couldn't get working directory from launchConfig IJavaLaunchConfigurationConstants.ATTR_WORKING_DIRECTORY.");
  }

  return launcherDir;
}
 
Example 15
Source File: SharedCorePlugin.java    From Pydev with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Given a resource get the string in the filesystem for it.
 */
public static String getIResourceOSString(IResource f) {
    URI locationURI = f.getLocationURI();
    if (locationURI != null) {
        try {
            //RTC source control not return a valid uri
            return FileUtils.getFileAbsolutePath(new File(locationURI));
        } catch (IllegalArgumentException e) {
        }
    }

    IPath rawLocation = f.getRawLocation();
    if (rawLocation == null) {
        return null; //yes, we could have a resource that was deleted but we still have it's representation...
    }
    String fullPath = rawLocation.toOSString();
    //now, we have to make sure it is canonical...
    File file = new File(fullPath);
    if (file.exists()) {
        return FileUtils.getFileAbsolutePath(file);
    } else {
        //it does not exist, so, we have to check its project to validate the part that we can
        IProject project = f.getProject();
        IPath location = project.getLocation();
        File projectFile = location.toFile();
        if (projectFile.exists()) {
            String projectFilePath = FileUtils.getFileAbsolutePath(projectFile);

            if (fullPath.startsWith(projectFilePath)) {
                //the case is all ok
                return fullPath;
            } else {
                //the case appears to be different, so, let's check if this is it...
                if (fullPath.toLowerCase().startsWith(projectFilePath.toLowerCase())) {
                    String relativePart = fullPath.substring(projectFilePath.length());

                    //at least the first part was correct
                    return projectFilePath + relativePart;
                }
            }
        }
    }

    //it may not be correct, but it was the best we could do...
    return fullPath;
}
 
Example 16
Source File: Utilities.java    From APICloud-Studio with GNU General Public License v3.0 4 votes vote down vote up
public static File getFile()
{
	IPath stateLocation = CommonEditorPlugin.getDefault().getStateLocation();
	IPath path = stateLocation.append("/_" + new Object().hashCode()); //$NON-NLS-1$ 
	return new File(path.toOSString());
}
 
Example 17
Source File: JavaHotCodeReplaceProvider.java    From java-debug with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Answers whether children should be visited.
 * <p>
 * If the associated resource is a class file which has been changed, record it.
 * </p>
 */
@Override
public boolean visit(IResourceDelta delta) {
    if (delta == null || 0 == (delta.getKind() & IResourceDelta.CHANGED)) {
        return false;
    }
    IResource resource = delta.getResource();
    if (resource != null) {
        switch (resource.getType()) {
            case IResource.FILE:
                if (0 == (delta.getFlags() & IResourceDelta.CONTENT)) {
                    return false;
                }
                if (CLASS_FILE_EXTENSION.equals(resource.getFullPath().getFileExtension())) {
                    IPath localLocation = resource.getLocation();
                    if (localLocation != null) {
                        String path = localLocation.toOSString();
                        IClassFileReader reader = ToolFactory.createDefaultClassFileReader(path,
                                IClassFileReader.CLASSFILE_ATTRIBUTES);
                        if (reader != null) {
                            // this name is slash-delimited
                            String qualifiedName = new String(reader.getClassName());
                            boolean hasBlockingErrors = false;
                            try {
                                // If the user doesn't want to replace
                                // classfiles containing
                                // compilation errors, get the source
                                // file associated with
                                // the class file and query it for
                                // compilation errors
                                IJavaProject pro = JavaCore.create(resource.getProject());
                                ISourceAttribute sourceAttribute = reader.getSourceFileAttribute();
                                String sourceName = null;
                                if (sourceAttribute != null) {
                                    sourceName = new String(sourceAttribute.getSourceFileName());
                                }
                                IResource sourceFile = getSourceFile(pro, qualifiedName, sourceName);
                                if (sourceFile != null) {
                                    IMarker[] problemMarkers = null;
                                    problemMarkers = sourceFile.findMarkers(
                                            IJavaModelMarker.JAVA_MODEL_PROBLEM_MARKER, true,
                                            IResource.DEPTH_INFINITE);
                                    for (IMarker problemMarker : problemMarkers) {
                                        if (problemMarker.getAttribute(IMarker.SEVERITY,
                                                -1) == IMarker.SEVERITY_ERROR) {
                                            hasBlockingErrors = true;
                                            break;
                                        }
                                    }
                                }
                            } catch (CoreException e) {
                                logger.log(Level.SEVERE, "Failed to visit classes: " + e.getMessage(), e);
                            }
                            if (!hasBlockingErrors) {
                                changedFiles.add(resource);
                                // dot-delimit the name
                                fullyQualifiedNames.add(qualifiedName.replace('/', '.'));
                            }
                        }
                    }
                }
                return false;

            default:
                return true;
        }
    }
    return true;
}
 
Example 18
Source File: AltConfigWizard.java    From CogniCrypt with Eclipse Public License 2.0 4 votes vote down vote up
/**
 * This method is called once the user selects an instance. It writes the instance to an xml file and calls the code generation.
 *
 * @return <code>true</code>/<code>false</code> if writing instance file and code generation are (un)successful
 */
@Override
public boolean performFinish() {
	boolean ret = false;
	final CodeGenerators genKind = selectedTask.getCodeGen();
	CodeGenerator codeGenerator = null;
	String additionalResources = selectedTask.getAdditionalResources();
	final LocatorPage currentPage = (LocatorPage) getContainer().getCurrentPage();
	IResource targetFile = (IResource) currentPage.getSelectedResource().getFirstElement();

	String taskName = selectedTask.getName();
	JOptionPane optionPane = new JOptionPane("CogniCrypt is now generating code that implements " + selectedTask.getDescription() + "\ninto file " + ((targetFile != null)
		? targetFile.getName()
		: "Output.java") + ". This should take no longer than a few seconds.", JOptionPane.INFORMATION_MESSAGE, JOptionPane.DEFAULT_OPTION, null, new Object[] {}, null);
	JDialog waitingDialog = optionPane.createDialog("Generating Code");
	waitingDialog.setModal(false);
	waitingDialog.setVisible(true);
	Configuration chosenConfig = null;
	try {
		switch (genKind) {
			case CrySL:
				CrySLBasedCodeGenerator.clearParameterCache();
				File templateFile = CodeGenUtils.getResourceFromWithin(selectedTask.getCodeTemplate()).listFiles()[0];
				codeGenerator = new CrySLBasedCodeGenerator(targetFile);
				String projectRelDir = Constants.outerFileSeparator + codeGenerator.getDeveloperProject()
					.getSourcePath() + Constants.outerFileSeparator + Constants.PackageName + Constants.outerFileSeparator;
				String pathToTemplateFile = projectRelDir + templateFile.getName();
				String resFileOSPath = "";

				IPath projectPath = targetFile.getProject().getRawLocation();
				if (projectPath == null) {
					projectPath = targetFile.getProject().getLocation();
				}
				resFileOSPath = projectPath.toOSString() + pathToTemplateFile;

				Files.createDirectories(Paths.get(projectPath.toOSString() + projectRelDir));
				Files.copy(templateFile.toPath(), Paths.get(resFileOSPath), StandardCopyOption.REPLACE_EXISTING);
				codeGenerator.getDeveloperProject().refresh();

				resetAnswers();
				chosenConfig = new CrySLConfiguration(resFileOSPath, ((CrySLBasedCodeGenerator) codeGenerator).setUpTemplateClass(pathToTemplateFile));
				break;
			case XSL:
				this.constraints = (this.constraints != null) ? this.constraints : new HashMap<>();
				final InstanceGenerator instanceGenerator = new InstanceGenerator(CodeGenUtils.getResourceFromWithin(selectedTask.getModelFile())
					.getAbsolutePath(), "c0_" + taskName, selectedTask.getDescription());
				instanceGenerator.generateInstances(this.constraints);

				// Initialize Code Generation
				codeGenerator = new XSLBasedGenerator(targetFile, selectedTask.getCodeTemplate());
				chosenConfig = new XSLConfiguration(instanceGenerator.getInstances().values().iterator()
					.next(), this.constraints, codeGenerator.getDeveloperProject().getProjectPath() + Constants.innerFileSeparator + Constants.pathToClaferInstanceFile);
				break;
			default:
				return false;
		}
		ret = codeGenerator.generateCodeTemplates(chosenConfig, additionalResources);

		try {
			codeGenerator.getDeveloperProject().refresh();
		} catch (CoreException e1) {
			Activator.getDefault().logError(e1);
		}

	} catch (Exception ex) {
		Activator.getDefault().logError(ex);
	} finally {

		waitingDialog.setVisible(false);
		waitingDialog.dispose();
	}

	return ret;
}
 
Example 19
Source File: NewReportWizard.java    From birt with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Get the defualt location for the provided name.
 * 
 * @return the location
 */
private String getDefaultLocation( )
{
	IPath defaultPath = Platform.getLocation( );
	return defaultPath.toOSString( );
}
 
Example 20
Source File: ResourceUtils.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 2 votes vote down vote up
/**
 * Reads the contents of a file.
 *
 * @param path the absolute filesystem path to the file
 * @return the contents of the file
 * @throws IOException
 */
public static String readFileContents(IPath path) throws IOException {
  File file = new File(path.toOSString());
  return readFileContents(file);
}