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

The following examples show how to use org.eclipse.core.runtime.IPath#toString() . 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: FileUtils.java    From gama with GNU General Public License v3.0 6 votes vote down vote up
private static String findInWorkspace(final String fp, final IContainer container, final boolean mustExist) {
	final IPath full = container.getFullPath().append(fp);
	IResource file = ROOT.getFile(full);
	if (!file.exists()) {
		// Might be a folder we're looking for
		file = ROOT.getFolder(full);
	}
	if (!file.exists()) {
		if (mustExist) { return null; }
	}
	final IPath loc = file.getLocation();
	// cf. #2997
	if (loc == null) { return fp; }
	return loc.toString();
	// getLocation() works for regular and linked files
}
 
Example 2
Source File: FatJarAntExporter.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
protected static SourceInfo[] convert(IPath[] classpath) {
	SourceInfo[] result= new SourceInfo[classpath.length];
	for (int i= 0; i < classpath.length; i++) {
		IPath path= classpath[i];
		if (path != null) {
			if (path.toFile().isDirectory()) {
				result[i]= new SourceInfo(false, path.toString(), ""); //$NON-NLS-1$
			} else if (path.toFile().isFile()) {
				// TODO: check for ".jar" extension?
				result[i]= new SourceInfo(true, path.toString(), ""); //$NON-NLS-1$
			}
		}
	}

	return result;
}
 
Example 3
Source File: CreateMultipleSourceFoldersDialog.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Asks to change the output folder to 'proj/bin' when no source folders were existing
 *
 * @param existing the element to remove
 * @return returns <code>true</code> if the element has been removed
 */
private boolean removeProjectFromBP(CPListElement existing) {
	IPath outputFolder= new Path(fOutputLocation);

	IPath newOutputFolder= null;
	String message;
	if (outputFolder.segmentCount() == 1) {
		String outputFolderName= PreferenceConstants.getPreferenceStore().getString(PreferenceConstants.SRCBIN_BINNAME);
		newOutputFolder= outputFolder.append(outputFolderName);
		message= Messages.format(NewWizardMessages.SourceContainerWorkbookPage_ChangeOutputLocationDialog_project_and_output_message, BasicElementLabels.getPathLabel(newOutputFolder, false));
	} else {
		message= NewWizardMessages.SourceContainerWorkbookPage_ChangeOutputLocationDialog_project_message;
	}
	String title= NewWizardMessages.SourceContainerWorkbookPage_ChangeOutputLocationDialog_title;
	if (MessageDialog.openQuestion(getShell(), title, message)) {
		fRemovedElements.add(existing);
		if (newOutputFolder != null) {
			fOutputLocation= newOutputFolder.toString();
		}
		return true;
	}
	return false;
}
 
Example 4
Source File: GitCommitHandlerV1.java    From orion.server with Eclipse Public License 1.0 6 votes vote down vote up
private boolean identifyNewCommitResource(HttpServletRequest request, HttpServletResponse response, Repository db, String newCommit)
		throws ServletException {
	try {
		URI u = getURI(request);
		IPath p = new Path(u.getPath());
		IPath np = new Path("/"); //$NON-NLS-1$
		for (int i = 0; i < p.segmentCount(); i++) {
			String s = p.segment(i);
			if (i == 2) {
				s += ".." + GitUtils.encode(newCommit); //$NON-NLS-1$
			}
			np = np.append(s);
		}
		if (p.hasTrailingSeparator())
			np = np.addTrailingSeparator();
		URI nu = new URI(u.getScheme(), u.getUserInfo(), u.getHost(), u.getPort(), np.toString(), request.getQueryString(), u.getFragment());
		JSONObject result = new JSONObject();
		result.put(ProtocolConstants.KEY_LOCATION, nu);
		OrionServlet.writeJSONResponse(request, response, result, JsonURIUnqualificationStrategy.ALL_NO_GIT);
		response.setHeader(ProtocolConstants.HEADER_LOCATION, resovleOrionURI(request, nu).toString());
		return true;
	} catch (Exception e) {
		return statusHandler.handleRequest(request, response, new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
				"An error occurred when identifying a new Commit resource.", e));
	}
}
 
