Java Code Examples for org.eclipse.core.runtime.IPath

The following are top voted examples for showing how to use org.eclipse.core.runtime.IPath. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: Open_Source_ECOA_Toolset_AS5   File: GenerationUtils.java   View source code 6 votes vote down vote up
public static boolean validate(String container) {
	if (container != null) {
		String[] names = StringUtils.split(container, "/");
		IResource resource = wsRoot.findMember(new Path("/" + names[0]));
		IPath loc = resource.getLocation();
		File prjLoc = new File(loc.toString());
		File[] res = prjLoc.listFiles();
		HashMap<String, ArrayList<File>> fileGroups = new HashMap<String, ArrayList<File>>();
		HashMap<String, Integer> groupCnt = new HashMap<String, Integer>();
		for (File file : res) {
			String extension = FilenameUtils.getExtension(file.getName());
			ArrayList<File> list = fileGroups.get(extension);
			int cnt = (groupCnt.get(extension) == null) ? 0 : groupCnt.get(extension).intValue();
			if (list == null)
				list = new ArrayList<File>();
			list.add(file);
			cnt++;
			groupCnt.put(extension, new Integer(cnt));
			fileGroups.put(extension, list);
		}
		return !validate(groupCnt);
	}
	return false;
}
 
Example 2
Project: bdf2   File: WizardNewFileCreationPage.java   View source code 6 votes vote down vote up
/**
 * Checks whether the linked resource target is valid. Sets the error
 * message accordingly and returns the status.
 * 
 * @return IStatus validation result from the CreateLinkedResourceGroup
 */
protected IStatus validateLinkedResource() {
	IPath containerPath = resourceGroup.getContainerFullPath();
	IPath newFilePath = containerPath.append(resourceGroup.getResource());
	IFile newFileHandle = createFileHandle(newFilePath);
	IStatus status = linkedResourceGroup
			.validateLinkLocation(newFileHandle);

	if (status.getSeverity() == IStatus.ERROR) {
		if (firstLinkCheck) {
			setMessage(status.getMessage());
			setErrorMessage(null);
		} else {
			setErrorMessage(status.getMessage());
		}
	} else if (status.getSeverity() == IStatus.WARNING) {
		setMessage(status.getMessage(), WARNING);
		setErrorMessage(null);
	}
	return status;
}
 
Example 3
Project: Hydrograph   File: ConverterUiHelper.java   View source code 6 votes vote down vote up
/**
**
 * This methods loads schema from external schema file
 * 
 * @param externalSchemaFilePath
 * @param schemaType
 * @return
 */
public List<GridRow> loadSchemaFromExternalFile(String externalSchemaFilePath,String schemaType) {
	IPath filePath=new Path(externalSchemaFilePath);
	IPath copyOfFilePath=filePath;
	if (!filePath.isAbsolute()) {
		filePath = ResourcesPlugin.getWorkspace().getRoot().getFile(filePath).getRawLocation();
	}
	if(filePath!=null && filePath.toFile().exists()){
	GridRowLoader gridRowLoader=new GridRowLoader(schemaType, filePath.toFile());
	return gridRowLoader.importGridRowsFromXML();
	
	}else{
		MessageBox messageBox=new MessageBox(Display.getCurrent().getActiveShell(), SWT.ICON_ERROR);
		messageBox.setMessage(Messages.FAILED_TO_IMPORT_SCHEMA_FILE+"\n"+copyOfFilePath.toString());
		messageBox.setText(Messages.ERROR);
		messageBox.open();
	}
	return null;
}
 
Example 4
Project: gw4e.project   File: JDTManager.java   View source code 6 votes vote down vote up
/**
 * Generate a test implementation if it does not exist
 * 
 * @param implementationFolder
 * @param implementationFragmentRoot
 * @param targetPkg
 * @param interfaceCompUnit
 * @param monitor
 * @throws CoreException
 */
public static IFile generateTestImplementation(TestResourceGeneration provider, IProgressMonitor monitor)
		throws Exception {

	IFile ifile = provider.toIFile();

	if (ifile.exists()) {
		JDTManager.rename(ifile, monitor);
		ifile.delete(true, monitor);
	}
	if (ifile.exists())
		return null;

	NewExecutionContextClassWizardPageRunner execRunner = new NewExecutionContextClassWizardPageRunner(provider,
			monitor);
	Display.getDefault().syncExec(execRunner);
	IPath path = execRunner.getType().getPath();
	IFile createdFile = (IFile) ResourceManager.getResource(path.toString());
	return createdFile;
}
 
