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

The following examples show how to use org.eclipse.core.runtime.IPath#hasTrailingSeparator() . 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: GitUtils.java    From orion.server with Eclipse Public License 1.0 6 votes vote down vote up
public static String getRelativePath(IPath filePath, IPath pathToGitRoot) {
	StringBuilder sb = new StringBuilder();
	String file = null;
	if (!filePath.hasTrailingSeparator()) {
		file = filePath.lastSegment();
		filePath = filePath.removeLastSegments(1);
	}
	for (int i = 0; i < pathToGitRoot.segments().length; i++) {
		if (pathToGitRoot.segments()[i].equals(".."))
			sb.append(filePath.segment(filePath.segments().length - pathToGitRoot.segments().length + i)).append("/");
		// else TODO
	}
	if (file != null)
		sb.append(file);
	return sb.toString();
}
 
Example 2
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 3
Source File: TracePackageExtractManifestOperation.java    From tracecompass with Eclipse Public License 2.0 6 votes vote down vote up
private TracePackageElement[] generateElementsFromArchive() {
    ArchiveFile archiveFile = getSpecifiedArchiveFile();
    Enumeration<@NonNull ?> entries = archiveFile.entries();
    Set<String> traceFileNames = new HashSet<>();
    while (entries.hasMoreElements()) {
        ArchiveEntry entry = (ArchiveEntry) entries.nextElement();
        String entryName = entry.getName();
        IPath fullArchivePath = new Path(entryName);
        if (!fullArchivePath.hasTrailingSeparator() && fullArchivePath.segmentCount() > 0) {
            traceFileNames.add(fullArchivePath.segment(0));
        }
    }

    List<TracePackageElement> packageElements = new ArrayList<>();
    for (String traceFileName : traceFileNames) {
        TracePackageTraceElement traceElement = new TracePackageTraceElement(null, traceFileName, null);
        new TracePackageFilesElement(traceElement, traceFileName);
        packageElements.add(traceElement);
    }

    return packageElements.toArray(new TracePackageElement[] {});
}
 
Example 4
Source File: MovePackageFragmentRootOperation.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private IPath[] renamePatterns(IPath rootPath, IPath[] patterns) {
	IPath[] newPatterns = null;
	int newPatternsIndex = -1;
	for (int i = 0, length = patterns.length; i < length; i++) {
		IPath pattern = patterns[i];
		if (pattern.equals(rootPath)) {
			if (newPatterns == null) {
				newPatterns = new IPath[length];
				System.arraycopy(patterns, 0, newPatterns, 0, i);
				newPatternsIndex = i;
			}
			IPath newPattern = this.destination.removeFirstSegments(1);
			if (pattern.hasTrailingSeparator())
				newPattern = newPattern.addTrailingSeparator();
			newPatterns[newPatternsIndex++] = newPattern;
		}
	}
	return newPatterns;
}
 
Example 5
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 6
Source File: GitIndexHandlerV1.java    From orion.server with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public boolean handleRequest(HttpServletRequest request, HttpServletResponse response, String path) throws ServletException {
	Repository db = null;
	try {
		IPath p = new Path(path);
		IPath filePath = p.hasTrailingSeparator() ? p : p.removeLastSegments(1);
		if (!AuthorizationService.checkRights(request.getRemoteUser(), "/" + filePath.toString(), request.getMethod())) {
			response.sendError(HttpServletResponse.SC_FORBIDDEN);
			return true;
		}
		Set<Entry<IPath, File>> set = GitUtils.getGitDirs(filePath, Traverse.GO_UP).entrySet();
		File gitDir = set.iterator().next().getValue();
		if (gitDir == null)
			return false; // TODO: or an error response code, 405?
		db = FileRepositoryBuilder.create(gitDir);
		switch (getMethod(request)) {
		case GET:
			return handleGet(request, response, db, GitUtils.getRelativePath(p, set.iterator().next().getKey()));
		case PUT:
			return handlePut(request, response, db, GitUtils.getRelativePath(p, set.iterator().next().getKey()));
		case POST:
			return handlePost(request, response, db, p);
		default:
			// fall through and return false below
		}
	} catch (Exception e) {
		String msg = NLS.bind("Failed to process an operation on index for {0}", path); //$NON-NLS-1$
		ServerStatus status = new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, msg, e);
		LogHelper.log(status);
		return statusHandler.handleRequest(request, response, status);
	} finally {
		if (db != null)
			db.close();
	}
	return false;
}
 