Example 5
Source File: CompilerBuiltinsDetector.java    From cmake4eclipse with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Get path to source file which is the input for the compiler.
 *
 * @param languageId
 *          the language ID.
 * @return full path to the source file.
 */
private String getInputFile(String languageId) {
  String specExt = builtinsDetectionBehavior.getInputFileExtension(languageId);
  if (specExt != null) {
    String specFileName = "detect_compiler_builtins" + '.' + specExt;

    final IPath builderCWD = cfgDescription.getBuildSetting().getBuilderCWD();
    IPath fileLocation = ResourcesPlugin.getWorkspace().getRoot().getFolder(builderCWD).getLocation()
        .append(specFileName);

    File specFile = new java.io.File(fileLocation.toOSString());
    if (!specFile.exists()) {
      try {
        // In the typical case it is sufficient to have an empty file.
        specFile.getParentFile().mkdirs(); // no build ran yet, must create dirs
        specFile.createNewFile();
      } catch (IOException e) {
        Plugin.getDefault().getLog().log(new Status(IStatus.ERROR, Plugin.PLUGIN_ID, "getInputFile()", e));
      }
    }

    return fileLocation.toString();
  }
  return null;
}
 
Example 6
Source File: Packager.java    From orion.server with Eclipse Public License 1.0 5 votes vote down vote up
protected void writeZip(IFileStore source, IPath path, ZipOutputStream zos) throws CoreException, IOException {

		/* load .cfignore if present */
		IFileStore cfIgnoreFile = source.getChild(CF_IGNORE_FILE);
		if (cfIgnoreFile.fetchInfo().exists()) {

			IgnoreNode node = new IgnoreNode();
			InputStream is = null;

			try {

				is = cfIgnoreFile.openInputStream(EFS.NONE, null);
				node.parse(is);

				cfIgnore.put(source.toURI(), node);

			} finally {
				if (is != null)
					is.close();
			}
		}

		IFileInfo info = source.fetchInfo(EFS.NONE, null);

		if (info.isDirectory()) {

			if (!isIgnored(source, path, true))
				for (IFileStore child : source.childStores(EFS.NONE, null))
					writeZip(child, path.append(child.getName()), zos);

		} else {

			if (!isIgnored(source, path, false)) {
				ZipEntry entry = new ZipEntry(path.toString());
				zos.putNextEntry(entry);
				IOUtilities.pipe(source.openInputStream(EFS.NONE, null), zos, true, false);
			}
		}
	}
 
Example 7
Source File: Activator.java    From erflute with Apache License 2.0 5 votes vote down vote up
/**
 * #analyzed ディレクトリ指定ダイアログを、workspace内部領域として表示する <br>
 * @param filePath デフォルトのディレクトリパス (NotNull)
 * @return ファイルパスの文字列表現 (NullAllowed: OK状態でなければ)
 */
public static String showDirectoryDialogInternal(String filePath) {
    final Shell shell = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell();
    final InternalDirectoryDialog fileDialog = new InternalDirectoryDialog(shell, filePath);
    if (fileDialog.open() == Window.OK) {
        final IPath path = fileDialog.getResourcePath();
        return path.toString();
    }
    return null;
}
 
Example 8
Source File: Index.java    From APICloud-Studio with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Index
 * 
 * @param containerURI
 * @param reuseExistingFile
 * @throws IOException
 */
protected Index(URI containerURI, boolean reuseExistingFile) throws IOException
{
	this.containerURI = containerURI;

	this.memoryIndex = new MemoryIndex();
	this.monitor = new ReentrantReadWriteLock();

	// Convert to a filename we can use for the actual index on disk
	IPath diskIndexPath = computeIndexLocation(containerURI);
	if (diskIndexPath == null)
	{
		return;
	}
	String diskIndexPathString = (diskIndexPath.getDevice() == null) ? diskIndexPath.toString() : diskIndexPath
			.toOSString();
	this.enterWrite();
	try
	{
		this.diskIndex = new DiskIndex(diskIndexPathString);
		this.diskIndex.initialize(reuseExistingFile);
	}
	finally
	{
		this.exitWrite();
	}
}
 
