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

The following examples show how to use org.eclipse.core.runtime.IPath#append() . 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: DiagramFileStore.java    From bonita-studio with GNU General Public License v2.0 6 votes vote down vote up
@Override
public IStatus build(IPath buildPath, IProgressMonitor monitor) {
    IPath processFolderPath = buildPath.append("process");
    IFolder processFolder = getRepository().getProject()
            .getFolder(processFolderPath.makeRelativeTo(getRepository().getProject().getLocation()));
    if (!processFolder.exists()) {
        try {
            processFolder.create(true, true, new NullProgressMonitor());
        } catch (CoreException e) {
           return e.getStatus();
        }
    }

    Map<String, Object> parameters = new HashMap<>();
    parameters.put("fileName", getName());
    parameters.put("destinationPath", processFolder.getLocation().toOSString());
    parameters.put("process", null);
    monitor.subTask(String.format(Messages.buildingDiagram, getDisplayName()));
    IStatus buildStatus = (IStatus) executeCommand(BUILD_DIAGRAM_COMMAND, parameters);
    if (Objects.equals(buildStatus.getSeverity(), IStatus.ERROR)) {
       return parseStatus(buildStatus);
    }
    return ValidationStatus.ok();
}
 
Example 2
Source File: ProcessVersion.java    From bonita-studio with GNU General Public License v2.0 6 votes vote down vote up
@Override
public IStatus build(IPath buildPath, IProgressMonitor monitor) {
    IPath processFolderPath = buildPath.append("process");
    IFolder processFolder = getRepository().getProject()
            .getFolder(processFolderPath.makeRelativeTo(getRepository().getProject().getLocation()));
    if (!processFolder.exists()) {
        try {
            processFolder.create(true, true, new NullProgressMonitor());
        } catch (CoreException e) {
            return e.getStatus();
        }
    }
    Map<String, Object> parameters = new HashMap<>();
    parameters.put("fileName", getFileStore().getName());
    parameters.put("destinationPath", processFolder.getLocation().toOSString());
    parameters.put("process", ModelHelper.getEObjectID(getModel()));
    monitor.subTask(String.format(Messages.buildingProcess, getName()));
    IStatus buildStatus = (IStatus) ((DiagramFileStore)getFileStore()).executeCommand(DiagramFileStore.BUILD_DIAGRAM_COMMAND, parameters);
    if (Objects.equals(buildStatus.getSeverity(), ValidationStatus.ERROR)) {
        return parseStatus(buildStatus);
    }
    return Status.OK_STATUS;
}
 
Example 3
Source File: WorkItem.java    From spotbugs with GNU Lesser General Public License v2.1 6 votes vote down vote up
private static void addClassesForFile(IFile file, Map<IPath, IPath> outLocations, Project fbProject) {
    IPath path = file.getLocation();
    IPath srcRoot = getMatchingSourceRoot(path, outLocations);
    if (srcRoot == null) {
        return;
    }
    IPath outputRoot = outLocations.get(srcRoot);
    int firstSegments = path.matchingFirstSegments(srcRoot);
    // add relative path to the output path
    IPath out = outputRoot.append(path.removeFirstSegments(firstSegments));
    String fileName = path.removeFileExtension().lastSegment();
    String namePattern = fileName + "\\.class|" + fileName + "\\$.*\\.class";
    namePattern = addSecondaryTypesToPattern(file, fileName, namePattern);
    File directory = out.removeLastSegments(1).toFile();

    // add parent folder and regexp for file names
    Pattern classNamesPattern = Pattern.compile(namePattern);
    ResourceUtils.addFiles(fbProject, directory, classNamesPattern);
}
 
Example 4
Source File: BirtWizardUtil.java    From birt with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Check folder if exist. If not, create it.
 * 
 * @param project
 * @param webContentFolder
 * @param folderName
 */