Example 7
Source File: ProjectResourceControl.java    From depan with Apache License 2.0 5 votes vote down vote up
/**
 * Determine if the inputs are consistent.
 * 
 * @return error string if problems exist, or null if inputs are valid
 */
public static String validateInputs(String containerName, String fileName) {

  if (containerName.length() == 0) {
    return "File container must be specified";
  }

  IPath containerPath = PlatformTools.buildPath(containerName);
  IResource container = WorkspaceTools.buildWorkspaceResource(containerPath);
  if (container == null
      || (container.getType()
          & (IResource.PROJECT | IResource.FOLDER)) == 0) {
    return "File container must exist";
  }
  if (!container.isAccessible()) {
    return "Project must be writable";
  }
  if (fileName.length() == 0) {
    return "File name must be specified";
  }
  IPath filePath = PlatformTools.buildPath(fileName);
  if ((1 != filePath.segmentCount()) || (filePath.hasTrailingSeparator())) {
    return "File name cannot be a path";
  }
  filePath.getFileExtension();

  return null;
}
 
Example 8
Source File: ModuleSpecifierContentProposalProviderFactory.java    From n4js with Eclipse Public License 1.0 4 votes vote down vote up
@Override
public IContentProposal[] getProposals(String contents, int position) {
	IContainer proposalRootFolder;

	if (null == rootFolder) {
		return EMPTY_PROPOSAL;
	}

	if (rootFolder.isEmpty()) {
		proposalRootFolder = ResourcesPlugin.getWorkspace().getRoot();
	} else if (rootFolder.segmentCount() == 1) {
		proposalRootFolder = ResourcesPlugin.getWorkspace().getRoot().getProject(rootFolder.segment(0));
	} else {
		proposalRootFolder = findContainerForPath(rootFolder);
	}

	if (null == proposalRootFolder || !proposalRootFolder.exists()) {
		return EMPTY_PROPOSAL;
	}

	// The field content as path
	IPath contentsPath = new Path(contents);

	// The directory to look for prefix matches
	IPath workingDirectoryPath;

	// If the contents path has a trailing separator...
	if (contentsPath.hasTrailingSeparator()) {
		// Use the full content as working directory path
		workingDirectoryPath = contentsPath;
	} else {
		// Otherwise only use complete segments as working directory
		workingDirectoryPath = contentsPath.removeLastSegments(1);
	}

	IContainer workingDirectory;

	if (workingDirectoryPath.segmentCount() > 0) {
		workingDirectory = proposalRootFolder.getFolder(workingDirectoryPath);
	} else {
		workingDirectory = proposalRootFolder;
	}

	// Return an empty proposal list for non-existing working directories
	if (null == workingDirectory || !workingDirectory.exists()) {
		return EMPTY_PROPOSAL;
	}
	try {
		return Arrays.asList(workingDirectory.members()).stream()
				// Only work with files and folders
				.filter(r -> (r instanceof IFile || r instanceof IFolder))
				// Filter by prefix matching
				.filter(resource -> {
					IPath rootRelativePath = resource.getFullPath().makeRelativeTo(rootFolder);
					return rootRelativePath.toString().startsWith(contentsPath.toString());
				})
				// Transform to a ModuleSpecifierProposal
				.map(resource -> {
					// Create proposal path
					IPath proposalPath = resource.getFullPath()
							.makeRelativeTo(proposalRootFolder.getFullPath());
					// Set the proposal type
					ModuleSpecifierProposal.ModuleProposalType type = resource instanceof IFile
							? ModuleSpecifierProposal.ModuleProposalType.MODULE
							: ModuleSpecifierProposal.ModuleProposalType.FOLDER;
					// Create a new module specifier proposal
					return ModuleSpecifierProposal.createFromPath(proposalPath, type);
				})
				.toArray(IContentProposal[]::new);
	} catch (CoreException e) {
		return EMPTY_PROPOSAL;
	}

}