Example 5
Project: n4js   File: ModuleSpecifierContentProposalProviderFactory.java   View source code 6 votes vote down vote up
/**
 * Creates a module specifier proposal from a given path and type
 *
 * @param path
 *            The path of the proposal
 * @param moduleType
 *            The type of the proposal
 * @return The proposal
 */
static ModuleSpecifierProposal createFromPath(IPath path, ModuleProposalType moduleType) {
	String content, label;

	if (moduleType == ModuleProposalType.FOLDER) {
		content = path.removeFileExtension().addTrailingSeparator().toString();
	} else {
		content = path.removeFileExtension().toString();
	}

	if (moduleType == ModuleProposalType.FOLDER) {
		label = path.addTrailingSeparator().toString();
	} else {
		label = path.toString();
	}

	return new ModuleSpecifierProposal(content, label, moduleType);
}
 
Example 6
Project: gw4e.project   File: JDTManager.java   View source code 6 votes vote down vote up
/**
 * @param project
 * @param itype
 * @return
 * @throws JavaModelException
 */
private static IPath findPathInGeneratedAnnotation(IProject project, IType itype) throws JavaModelException {
	ICompilationUnit cu = itype.getCompilationUnit();
	List<IAnnotationBinding> annotations = resolveAnnotation(cu, Generated.class).getAnnotations();
	if ((annotations != null) && (annotations.size() > 0)) {
		IAnnotationBinding ab = annotations.get(0);
		IMemberValuePairBinding[] attributes = ab.getAllMemberValuePairs();
		for (int i = 0; i < attributes.length; i++) {
			IMemberValuePairBinding attribut = attributes[i];
			if (attribut.getName().equalsIgnoreCase("value")) {
				Object[] o = (Object[]) attribut.getValue();
				if (o != null && o.length > 0 && String.valueOf(o[0]).trim().length() > 0) {
					try {
						IPath p = ResourceManager.find(project, String.valueOf(o[0]).trim());
						return p;
					} catch (Exception e) {
						ResourceManager.logException(e);
						return null;
					}
				}
			}
		}
	}
	return null;
}
 
Example 7
Project: n4js   File: WorkspaceWizardPage.java   View source code 6 votes vote down vote up
/**
 * Open the dialog to select a module specifier
 *
 * @param shell
 *            The Shell to open the dialog in
 */
public void openModuleSpecifierDialog(Shell shell) {
	ModuleSpecifierSelectionDialog dialog = new ModuleSpecifierSelectionDialog(shell,
			model.getProject().append(model.getSourceFolder()));

	if (!model.getModuleSpecifier().isEmpty()) {
		String initialSelectionSpecifier = model.getModuleSpecifier();

		dialog.setInitialSelection(initialSelectionSpecifier);
	}

	dialog.open();

	Object result = dialog.getFirstResult();

	if (result instanceof String) {
		IPath specifierPath = new Path((String) result);
		model.setModuleSpecifier(specifierPath.removeFileExtension().toString());
	}
}
 
Example 8
Project: gw4e.project   File: GenerationFactory.java   View source code 6 votes vote down vote up
public static TestResourceGeneration get (IFile file) throws CoreException, FileNotFoundException {
	String targetFolder = GraphWalkerContextManager.getTargetFolderForTestImplementation(file);
	IPath pkgFragmentRootPath = file.getProject().getFullPath().append(new Path(targetFolder));
	IPackageFragmentRoot implementationFragmentRoot = JDTManager.getPackageFragmentRoot(file.getProject(), pkgFragmentRootPath);
	String classname = file.getName().split("\\.")[0];
	classname = classname + PreferenceManager.suffixForTestImplementation(implementationFragmentRoot.getJavaProject().getProject().getName()) + ".java";

	ClassExtension ce = PreferenceManager.getDefaultClassExtension(file);
	IPath p = ResourceManager.getPathWithinPackageFragment(file).removeLastSegments(1);
	p = implementationFragmentRoot.getPath().append(p);
	
	ResourceContext context = new ResourceContext(p, classname, file, true, false, false, ce);
	
	TestResourceGeneration trg = new TestResourceGeneration(context);
	return trg;
}
 
Example 9
Project: n4js   File: AbstractExportToSingleFileWizardPage.java   View source code 6 votes vote down vote up
/**
 * Returns the name of a container with a location that encompasses targetDirectory. Returns null if there is no
 * conflict.
 *
 * @param targetDirectory
 *            the path of the directory to check.
 * @return the conflicting container name or <code>null</code>
 */