private static void checkFolder( IProject project, String webContentFolder,
		String folderName )
{
	if ( folderName == null )
		return;

	try
	{
		File file = new File( folderName );
		if ( file != null )
		{
			if ( file.exists( ) )
				return;

			if ( file.isAbsolute( ) )
			{
				// create absolute folder
				file.mkdir( );
			}
			else
			{
				// create folder in web content folder
				final IWorkspace ws = ResourcesPlugin.getWorkspace( );
				final IPath pjPath = project.getFullPath( );

				IPath configPath = pjPath.append( webContentFolder );
				IPath path = configPath.append( folderName );
				BirtWizardUtil.mkdirs( ws.getRoot( ).getFolder( path ) );
			}
		}
	}
	catch ( Exception e )
	{
		Logger.logException( Logger.WARNING, e );
	}
}
 
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: SourceAttachmentPackageFragmentRootWalker.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
public T traverse(IFolder folder, boolean stopOnFirstResult, TraversalState state) {
	T result = null;
	try {
		IPath path = new Path("");
		List<?> parents = state.getParents();
		for (int i = 1, count = parents.size(); i < count; ++i) {
			path = path.append(((IFolder) parents.get(i)).getName());
		}
		for (IResource resource : folder.members()) {
			switch (resource.getType()) {
				case IResource.FOLDER: {
					// If something in this folder might be in the bin includes, traverse it.
					//
					if (isBinInclude(path.append(resource.getName()).toString() + "/") != NO) {
						state.push(resource);
						result = traverse((IFolder) resource, stopOnFirstResult, state);
						state.pop();
					}
					break;
				}
				case IResource.FILE: {
					// If the file is definitely in the bin includes, handle it.
					//
					if (isBinInclude(path.append(resource.getName()).toString()) == YES) {
						result = handle((IFile) resource, state);
					}
					break;
				}
			}
			if (stopOnFirstResult && result != null) {
				break;
			}
		}
	} catch (CoreException e) {
		LOG.error(e.getMessage(), e);
	}
	return result;
}
 
Example 7
Source File: JavadocOptionsManager.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private IPath makeAbsolutePathFromRelative(IPath path) {
	if (!path.isAbsolute()) {
		if (fXmlfile == null) {
			return null;
		}
		// The XML file is always local. So ok to use getLocation here
		IPath basePath= fXmlfile.getParent().getLocation(); // relative to the ant file location
		if (basePath == null) {
			return null;
		}
		return basePath.append(path);
	}
	return path;
}
 
Example 8
Source File: NodePackageManager.java    From APICloud-Studio with GNU General Public License v3.0 5 votes vote down vote up
public IPath getBinariesPath() throws CoreException
{
	IPath prefix = getConfigPrefixPath();
	if (prefix == null)
	{
		return null;
	}

	if (PlatformUtil.isWindows())
	{
		return prefix;
	}
	return prefix.append(BIN);
}
 
Example 9
Source File: IDETypeScriptRepositoryManager.java    From typescript.java with MIT License 5 votes vote down vote up
@Override
public IPath getPath(String path, IProject project) {
	if (path.startsWith(PROJECT_LOC_TOKEN)) {
		// ${project_loc:node_modules/typescript
		String projectPath = path.substring(PROJECT_LOC_TOKEN.length(),
				path.endsWith(END_TOKEN) ? path.length() - 1 : path.length());
		IPath location = project.getLocation();
		return location != null ? location.append(projectPath) : null;
	} else if (path.startsWith(WORKSPACE_LOC_TOKEN)) {
		String wsPath = path.substring(WORKSPACE_LOC_TOKEN.length(),
				path.endsWith(END_TOKEN) ? path.length() - 1 : path.length());
		return ResourcesPlugin.getWorkspace().getRoot().getLocation().append(wsPath);
	}
	return null;
}
 
Example 10
Source File: BaseValidationTest.java    From codewind-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void test06_runQuickFix() throws Exception {
	IProject project = ResourcesPlugin.getWorkspace().getRoot().getProject(projectName);
	runQuickFix(project);
	// Validation should get run again automatically when the quick fix is complete and
	// this should clear the marker
	waitForMarkersCleared(project);
	// Check that the dockerfile is there
	IPath path = project.getLocation();
	path = path.append(srcPath);
	assertTrue("The dockerfile should be regenerated", path.toFile().exists());
}
 
Example 11
Source File: ResourceContainer.java    From depan with Apache License 2.0 5 votes vote down vote up
/**
 * Convert the {@link ResourceContainer} into an Eclipse Project relative
 * folder path.
 * 
 * As a static method, it's much harder to inadvertently alter the state
 * of the instance.
 */
public static IPath getPath(ResourceContainer container) {
  IPath result = Path.fromOSString(container.getLabel());
  ResourceContainer pathRsrc = container.getParent();
  while (null != pathRsrc) {
    IPath front = Path.fromOSString(pathRsrc.getLabel());
    pathRsrc = pathRsrc.getParent();
    result = front.append(result);
  }

  return result;
}
 