Example 9
Source File: BaseToCommitConverter.java    From orion.server with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public URI baseToCommitLocation(URI base, String commit, String path) throws URISyntaxException {
	IPath p = new Path(base.getPath());
	p = p.uptoSegment(1).append(Commit.RESOURCE).append(commit).addTrailingSeparator().append(p.removeFirstSegments(3));
	if (path != null)
		p = p.append(path);
	return new URI(base.getScheme(), base.getUserInfo(), base.getHost(), base.getPort(), p.toString(), getQuery(base.getQuery()), base.getFragment());
}
 
Example 10
Source File: Branch.java    From orion.server with Eclipse Public License 1.0 5 votes vote down vote up
private URI createLocation(String resource) throws URISyntaxException {
	String shortName = getName(false, true);
	IPath basePath = new Path(cloneLocation.getPath());
	IPath newPath = new Path(GitServlet.GIT_URI).append(resource).append(shortName).append(basePath.removeFirstSegments(2));
	return new URI(cloneLocation.getScheme(), cloneLocation.getUserInfo(), cloneLocation.getHost(), cloneLocation.getPort(), newPath.toString(),
			cloneLocation.getQuery(), cloneLocation.getFragment());
}
 
Example 11
Source File: GitDiffHandlerV1.java    From orion.server with Eclipse Public License 1.0 5 votes vote down vote up
private boolean identifyNewDiffResource(HttpServletRequest request, HttpServletResponse response) throws ServletException {
	try {
		StringWriter writer = new StringWriter();
		IOUtilities.pipe(request.getReader(), writer, false, false);
		JSONObject requestObject = new JSONObject(writer.toString());
		URI u = getURI(request);
		IPath p = new Path(u.getPath());
		IPath np = new Path("/"); //$NON-NLS-1$
		for (int i = 0; i < p.segmentCount(); i++) {
			String s = p.segment(i);
			if (i == 2) {
				s += ".."; //$NON-NLS-1$
				s += GitUtils.encode(requestObject.getString(GitConstants.KEY_COMMIT_NEW));
			}
			np = np.append(s);
		}
		if (p.hasTrailingSeparator())
			np = np.addTrailingSeparator();
		URI nu = new URI(u.getScheme(), u.getUserInfo(), u.getHost(), u.getPort(), np.toString(), u.getQuery(), u.getFragment());
		JSONObject result = new JSONObject();
		result.put(ProtocolConstants.KEY_LOCATION, nu.toString());
		OrionServlet.writeJSONResponse(request, response, result, JsonURIUnqualificationStrategy.ALL_NO_GIT);
		response.setHeader(ProtocolConstants.HEADER_LOCATION, resovleOrionURI(request, nu).toString());
		return true;
	} catch (Exception e) {
		return statusHandler.handleRequest(request, response, new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
				"An error occured when identifying a new Diff resource.", e));
	}
}
 
Example 12
Source File: HierarchyScope.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public HierarchyScope(IType type, WorkingCopyOwner owner) throws JavaModelException {
	this.focusType = type;
	this.owner = owner;

	this.enclosingProjectsAndJars = computeProjectsAndJars(type);

	// resource path
	IPackageFragmentRoot root = (IPackageFragmentRoot)type.getPackageFragment().getParent();
	if (root.isArchive()) {
		IPath jarPath = root.getPath();
		Object target = JavaModel.getTarget(jarPath, true);
		String zipFileName;
		if (target instanceof IFile) {
			// internal jar
			zipFileName = jarPath.toString();
		} else if (target instanceof File) {
			// external jar
			zipFileName = ((File)target).getPath();
		} else {
			return; // unknown target
		}
		this.focusPath =
			zipFileName
				+ JAR_FILE_ENTRY_SEPARATOR
				+ type.getFullyQualifiedName().replace('.', '/')
				+ SUFFIX_STRING_class;
	} else {
		this.focusPath = type.getPath().toString();
	}

	this.needsRefresh = true;

	//disabled for now as this could be expensive
	//JavaModelManager.getJavaModelManager().rememberScope(this);
}
 
Example 13
Source File: ProjectStateChangeListener.java    From n4js with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Returns whether a modification at the given path is a source container modification.
 */