private String getConflictingContainerNameFor(String targetDirectory) {

	IPath rootPath = ResourcesPlugin.getWorkspace().getRoot().getLocation();
	IPath testPath = new Path(targetDirectory);
	// cannot export into workspace root
	if (testPath.equals(rootPath))
		return rootPath.lastSegment();

	// Are they the same?
	if (testPath.matchingFirstSegments(rootPath) == rootPath.segmentCount()) {
		String firstSegment = testPath.removeFirstSegments(rootPath.segmentCount()).segment(0);
		if (!Character.isLetterOrDigit(firstSegment.charAt(0)))
			return firstSegment;
	}

	return null;

}
 
Example 10
Project: Open_Source_ECOA_Toolset_AS5   File: PluginUtil.java   View source code 6 votes vote down vote up
public LogicalSystemNode getLogicalSystemDefinition(String name, String containerName) {
	LogicalSystemNode ret = null;
	if (containerName != null) {
		String[] names = StringUtils.split(containerName, "/");
		IWorkspaceRoot wsRoot = ResourcesPlugin.getWorkspace().getRoot();
		IResource resource = wsRoot.findMember(new Path("/" + names[0]));
		IPath loc = resource.getLocation();
		File file = new File(loc.toOSString() + File.separator + name + ".lsys");
		try {
			ret = ParseUtil.getLogicalSystemNodeFromText(FileUtils.readFileToString(file));
		} catch (IOException e) {
			EclipseUtil.writeStactTraceToConsole(e);
		}
	}
	return ret;
}
 
Example 11
Project: gw4e.project   File: GW4EParserImpl.java   View source code 6 votes vote down vote up
private void handleSyntaxException(IFile in) {
	ParserContextProperties props = new ParserContextProperties();
	IPath buildPoliciesPath=null;
	try {
		buildPoliciesPath = ResourceManager.getBuildPoliciesPathForGraphModel(in);
	} catch (FileNotFoundException e) {
		 ResourceManager.logException(e);
	}
	props.setProperty(PathGeneratorConfigurationException.GRAPHMODELPATH,in.getFullPath().toString());
	props.setProperty(PathGeneratorConfigurationException.BUILDPOLICIESPATH,buildPoliciesPath.toString());

	Location location = Location.NULL_LOCATION;
	 
	MarkerManager.addMarker(in, this,
			new ParserException(
					location, 
					new GraphModelSyntaxException(location, "Syntax Error in graph model", props)),
					IMarker.SEVERITY_ERROR);

	
}
 
Example 12
Project: eclipse-batch-editor   File: BatchEditor.java   View source code 6 votes vote down vote up
private boolean isMarkerChangeForThisEditor(IResourceChangeEvent event) {
	IResource resource = ResourceUtil.getResource(getEditorInput());
	if (resource == null) {
		return false;
	}
	IPath path = resource.getFullPath();
	if (path == null) {
		return false;
	}
	IResourceDelta eventDelta = event.getDelta();
	if (eventDelta == null) {
		return false;
	}
	IResourceDelta delta = eventDelta.findMember(path);
	if (delta == null) {
		return false;
	}
	boolean isMarkerChangeForThisResource = (delta.getFlags() & IResourceDelta.MARKERS) != 0;
	return isMarkerChangeForThisResource;
}
 
Example 13
Project: Hydrograph   File: JobCreationPage.java   View source code 6 votes vote down vote up
protected boolean validatePage() {
	boolean returnCode=  super.validatePage() && validateFilename();
	if(returnCode){
		IPath iPath=new Path(getContainerFullPath()+JOBS_FOLDER_NAME);
		IFolder folder=ResourcesPlugin.getWorkspace().getRoot().getFolder(iPath);
		if(!StringUtils.endsWithIgnoreCase(getFileName(), Constants.JOB_EXTENSION)){
			IFile newFile= folder.getFile(getFileName()+Constants.JOB_EXTENSION);
			if(newFile.exists()){
				setErrorMessage("'"+newFile.getName()+"'"+Constants.ALREADY_EXISTS);
				return false;
			}
		}
	}
	return returnCode;
	
}
 
Example 14
Project: gw4e.project   File: JDTManager.java   View source code 6 votes vote down vote up
/**
 * Save the AST int he Compilation Unit
 * 
 * @param testInterface
 * @param rewrite
 * @throws CoreException
 */
public static void save(CompilationUnit unit, ASTRewrite rewrite) throws CoreException {

	ITextFileBufferManager bufferManager = FileBuffers.getTextFileBufferManager();
	IPath path = unit.getJavaElement().getPath();
	try {
		bufferManager.connect(path, null);
		ITextFileBuffer textFileBuffer = bufferManager.getTextFileBuffer(path);
		IDocument document = textFileBuffer.getDocument();
		TextEdit edit = rewrite.rewriteAST(document, null);
		edit.apply(document);
		textFileBuffer.commit(null /* ProgressMonitor */, true /* Overwrite */);
	} catch (Exception e) {
		ResourceManager.logException(e);
	} finally {
		// disconnect the path
		bufferManager.disconnect(path, null);
	}
}
 