Example 12
Source File: NodeValidationTest.java    From codewind-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public void doSetup() throws Exception {
	super.doSetup();
	IPath path = project.getLocation();
   	path = path.append(srcPath);
	TestUtil.updateFile(path.toOSString(), "// Add your code here", "app.get('/hello', (req, res) => res.send('Hello World!'));");
	build(app);
	// For Java builds the states can go by quickly so don't do an assert on this
	CodewindUtil.waitForAppState(app, AppStatus.STOPPED, 120, 1);
	assertTrue("App should be in started state", CodewindUtil.waitForAppState(app, AppStatus.STARTED, 300, 1));
}
 
Example 13
Source File: BaseAutoBuildTest.java    From codewind-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void test07_modifyFile() throws Exception {
	IPath path = project.getLocation();
	path = path.append(srcPath);
	TestUtil.updateFile(path.toOSString(), text2, text3);
	refreshProject(project);
	// Check that build is started automatically
	CodewindUtil.waitForBuildState(app, BuildStatus.IN_PROGRESS, 30, 1);
	assertTrue("Build should be successful", CodewindUtil.waitForBuildState(app, BuildStatus.SUCCESS, 300, 1));
	assertTrue("App should be in started state", CodewindUtil.waitForAppState(app, AppStatus.STARTED, 120, 1));
	// Check for the new text
	pingApp(app, relativeURL, text3);
}
 
Example 14
Source File: EditFilterAction.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private IPath getOutputLocation(IJavaProject javaProject) {
	try {
		return javaProject.getOutputLocation();
	} catch (CoreException e) {
		IProject project= javaProject.getProject();
		IPath projPath= project.getFullPath();
		return projPath.append(PreferenceConstants.getPreferenceStore().getString(PreferenceConstants.SRCBIN_BINNAME));
	}
}
 
Example 15
Source File: CoreUtil.java    From codewind-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
public static IPath getCodewindDataPath() {
	if (isWindows()) {
		return new Path("C:/codewind-data");
	}
	IPath userHome = getUserHome();
	if (userHome != null) {
		return userHome.append("codewind-data");
	}
	return null;
}
 
Example 16
Source File: AddSourceFolderWizardPage.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
private static StatusInfo validatePathName(String str, IContainer parent) {
	StatusInfo result= new StatusInfo();
	result.setOK();

	IPath parentPath= parent.getFullPath();

	if (str.length() == 0) {
		result.setError(Messages.format(NewWizardMessages.NewSourceFolderWizardPage_error_EnterRootName, BasicElementLabels.getPathLabel(parentPath, false)));
		return result;
	}

	IPath path= parentPath.append(str);

	IWorkspaceRoot workspaceRoot= ResourcesPlugin.getWorkspace().getRoot();
	IStatus validate= workspaceRoot.getWorkspace().validatePath(path.toString(), IResource.FOLDER);
	if (validate.matches(IStatus.ERROR)) {
		result.setError(Messages.format(NewWizardMessages.NewSourceFolderWizardPage_error_InvalidRootName, validate.getMessage()));
		return result;
	}

	IResource res= workspaceRoot.findMember(path);
	if (res != null) {
		if (res.getType() != IResource.FOLDER) {
			result.setError(NewWizardMessages.NewSourceFolderWizardPage_error_NotAFolder);
			return result;
		}
	} else {

		URI parentLocation= parent.getLocationURI();
		if (parentLocation != null) {
			try {
				IFileStore store= EFS.getStore(parentLocation).getChild(str);
				if (store.fetchInfo().exists()) {
					result.setError(NewWizardMessages.NewSourceFolderWizardPage_error_AlreadyExistingDifferentCase);
					return result;
				}
			} catch (CoreException e) {
				// we couldn't create the file store. Ignore the exception
				// since we can't check if the file exist. Pretend that it
				// doesn't.
			}
		}
	}

	return result;
}
 