public static boolean isSourceContainerModification(IN4JSCore n4jsCore, IPath changedPath) {
	final String fullPathStr = changedPath.toString();
	final URI folderUri = URI.createPlatformResourceURI(fullPathStr, true);
	final IN4JSProject project = n4jsCore.findProject(folderUri).orNull();
	if (null != project && project.exists()) {
		return from(project.getSourceContainers())
				.transform(container -> container.getLocation())
				.filter(PlatformResourceURI.class)
				.transform(uri -> uri.getAbsolutePath())
				.firstMatch(path -> path.equals(fullPathStr))
				.isPresent();
	}
	return false;
}
 
Example 14
Source File: EclipseResourceTypeDetector.java    From sarl with Apache License 2.0 5 votes vote down vote up
/** Replies the given resource is a test resource according to the Java or Maven standard.
 *
 * @param resource the resource to test.
 * @return {@link Boolean#TRUE} if the resource is a test resource. {@link Boolean#FALSE}
 *     if the resource is not a test resource. {@code null} if the detector cannot determine
 *     the type of the resource.
 */
@SuppressWarnings("checkstyle:nestedifdepth")
protected static Boolean isJavaOrMavenTestResource(Resource resource) {
	final URI uri = resource.getURI();
	if (uri.isPlatformResource()) {
		final String platformString = uri.toPlatformString(true);
		final IResource iresource = ResourcesPlugin.getWorkspace().getRoot().findMember(platformString);
		if (iresource != null) {
			final IProject project = iresource.getProject();
			final IJavaProject javaProject = JavaCore.create(project);
			try {
				final IPackageFragment packageFragment = javaProject.findPackageFragment(iresource.getParent().getFullPath());
				final IPackageFragmentRoot root = (IPackageFragmentRoot) packageFragment.getAncestor(IJavaElement.PACKAGE_FRAGMENT_ROOT);
				if (root != null) {
					final IPath rootPath = root.getPath();
					String name = null;
					if (root.isExternal()) {
						name = rootPath.toOSString();
					} else if (javaProject.getElementName().equals(rootPath.segment(0))) {
					    if (rootPath.segmentCount() != 1) {
							name = rootPath.removeFirstSegments(1).makeRelative().toString();
					    }
					} else {
						name = rootPath.toString();
					}
					if (name != null && name.startsWith(SARLConfig.FOLDER_MAVEN_TEST_PREFIX)) {
						return Boolean.TRUE;
					}
				}
			} catch (JavaModelException e) {
				//
			}
		}
	}
	return null;
}
 
Example 15
Source File: ParseManifestJSONCommand.java    From orion.server with Eclipse Public License 1.0 5 votes vote down vote up
private ServerStatus canAccess(IPath contentPath) throws CoreException {
	String accessLocation = "/file/" + contentPath.toString(); //$NON-NLS-1$
	if (contentPath.segmentCount() < 1)
		return new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_FORBIDDEN, "Forbidden access to application contents", null);

	if (!AuthorizationService.checkRights(userId, accessLocation, "GET")) //$NON-NLS-1$
		return new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_FORBIDDEN, "Forbidden access to application contents", null);
	else
		return new ServerStatus(Status.OK_STATUS, HttpServletResponse.SC_OK);
}
 
Example 16
Source File: Activator.java    From ermaster-b with Apache License 2.0 5 votes vote down vote up
public static String showSaveDialogInternal(String filePath,
		String[] filterExtensions) {

	InternalFileDialog fileDialog = new InternalFileDialog(PlatformUI.getWorkbench()
			.getActiveWorkbenchWindow().getShell(), filePath, filterExtensions[0].substring(1));
	if (fileDialog.open() == Window.OK) {
		IPath path = fileDialog.getResourcePath();
		return path.toString();
	}
	return null;
}
 