Example 15
Project: Equella   File: JarPluginModelImpl.java   View source code 6 votes vote down vote up
@Override
public List<IClasspathEntry> createClasspathEntries()
{
	IPath srcJar = null;
	if( underlyingResource.getFileExtension().equals("jar") )
	{
		String name = underlyingResource.getName();
		IFile srcJarFile = underlyingResource.getProject().getFile(
			"lib-src/" + name.substring(0, name.length() - 4) + "-sources.jar");
		if( srcJarFile.exists() )
		{
			srcJar = srcJarFile.getFullPath();
		}
	}
	return Arrays.asList(JavaCore.newLibraryEntry(underlyingResource.getFullPath(), srcJar, null));
}
 
Example 16
Project: neoscada   File: DeploymentEditor.java   View source code 6 votes vote down vote up
/**
 * This also changes the editor's input.
 * <!-- begin-user-doc -->
 * <!-- end-user-doc -->
 * @generated
 */
@Override
public void doSaveAs ()
{
    SaveAsDialog saveAsDialog = new SaveAsDialog ( getSite ().getShell () );
    saveAsDialog.open ();
    IPath path = saveAsDialog.getResult ();
    if ( path != null )
    {
        IFile file = ResourcesPlugin.getWorkspace ().getRoot ().getFile ( path );
        if ( file != null )
        {
            doSaveAs ( URI.createPlatformResourceURI ( file.getFullPath ().toString (), true ), new FileEditorInput ( file ) );
        }
    }
}
 
Example 17
Project: neoscada   File: SetupEditor.java   View source code 6 votes vote down vote up
/**
 * This also changes the editor's input.
 * <!-- begin-user-doc -->
 * <!-- end-user-doc -->
 * @generated
 */
@Override
public void doSaveAs ()
{
    SaveAsDialog saveAsDialog = new SaveAsDialog ( getSite ().getShell () );
    saveAsDialog.open ();
    IPath path = saveAsDialog.getResult ();
    if ( path != null )
    {
        IFile file = ResourcesPlugin.getWorkspace ().getRoot ().getFile ( path );
        if ( file != null )
        {
            doSaveAs ( URI.createPlatformResourceURI ( file.getFullPath ().toString (), true ), new FileEditorInput ( file ) );
        }
    }
}
 
Example 18
Project: neoscada   File: InfrastructureEditor.java   View source code 6 votes vote down vote up
/**
 * This also changes the editor's input.
 * <!-- begin-user-doc -->
 * <!-- end-user-doc -->
 * @generated
 */
@Override
public void doSaveAs ()
{
    SaveAsDialog saveAsDialog = new SaveAsDialog ( getSite ().getShell () );
    saveAsDialog.open ();
    IPath path = saveAsDialog.getResult ();
    if ( path != null )
    {
        IFile file = ResourcesPlugin.getWorkspace ().getRoot ().getFile ( path );
        if ( file != null )
        {
            doSaveAs ( URI.createPlatformResourceURI ( file.getFullPath ().toString (), true ), new FileEditorInput ( file ) );
        }
    }
}
 
Example 19
Project: neoscada   File: GlobalizeEditor.java   View source code 6 votes vote down vote up
/**
 * This also changes the editor's input.
 * <!-- begin-user-doc -->
 * <!-- end-user-doc -->
 * @generated
 */
@Override
public void doSaveAs ()
{
    SaveAsDialog saveAsDialog = new SaveAsDialog ( getSite ().getShell () );
    saveAsDialog.open ();
    IPath path = saveAsDialog.getResult ();
    if ( path != null )
    {
        IFile file = ResourcesPlugin.getWorkspace ().getRoot ().getFile ( path );
        if ( file != null )
        {
            doSaveAs ( URI.createPlatformResourceURI ( file.getFullPath ().toString (), true ), new FileEditorInput ( file ) );
        }
    }
}
 
Example 20
Project: neoscada   File: ComponentEditor.java   View source code 6 votes vote down vote up
/**
 * This also changes the editor's input.
 * <!-- begin-user-doc -->
 * <!-- end-user-doc -->
 * @generated
 */