Example 17
Source File: ProjectImportedHasAstManagerTestWorkbench.java    From Pydev with Eclipse Public License 1.0 4 votes vote down vote up
public void testEditWithNoNature() throws Exception {
    NullProgressMonitor monitor = new NullProgressMonitor();

    IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
    IPath workspaceLoc = root.getRawLocation();
    IProject project = root.getProject("pydev_nature_pre_configured");
    if (project.exists()) {
        project.delete(true, monitor);
    }

    //let's create its structure
    IPath projectLoc = workspaceLoc.append("pydev_nature_pre_configured");
    projectLoc.toFile().mkdir();

    writeProjectFile(projectLoc.append(".project"));

    writePydevProjectFile(projectLoc.append(".pydevproject"));
    File srcLocFile = projectLoc.append("src").toFile();
    srcLocFile.mkdir();

    assertTrue(!project.exists());
    project.create(monitor);
    project.open(monitor);
    project.refreshLocal(IResource.DEPTH_INFINITE, monitor);
    IJobManager jobManager = Job.getJobManager();
    jobManager.resume();
    final PythonNature nature = (PythonNature) PythonNature.addNature(project, null, null, null, null, null, null);
    assertTrue(nature != null);

    //Let's give it some time to run the jobs that restore the nature
    goToIdleLoopUntilCondition(new ICallback<Boolean, Object>() {

        @Override
        public Boolean call(Object arg) {
            if (nature != null) {
                if (nature.getAstManager() != null) {
                    return true;
                }
            }
            return false;
        }
    });

    assertTrue(nature.getAstManager() != null);
    PythonPathHelper pythonPathHelper = (PythonPathHelper) nature.getAstManager().getModulesManager()
            .getPythonPathHelper();
    List<String> lst = new ArrayList<String>();
    lst.add(FileUtils.getFileAbsolutePath(srcLocFile));
    assertEquals(lst, pythonPathHelper.getPythonpath());

}
 
Example 18
Source File: WizardFolderImportPage.java    From APICloud-Studio with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Input validation.
 */
protected boolean validate()
{
	if (directoryPathField.getText().trim().length() == 0)
	{
		setErrorMessage(EplMessages.WizardFolderImportPage_ERR_NoFolderSelected);
		return false;
	}
	else if (!new File(directoryPathField.getText()).exists())
	{
		setErrorMessage(EplMessages.WizardFolderImportPage_ERR_FolderNotExist);
		return false;
	}
	else
	{
		String name = projectNameField.getText().trim();
		if (name.length() == 0)
		{
			setErrorMessage(EplMessages.WizardFolderImportPage_ERR_NoProjectName);
			return false;
		}
		if (projectsNames.contains(name))
		{
			setErrorMessage(EplMessages.WizardFolderImportPage_ERR_ProjectNameExists);
			return false;
		}

		IPath path = Path.fromOSString(directoryPathField.getText());
		setPrimaryNatureFromContributions(path);

		// Set a warning message if the imported project already contain certain project natures.
		IPath dotProjectPath = path.append(IProjectDescription.DESCRIPTION_FILE_NAME);

		IProjectDescription description = null;
		if (dotProjectPath.toFile().exists())
		{
			try
			{
				description = IDEWorkbenchPlugin.getPluginWorkspace().loadProjectDescription(dotProjectPath);
				if (description != null && description.getNatureIds().length > 0)
				{
					String delimiter = StringUtil.EMPTY;
					StringBuilder natures = new StringBuilder();
					for (String natureId : description.getNatureIds())
					{
						String nature = fLabelProvider.getText(natureId);
						if (StringUtil.isEmpty(nature))
						{
							nature = natureId;
						}
						natures.append(delimiter).append(nature);
						delimiter = ", "; //$NON-NLS-1$
					}
					String[] natureIds = description.getNatureIds();
					if (natureIds.length > 0 && !natureIds[0].equals(fPrimaryNature))
					{
						String[] oldNatures = natureIds;
						natureIds = new String[description.getNatureIds().length + 1];
						System.arraycopy(oldNatures, 0, natureIds, 1, oldNatures.length);
						natureIds[0] = fPrimaryNature;
					}
					// set the natures checked in the nature table as they are the most relevant ones.
					fTableViewer.setCheckedElements(natureIds);
					setMessage(EplMessages.WizardFolderImportPage_override_project_nature + natures.toString(),
							WARNING);
					setErrorMessage(null);
					return true;
				}
			}
			catch (CoreException e)
			{
				IdeLog.logWarning(UIEplPlugin.getDefault(), "Error reading project description for " + name, e); //$NON-NLS-1$
			}
		}
	}
	setMessage(null);
	setErrorMessage(null);
	return true;
}
 
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: InternalConfigurationType.java    From eclipse-cs with GNU Lesser General Public License v2.1 3 votes vote down vote up
/**
 * Resolves the location inside the plugins workspace state location.
 *
 * @param location
 *          the location
 * @return the resolved location in the workspace
 */
public static String resolveLocationInWorkspace(String location) {

  IPath configPath = CheckstylePlugin.getDefault().getStateLocation();
  configPath = configPath.append(location);
  return configPath.toString();
}