Example 17
Source File: WebAppLaunchShortcutStrategy.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 4 votes vote down vote up
@Override
public String generateUrl(IResource selection, boolean isExternal)
    throws CoreException {
  IProject project = selection.getProject();
  WebAppUtilities.verifyIsWebApp(project);

  IFolder warFolder = WebAppUtilities.getWarSrc(project);
  if (warFolder == null) {
    throw new CoreException(new Status(IStatus.ERROR, GWTPlugin.PLUGIN_ID,
        "Couldn't find WAR folder."));
  }

  if (isExternal) {
    return getUrlFromUser(selection, isExternal);
  }

  if (ResourceUtils.hasJspOrHtmlExtension(selection)) {
    int warSegments = warFolder.getFullPath().segmentCount();
    IPath pathRelativeToWar = selection.getFullPath().removeFirstSegments(
        warSegments);

    return pathRelativeToWar.toString();
  }

  List<IResource> candidates = new ArrayList<IResource>();

  for (IResource member : warFolder.members()) {
    if (ResourceUtils.hasJspOrHtmlExtension(member)) {
      candidates.add(member);
    }
  }

  if (candidates.isEmpty()) {
    // NOTE: This can happen for a gae-only project that only has a servlet.
    return "";
  } else if (candidates.size() == 1) {
    return candidates.get(0).getName();
  } else {
    return getUrlFromUser(selection, isExternal);
  }
}
 
Example 18
Source File: ClasspathVariableResolver.java    From eclipse-cs with GNU Lesser General Public License v2.1 4 votes vote down vote up
@Override
public String resolve(String aName) {

  IPath var = JavaCore.getClasspathVariable(aName);
  return var != null ? var.toString() : null;
}
 
Example 19
Source File: JDClassFileEditor.java    From jd-eclipse with GNU General Public License v3.0 4 votes vote down vote up
@SuppressWarnings("rawtypes")
protected void setupSourceMapper(IClassFile classFile) {
	try {
		// Search package fragment root and classPath
		IJavaElement packageFragment = classFile.getParent();
		IJavaElement packageFragmentRoot = packageFragment.getParent();

		if (packageFragmentRoot instanceof PackageFragmentRoot) {
			// Setup a new source mapper.
			PackageFragmentRoot root = (PackageFragmentRoot)packageFragmentRoot;				
				
			// Location of the archive file containing classes.
			IPath basePath = root.getPath();
			File baseFile = basePath.makeAbsolute().toFile();	
			
			if (!baseFile.exists()) {
				IResource resource = root.getCorrespondingResource();
				basePath = resource.getLocation();
				baseFile = basePath.makeAbsolute().toFile();
			}
			
			// Class path
			String classPath = classFile.getElementName();
			String packageName = packageFragment.getElementName();
			if ((packageName != null) && (packageName.length() > 0)) {
				classPath = packageName.replace('.', '/') + '/' + classPath;
			}
			
			// Location of the archive file containing source.
			IPath sourcePath = root.getSourceAttachmentPath();
			if (sourcePath == null) {
				sourcePath = basePath;
			}
			
			// Location of the package fragment root within the zip 
			// (empty specifies the default root).
			IPath sourceAttachmentRootPath = root.getSourceAttachmentRootPath();
			String sourceRootPath;
			
			if (sourceAttachmentRootPath == null) {
				sourceRootPath = null;
			} else {
				sourceRootPath = sourceAttachmentRootPath.toString();
				if ((sourceRootPath != null) && (sourceRootPath.length() == 0))
					sourceRootPath = null;
			}
			
			// Options
			Map options = root.getJavaProject().getOptions(true);
			
			root.setSourceMapper(new JDSourceMapper(baseFile, sourcePath, sourceRootPath, options));				
		}		
	} catch (CoreException e) {
		JavaDecompilerPlugin.getDefault().getLog().log(new Status(
			Status.ERROR, JavaDecompilerPlugin.PLUGIN_ID, 
			0, e.getMessage(), e));
	}
}
 
Example 20
Source File: XmlUtils.java    From tracecompass with Eclipse Public License 2.0 2 votes vote down vote up
/**
 * Create an XML file string from a base file name.
 *
 * @param baseName
 *            the base name of the file (without an extension)
 * @return the base name with the XML extension
 */
public static String createXmlFileString(String baseName) {
    IPath path = new Path(baseName).addFileExtension(XmlUtils.XML_EXTENSION);
    return path.toString();
}