@Override
public void doSaveAs ()
{
    SaveAsDialog saveAsDialog = new SaveAsDialog ( getSite ().getShell () );
    saveAsDialog.open ();
    IPath path = saveAsDialog.getResult ();
    if ( path != null )
    {
        IFile file = ResourcesPlugin.getWorkspace ().getRoot ().getFile ( path );
        if ( file != null )
        {
            doSaveAs ( URI.createPlatformResourceURI ( file.getFullPath ().toString (), true ), new FileEditorInput ( file ) );
        }
    }
}
 
Example 21
Project: neoscada   File: ConfigurationEditor.java   View source code 6 votes vote down vote up
/**
 * This also changes the editor's input.
 * <!-- begin-user-doc -->
 * <!-- end-user-doc -->
 * @generated
 */
@Override
public void doSaveAs ()
{
    SaveAsDialog saveAsDialog = new SaveAsDialog ( getSite ().getShell () );
    saveAsDialog.open ();
    IPath path = saveAsDialog.getResult ();
    if ( path != null )
    {
        IFile file = ResourcesPlugin.getWorkspace ().getRoot ().getFile ( path );
        if ( file != null )
        {
            doSaveAs ( URI.createPlatformResourceURI ( file.getFullPath ().toString (), true ), new FileEditorInput ( file ) );
        }
    }
}
 
Example 22
Project: gw4e.project   File: ResourceManager.java   View source code 6 votes vote down vote up
/**
 * Process recursively the containers until we found a resource with the
 * specified path
 * 
 * @param container
 * @param path
 * @return
 * @throws CoreException
 */
private static boolean resourceExistsIn(IContainer container, IPath path) throws CoreException {
	boolean found = false;
	IResource[] members = container.members();
	for (IResource member : members) {
		if (member instanceof IContainer) {

			found = resourceExistsIn((IContainer) member, path);
			if (found)
				break;
		} else if (member instanceof IFile) {
			IFile file = (IFile) member;

			if (path.equals(file.getFullPath()))
				return true;
		}
	}
	return found;
}
 
Example 23
Project: Hydrograph   File: ELTGraphicalEditor.java   View source code 6 votes vote down vote up
private IPath getParameterFileIPath(){
	if(getEditorInput() instanceof IFileEditorInput){
		IFileEditorInput input = (IFileEditorInput)getEditorInput() ;
		IFile file = input.getFile();
		IProject activeProject = file.getProject();
		String activeProjectName = activeProject.getName();

		IPath parameterFileIPath =new Path("/"+activeProjectName+"/param/"+ getPartName().replace(".job", ".properties"));
	    activeProjectName.concat("_").concat(getPartName().replace(".job", "_"));

		return parameterFileIPath;
	}else{
		return null;
	}

}
 
Example 24
Project: Hydrograph   File: CategoriesDialogSourceComposite.java   View source code 6 votes vote down vote up
private boolean isJarPresentInLibFolder(IPath path) {
	String currentProjectName = BuildExpressionEditorDataSturcture.INSTANCE.getCurrentProject().getName();
	if (StringUtils.equals(currentProjectName, path.segment(0))
			&& StringUtils.equals(PathConstant.PROJECT_LIB_FOLDER, path.segment(1)))
		return true;
	return false;
}
 
Example 25
Project: OCCI-Studio   File: PlatformEditor.java   View source code 5 votes vote down vote up
/**
 * This also changes the editor's input.
 * <!-- begin-user-doc -->
 * <!-- end-user-doc -->
 * @generated
 */
@Override
public void doSaveAs() {
	SaveAsDialog saveAsDialog = new SaveAsDialog(getSite().getShell());
	saveAsDialog.open();
	IPath path = saveAsDialog.getResult();
	if (path != null) {
		IFile file = ResourcesPlugin.getWorkspace().getRoot().getFile(path);
		if (file != null) {
			doSaveAs(URI.createPlatformResourceURI(file.getFullPath().toString(), true), new FileEditorInput(file));
		}
	}
}
 
Example 26
Project: gw4e.project   File: GeneratorChoiceComposite.java   View source code 5 votes vote down vote up
public void setTarget(IPath p, String name) {
	IFolder folder = (IFolder) ResourceManager.getResource(p.toString());
	IJavaElement element = JavaCore.create(folder);
	if (element instanceof IPackageFragmentRoot) {
		this.pkgf = ((IPackageFragmentRoot) element).getPackageFragment(IPackageFragment.DEFAULT_PACKAGE_NAME);
	} else {
		this.pkgf = (IPackageFragment) element;
	}
	String value = name.split(Pattern.quote(".")) [0];
	newClassnameText.setText(value);
	extendingClassnameText.setText(value);
}
 
Example 27
Project: n4js   File: ModuleSpecifierSelectionDialog.java   View source code 5 votes vote down vote up
/**
 * Creates all non-existing segments of the given path.
 *
 * @param path
 *            The path to create
 * @param parent
 *            The container in which the path should be created in
 * @param monitor
 *            A progress monitor. May be {@code null}
 *
 * @return The folder specified by the path
 */
private IContainer createFolderPath(IPath path, IContainer parent, IProgressMonitor monitor) {
	IContainer activeContainer = parent;

	if (null != monitor) {
		monitor.beginTask("Creating folders", path.segmentCount());
	}

	for (String segment : path.segments()) {
		IFolder folderToCreate = activeContainer.getFolder(new Path(segment));
		try {
			if (!folderToCreate.exists()) {
				createFolder(segment, activeContainer, monitor);
			}
			if (null != monitor) {
				monitor.worked(1);
			}
			activeContainer = folderToCreate;
		} catch (CoreException e) {
			LOGGER.error("Failed to create module folders.", e);
			MessageDialog.open(MessageDialog.ERROR, getShell(),
					FAILED_TO_CREATE_FOLDER_TITLE, String.format(FAILED_TO_CREATE_FOLDER_MESSAGE,
							folderToCreate.getFullPath().toString(), e.getMessage()),
					SWT.NONE);
			break;
		}
	}
	return activeContainer;
}
 
Example 28
Project: gw4e.project   File: ClasspathManager.java   View source code 5 votes vote down vote up
/**
 * Manage source folders exclusion
 * 
 * @param project
 * @param folderPath
 * @throws JavaModelException
 */
private static void handleFolderExclusion(IProject project, String folderPath) throws JavaModelException {
	IJavaProject javaProject = JavaCore.create(project);
	IClasspathEntry[] entries = javaProject.getRawClasspath();
	IClasspathEntry rootSrcEntry = null;
	IPath srcPath = javaProject.getPath().append("src");
	for (int i = 0; i < entries.length; i++) {
		if ((entries[i].getPath().equals(srcPath))) {
			rootSrcEntry = entries[i];
			break;
		}
	}

	// 'src' folder by itslef is not in the build path ...
	if (rootSrcEntry == null)
		return;

	String relative = folderPath.substring("src/".length()).concat("/");

	StringTokenizer st = new StringTokenizer(relative, "/");
	StringBuffer sb = new StringBuffer();
	while (st.hasMoreTokens()) {
		String temp = st.nextToken();
		sb.append(temp).append("/");
		rootSrcEntry = ClasspathManager.ensureExcludedPath(project, rootSrcEntry, sb.toString());
	}

}
 
Example 29
Project: Hydrograph   File: JobManager.java   View source code 5 votes vote down vote up
/**
 * Check if the file path is absolute else return workspace file path.
 *
 * @param jobFilePath the job file path
 * @return the absolute path from file
 */
public static String getAbsolutePathFromFile(IPath jobFilePath) {
	if (ResourcesPlugin.getWorkspace().getRoot().getFile(jobFilePath).exists()) {
		return ResourcesPlugin.getWorkspace().getRoot().getFile(jobFilePath).getLocation().toString();
	} else if (jobFilePath.toFile().exists()) {
		return jobFilePath.toFile().getAbsolutePath();
	}
	return "";
}
 
Example 30
Project: n4js   File: ModuleSpecifierSelectionDialog.java   View source code 5 votes vote down vote up
@Override
public String isValid(String newText) {
	IPath path = new Path(newText);
	String fileExtension = path.getFileExtension();
	String moduleName = path.removeFileExtension().lastSegment();

	if (path.removeFileExtension().segmentCount() < 1 || moduleName.isEmpty()) {
		return "The module name must not be empty.";
	}

	if (!isValidFolderName(path.removeFileExtension().toString())) {
		return "The module name is not a valid file system name.";
	}

	if (fileExtension == null) {
		return "The module name needs to have a valid N4JS file extension.";
	}
	if (!(fileExtension.equals(N4JSGlobals.N4JS_FILE_EXTENSION) ||
			fileExtension.equals(N4JSGlobals.N4JSD_FILE_EXTENSION))) {
		return "Invalid file extension.";
	}
	if (!isModuleFileSpecifier(path)) {
		return "Invalid module file specifier.";
	}
	if (path.segmentCount() > 1) {
		return IPath.SEPARATOR + " is not allowed in a module file specifier.";
	}
	if (treeViewer.getStructuredSelection().getFirstElement() == null) {
		return "Please select a module container";
	}

	return null;
}
 
Example 31
Project: OCCI-Studio   File: CrtpEditor.java   View source code 5 votes vote down vote up
/**
 * This also changes the editor's input.
 * <!-- begin-user-doc -->
 * <!-- end-user-doc -->
 * @generated
 */
@Override
public void doSaveAs() {
	SaveAsDialog saveAsDialog = new SaveAsDialog(getSite().getShell());
	saveAsDialog.open();
	IPath path = saveAsDialog.getResult();
	if (path != null) {
		IFile file = ResourcesPlugin.getWorkspace().getRoot().getFile(path);
		if (file != null) {
			doSaveAs(URI.createPlatformResourceURI(file.getFullPath().toString(), true), new FileEditorInput(file));
		}
	}
}
 
Example 32
Project: gw4e.project   File: BuildPolicyManager.java   View source code 5 votes vote down vote up
/**
 * @param buildPolicy
 * @param graphModelFile
 * @return
 */
private static IPath graphModelExists(IFile buildPolicy, String graphModelFile) throws FileNotFoundException {
	IPath path = null;
	try {
		path = buildPolicy.getFullPath().removeLastSegments(1).append(graphModelFile);
		if (ResourceManager.fileExists(buildPolicy.getProject(), path.toString()))
			return path;
	} catch (CoreException e) {
		ResourceManager.logException(e);
	}
	throw new FileNotFoundException(path.toString());
}
 
Example 33
Project: n4js   File: N4JSClassifierWizardModelValidator.java   View source code 5 votes vote down vote up
/**
 * Module specifier specifier property constraints
 */
@Override
protected void validateModuleSpecifier() throws ValidationException {

	String effectiveModuleSpecifier = getModel().getEffectiveModuleSpecifier();

	// Invoke super validation procedure on full effective module specifier
	doValidateModuleSpecifier(effectiveModuleSpecifier);

	/* Check for potential file collisions */
	if (isFileSpecifyingModuleSpecifier(effectiveModuleSpecifier)) {
		IProject moduleProject = ResourcesPlugin.getWorkspace().getRoot()
				.getProject(getModel().getProject().toString());
		IPath effectiveModulePath = new Path(getModel().getEffectiveModuleSpecifier());

		IPath n4jsdPath = getModel().getSourceFolder()
				.append(effectiveModulePath.addFileExtension(N4JSGlobals.N4JSD_FILE_EXTENSION));
		IPath n4jsPath = getModel().getSourceFolder()
				.append(effectiveModulePath.addFileExtension(N4JSGlobals.N4JS_FILE_EXTENSION));

		if (getModel().isDefinitionFile() && moduleProject.exists(n4jsPath)) {
			throw new ValidationException(
					String.format(ErrorMessages.THE_NEW_DEFINITION_MODULE_COLLIDES_WITH_THE_SOURCE_FILE,
							moduleProject.getFullPath().append(n4jsPath)));
		} else if (!getModel().isDefinitionFile() && moduleProject.exists(n4jsdPath)) {
			throw new ValidationException(String
					.format(ErrorMessages.THE_NEW_SOURCE_MODULE_COLLIDES_WITH_THE_DEFINITION_FILE,
							moduleProject.getFullPath().append(n4jsdPath)));
		}
	}

}
 
Example 34
Project: gw4e.project   File: JDTManagerTest.java   View source code 5 votes vote down vote up
@Test
public void testGetGraphModelPath() throws Exception {
	IJavaProject project = ProjectHelper.getOrCreateSimpleGW4EProject(PROJECT_NAME, true,true);
	IType type = project.findType("SimpleImpl");
	IPath path = JDTManager.getGraphModelPath(project.getProject(),type);
	assertEquals("/" + PROJECT_NAME +"/src/test/resources/Simple.json", path.toString());
}
 
Example 35
Project: gw4e.project   File: MissingPoliciesForFileMarkerResolution.java   View source code 5 votes vote down vote up
private void fix(IMarker marker, IProgressMonitor monitor) {
	try {
		IPath graphModelPath = new Path ((String)marker.getAttribute(BuildPolicyConfigurationException.GRAPHMODELPATH));
		IFile ifile = (IFile) ResourceManager.toResource(graphModelPath);
		BuildPolicyManager.addDefaultPolicies(ifile,monitor);
		marker.delete();
	} catch (Exception e) {
		ResourceManager.logException(e);
	}
}
 
Example 36
Project: gw4e.project   File: FolderSelectionGroup.java   View source code 5 votes vote down vote up
private void updateOutputResource ()  {
	if (outputField==null) return;
	try {
		IPath path = selectedContainer.getFullPath().append(new Path(resourceNameField.getText()));
		outputField.setText(path.toString() + "." + this.resourceExtension); 
	} catch (Exception e) {
		outputField.setText(""); 
	}
}
 
Example 37
Project: gw4e.project   File: GW4EStaticApiBasedTestCase.java   View source code 5 votes vote down vote up
@Test
public void testGenerateApiBasedTest () throws CoreException, IOException, InterruptedException {
	GW4EProject project = new GW4EProject(bot, gwproject);
	FileParameters fp = project.createSimpleProject ();
	fp.setTargetFilename("SimpleStatic");
	 
	List<String> ids = buildIds ("Start","e_StartApp","v_VerifyAppRunning");
	IPath p = new Path("/"+ gwproject+ "/src/main/resources/com/company/Simple.json");
	IFile file = (IFile) ResourceManager.getResource(p.toString());
	StaticGeneratorWizard.open(file, ids);
	
	StaticGeneratorWizard ges = new StaticGeneratorWizard(bot);
	ges.assertTargetElements("Start","e_StartApp","v_VerifyAppRunning");
	ges.assertSourceElements("v_VerifyPreferencePage","e_ClosePreferencePage","e_OpenPreferencesPage");
	ges.next();
	ges.assertExtensionValue(0,"com.company.SimpleImpl.java - gwproject/src/main/java"); 
	ges.next();
	ges.enterDestination("SimpleStatic", "/gwproject/src/main/java/com/company/SimpleStatic.java", "src/main/java", "com", "company");
	ges.finish();	
	
	DefaultCondition condition = new EditorOpenedCondition(bot,"SimpleStatic.java");
	bot.waitUntil(condition,RUN_TIMEOUT);
	
	String[] nodes = new String[4];
	nodes[0] =  gwproject;
	nodes[1] = "src/main/java";
	nodes[2] = "com.company";
	nodes[3] = "SimpleStatic.java";
	
	GW4ETestRunner gwtr = new  GW4ETestRunner(bot);
	String[] expected = new String[] { "Executing:v_VerifyAppRunning" };
	gwtr.runAsJavaApplication(expected,RUN_TIMEOUT,nodes);
	System.out.println("ended");
}
 
Example 38
Project: gw4e.project   File: ProjectHelper.java   View source code 5 votes vote down vote up
public static IJavaProject createProject(String name) throws CoreException {

		IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
		IProject project = root.getProject(name);
		if (!project.exists()) {
			project.create(new NullProgressMonitor());
		} else {
			project.refreshLocal(IResource.DEPTH_INFINITE, new NullProgressMonitor());
		}

		if (!project.isOpen()) {
			project.open(new NullProgressMonitor());
		}

		IFolder binFolder = project.getFolder("bin");
		if (!binFolder.exists()) {
			createFolder(binFolder, false, true, new NullProgressMonitor());
		}
		IPath outputLocation = binFolder.getFullPath();

		addNatureToProject(project, JavaCore.NATURE_ID, new NullProgressMonitor());

		IJavaProject jproject = JavaCore.create(project);
		jproject.setOutputLocation(outputLocation, new NullProgressMonitor());

		IClasspathEntry[] entries = PreferenceConstants.getDefaultJRELibrary();

		jproject.setRawClasspath(entries, new NullProgressMonitor());

		return jproject;
	}
 
Example 39
Project: time4sys   File: AnalysisEditor.java   View source code 5 votes vote down vote up
/**
 * This also changes the editor's input.
 * <!-- begin-user-doc -->
 * <!-- end-user-doc -->
 * @generated
 */
@Override
public void doSaveAs() {
	SaveAsDialog saveAsDialog = new SaveAsDialog(getSite().getShell());
	saveAsDialog.open();
	IPath path = saveAsDialog.getResult();
	if (path != null) {
		IFile file = ResourcesPlugin.getWorkspace().getRoot().getFile(path);
		if (file != null) {
			doSaveAs(URI.createPlatformResourceURI(file.getFullPath().toString(), true), new FileEditorInput(file));
		}
	}
}
 
Example 40
Project: n4js   File: AbstractExportToSingleFileWizardPage.java   View source code 5 votes vote down vote up
/**
 * Returns the name of a {@link IProject} with a location that includes targetDirectory. Returns null if there is no
 * such {@link IProject}.
 *
 * @param targetDirectory
 *            the path of the directory to check.
 * @return the overlapping project name or <code>null</code>
 */
private String getOverlappingProjectName(String targetDirectory) {
	IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
	IPath testPath = new Path(targetDirectory);
	IContainer[] containers = root.findContainersForLocationURI(testPath.makeAbsolute().toFile().toURI());
	if (containers.length > 0) {
		return containers[0].getProject().getName();
	}
	return null;
}