Java Code Examples for org.eclipse.emf.common.util.URI#createPlatformResourceURI()

The following examples show how to use org.eclipse.emf.common.util.URI#createPlatformResourceURI() . 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: DerivedResourceMarkerBasedOpenerContributor.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public boolean collectGeneratedFileOpeners(IEditorPart editor, IAcceptor<FileOpener> acceptor) {
	IStorage storage = getStorage(editor);
	if (storage != null) {
		IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
		URI uri = URI.createPlatformResourceURI(storage.getFullPath().toString(), true);
		try {
			List<IFile> resources = derivedResourceMarkers.findDerivedResources(root, uri.toString());
			for (IFile file : resources)
				acceptor.accept(createOpener(file));
			return true;
		} catch (CoreException e) {
			LOG.error(e.getMessage(), e);
		}
	}
	return false;
}
 
Example 2
Source File: SCTBuilder.java    From statecharts with Eclipse Public License 1.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
private <TYPE extends EObject> TYPE loadFromResource(IResource res) {
	URI uri = URI.createPlatformResourceURI(res.getFullPath().toString(), true);
	ResourceSet set = new ResourceSetImpl();
	Resource emfResource = null;
	try {
		emfResource = set.getResource(uri, true);
	} catch (WrappedException e) {
		Platform.getLog(BuilderActivator.getDefault().getBundle()).log(new Status(IStatus.WARNING,
				GeneratorActivator.PLUGIN_ID, "Resource " + uri + " can not be loaded by builder", e));
		return null;
	}
	if (emfResource.getErrors().size() > 0 || emfResource.getContents().size() == 0)
		return null;
	return (TYPE) emfResource.getContents().get(0);
}
 
Example 3
Source File: M2DocNewProjectWizard.java    From M2Doc with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public boolean performFinish() {
    final String projectName = newProjectPage.getProjectName();
    final String templateName = newTemplatePage.getTemplateName();
    final String variableName = variablePage.getVariableName();
    final EObject variableValue = variablePage.getVariableValue();
    final URI genconfURI = URI.createPlatformResourceURI(generationPage.getGenerationName(), true);
    final URI destinationURI = URI.createPlatformResourceURI(generationPage.getDestinationName(), true);
    final URI validationURI = URI.createPlatformResourceURI(generationPage.getValidationName(), true);
    final boolean launchGeneration = generationPage.getLaunchGeneration();

    final Job job = new FinishJob("Creating M2Doc project: " + projectName, variableValue, variableName,
            launchGeneration, projectName, templateName, genconfURI, destinationURI, validationURI);
    job.setRule(ResourcesPlugin.getWorkspace().getRoot());
    job.schedule();

    return true;
}
 
Example 4
Source File: SourceAttachmentPackageFragmentRootWalker.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Converts the physical URI to a logic URI based on the bundle symbolic name.
 */
protected URI getLogicalURI(URI uri, IStorage storage, TraversalState state) {
	if (bundleSymbolicName != null) {
		URI logicalURI = URI.createPlatformResourceURI(bundleSymbolicName, false);
		List<?> parents = state.getParents();
		for (int i = 1; i < parents.size(); i++) {
			Object obj = parents.get(i);
			if (obj instanceof IPackageFragment) {
				logicalURI = logicalURI.appendSegments(((IPackageFragment) obj).getElementName().split("\\."));
			} else if (obj instanceof IJarEntryResource) {
				logicalURI = logicalURI.appendSegment(((IJarEntryResource) obj).getName());
			} else if (obj instanceof IFolder) {
				logicalURI = logicalURI.appendSegment(((IFolder) obj).getName());
			}
		}
		return logicalURI.appendSegment(uri.lastSegment());
	}
	return uri;
}
 
Example 5
Source File: AbstractGenerationHandler.java    From M2Doc with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public Object execute(ExecutionEvent event) throws ExecutionException {
    final ISelection selection = HandlerUtil.getCurrentSelection(event);
    final Shell shell = HandlerUtil.getActiveShell(event);
    if (selection instanceof IStructuredSelection) {
        Iterator<?> it = ((IStructuredSelection) selection).iterator();
        while (it.hasNext()) {
            final Object selected = it.next();
            final Generation generation;
            if (selected instanceof IFile
                && GenconfUtils.GENCONF_EXTENSION_FILE.equals(((IFile) selected).getFileExtension())) {
                URI genconfURI = URI.createPlatformResourceURI(((IFile) selected).getFullPath().toString(), true);
                generation = getGeneration(genconfURI);
            } else if (selected instanceof Generation) {
                generation = (Generation) selected;
            } else {
                generation = null;
            }

            if (generation != null) {
                execute(event, generation);
            } else {
                MessageDialog.openError(shell, "Bad selection",
                        "Document generation action can only be triggered on Generation object or a .genconf file.");
            }
        }
    } else {
        MessageDialog.openError(shell, "Bad selection",
                "Document generation action can only be triggered on Generation object or a .genconf file.");
    }

    return null;
}
 
Example 6
Source File: PackageJSONTestHelper.java    From n4js with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Loads the given project description file (using {@link Resource}) and applies
 * {@code projectDescriptionAdjustments} to the {@link JSONObject} to be found in the root of the given
 * {@code package.json} project description file.
 *
 * After the adjustments have been applied, the resource is saved.
 */
public void updateProjectDescription(IFile projectDescriptionFile,
		Consumer<JSONObject> projectDescriptionAdjustments) throws IOException {
	final URI uri = URI.createPlatformResourceURI(projectDescriptionFile.getFullPath().toString(), true);
	final ResourceSet resourceSet = getInjector().getInstance(IResourceSetProvider.class)
			.get(projectDescriptionFile.getProject());
	final Resource resource = resourceSet.getResource(uri, true);

	final JSONObject root = PackageJSONTestUtils.getPackageJSONRoot(resource);
	projectDescriptionAdjustments.accept(root);
	resource.save(null);
}
 
Example 7
Source File: GenerateXml.java    From eip-designer with Apache License 2.0 5 votes vote down vote up
/**
 * Finds the template in the plug-in. Returns the template plug-in URI.
 * 
 * @param bundleID
 *            is the plug-in ID
 * @param relativePath
 *            is the relative path of the template in the plug-in
 * @return the template URI
 * @throws IOException
 * @generated
 */
@SuppressWarnings("unchecked")
private URI getTemplateURI(String bundleID, IPath relativePath) throws IOException {
	Bundle bundle = Platform.getBundle(bundleID);
	if (bundle == null) {
		// no need to go any further
		return URI.createPlatformResourceURI(new Path(bundleID).append(relativePath).toString(), false);
	}
	URL url = bundle.getEntry(relativePath.toString());
	if (url == null && relativePath.segmentCount() > 1) {
		Enumeration<URL> entries = bundle.findEntries("/", "*.emtl", true);
		if (entries != null) {
			String[] segmentsRelativePath = relativePath.segments();
			while (url == null && entries.hasMoreElements()) {
				URL entry = entries.nextElement();
				IPath path = new Path(entry.getPath());
				if (path.segmentCount() > relativePath.segmentCount()) {
					path = path.removeFirstSegments(path.segmentCount() - relativePath.segmentCount());
				}
				String[] segmentsPath = path.segments();
				boolean equals = segmentsPath.length == segmentsRelativePath.length;
				for (int i = 0; equals && i < segmentsPath.length; i++) {
					equals = segmentsPath[i].equals(segmentsRelativePath[i]);
				}
				if (equals) {
					url = bundle.getEntry(entry.getPath());
				}
			}
		}
	}
	URI result;
	if (url != null) {
		result = URI.createPlatformPluginURI(new Path(bundleID).append(new Path(url.getPath())).toString(), false);
	} else {
		result = URI.createPlatformResourceURI(new Path(bundleID).append(relativePath).toString(), false);
	}
	return result;
}
 
Example 8
Source File: JarEntryURIHelper.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
public static URI getUriForPackageFragmentRoot(IPackageFragmentRoot root) {
	IResource underlyingResource = root.getResource();
	if (underlyingResource == null) {
		return URI.createFileURI(root.getPath().toString());
	} else {
		return URI.createPlatformResourceURI(underlyingResource.getFullPath().toString(), true);
	}
}
 
Example 9
Source File: SimulationImageRenderer.java    From statecharts with Eclipse Public License 1.0 5 votes vote down vote up
private Resource reload(IFile file) {
	final URI uri = URI.createPlatformResourceURI(file.getFullPath().toString(), true);
	Factory factory = ResourceFactoryRegistryImpl.INSTANCE.getFactory(uri);
	Resource resource = factory.createResource(uri);
	ResourceSet resourceSet = new ResourceSetImpl();
	TransactionalEditingDomain.Factory.INSTANCE.createEditingDomain(resourceSet);
	resourceSet.getResources().add(resource);
	try {
		resource.load(Collections.EMPTY_MAP);
	} catch (IOException e) {
		throw new IllegalStateException("Error loading resource", e);
	}
	return resource;
}
 
Example 10
Source File: Storage2UriMapperImpl.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
private URI internalGetUri(/* @NonNull */ IStorage storage) {
	if (storage instanceof IFile) {
		return URI.createPlatformResourceURI(storage.getFullPath().toString(), true);
	} else if (storage instanceof FileStoreStorage) {
		return URI.createFileURI(((FileStoreStorage) storage).getFullPath().makeAbsolute().toOSString());
	}
	return contribution.getUri(storage);
}
 
Example 11
Source File: ResourceUtil.java    From statecharts with Eclipse Public License 1.0 5 votes vote down vote up
public static Resource loadResource(String filename) {
	URI uri = URI.createPlatformResourceURI(filename, true);
	Factory factory = ResourceFactoryRegistryImpl.INSTANCE.getFactory(uri);
	Resource resource = factory.createResource(uri);
	ResourceSet resourceSet = new ResourceSetImpl();
	resourceSet.getResources().add(resource);
	try {
		resource.load(Collections.EMPTY_MAP);
		return resource;
	} catch (IOException e) {
		throw new IllegalStateException("Error loading resource", e);
	}
}
 
Example 12
Source File: WorkspaceWizardModelValidator.java    From n4js with Eclipse Public License 1.0 5 votes vote down vote up
private void validateSourceFolder() throws ValidationException {
	this.setSourceFolderValid(false);

	// 1. The source folder property must not be empty
	String sourceFolder = getModel().getSourceFolder().removeTrailingSeparator().toString();

	if (sourceFolder.trim().isEmpty()) {
		throw new ValidationException(ErrorMessages.SOURCE_FOLDER_MUST_NOT_BE_EMPTY,
				WorkspaceWizardModel.SOURCE_FOLDER_PROPERTY);
	}

	// 2. All segments of the source folder path must be valid folder names
	if (!WorkspaceWizardValidatorUtils.isValidFolderPath(getModel().getSourceFolder())) {
		throw new ValidationException(
				ErrorMessages.SOURCE_FOLDER_IS_NOT_A_VALID_FOLDER_NAME,
				WorkspaceWizardModel.SOURCE_FOLDER_PROPERTY);
	}

	// 3. The source folder must be a valid {@link IN4JSSourceContainer}
	// The source container must exist, and not be of type external or library

	URI projectUri = URI.createPlatformResourceURI(getModel().getProject().segment(0), true);
	IN4JSProject project = n4jsCore.findProject(projectUri).orNull();

	if (null == project) {
		throw new ValidationException(ErrorMessages.INVALID_STATE_VALIDATION_ERROR);
	}

	if (project.getSourceContainers().stream()
			.filter(src -> (src.isSource() || src.isTest())) // Filter source type
			.filter(src -> src.getRelativeLocation().equals(sourceFolder)) // Filter name
			.count() == 0)
		throw new ValidationException(ErrorMessages.SOURCE_FOLDER_DOES_NOT_EXIST,
				WorkspaceWizardModel.SOURCE_FOLDER_PROPERTY);

	this.setSourceFolderValid(true);

}
 
Example 13
Source File: ProjectTypeAwareWorkingSetManager.java    From n4js with Eclipse Public License 1.0 4 votes vote down vote up
private URI toUri(final IProject project) {
	return URI.createPlatformResourceURI(project.getName(), true);
}
 
Example 14
Source File: GenerateAll.java    From neoscada with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Finds the template in the plug-in. Returns the template plug-in URI.
 * 
 * @param bundleID
 *            is the plug-in ID
 * @param relativePath
 *            is the relative path of the template in the plug-in
 * @return the template URI
 * @throws IOException
 * @generated
 */
@SuppressWarnings ( "unused" )
private URI getTemplateURI ( final String bundleID, final IPath relativePath ) throws IOException
{
    final Bundle bundle = Platform.getBundle ( bundleID );
    if ( bundle == null )
    {
        // no need to go any further 
        return URI.createPlatformResourceURI ( new Path ( bundleID ).append ( relativePath ).toString (), false );
    }
    URL url = bundle.getEntry ( relativePath.toString () );
    if ( url == null && relativePath.segmentCount () > 1 )
    {
        final Enumeration<URL> entries = bundle.findEntries ( "/", "*.emtl", true );
        if ( entries != null )
        {
            final String[] segmentsRelativePath = relativePath.segments ();
            while ( url == null && entries.hasMoreElements () )
            {
                final URL entry = entries.nextElement ();
                IPath path = new Path ( entry.getPath () );
                if ( path.segmentCount () > relativePath.segmentCount () )
                {
                    path = path.removeFirstSegments ( path.segmentCount () - relativePath.segmentCount () );
                }
                final String[] segmentsPath = path.segments ();
                boolean equals = segmentsPath.length == segmentsRelativePath.length;
                for ( int i = 0; equals && i < segmentsPath.length; i++ )
                {
                    equals = segmentsPath[i].equals ( segmentsRelativePath[i] );
                }
                if ( equals )
                {
                    url = bundle.getEntry ( entry.getPath () );
                }
            }
        }
    }
    URI result;
    if ( url != null )
    {
        result = URI.createPlatformPluginURI ( new Path ( bundleID ).append ( new Path ( url.getPath () ) ).toString (), false );
    }
    else
    {
        result = URI.createPlatformResourceURI ( new Path ( bundleID ).append ( relativePath ).toString (), false );
    }
    return result;
}
 
Example 15
Source File: NewStatechartProjectWizard.java    From statecharts with Eclipse Public License 1.0 4 votes vote down vote up
public URI getModelURI() {
	return URI.createPlatformResourceURI(URI.encodeFragment(getModelFilePath().toString(), true), false);
}
 
Example 16
Source File: TestDiscoveryUIUtils.java    From n4js with Eclipse Public License 1.0 4 votes vote down vote up
private static URI getFileURI(final IFileEditorInput fileEditorInput) {
	final IFile originalFileToRun = fileEditorInput.getFile();
	final String pathName = originalFileToRun.getFullPath().toString();
	return URI.createPlatformResourceURI(pathName, true);
}
 
Example 17
Source File: TraceForStorageProvider.java    From xtext-eclipse with Eclipse Public License 2.0 4 votes vote down vote up
@Override
protected AbsoluteURI getAbsoluteLocation(IFile file) {
	URI uri = URI.createPlatformResourceURI(file.getFullPath().toString(), true);
	return new AbsoluteURI(uri);
}
 
Example 18
Source File: EclipseSourceFolder.java    From xtext-eclipse with Eclipse Public License 2.0 4 votes vote down vote up
@Override
public URI getPath() {
	return URI.createPlatformResourceURI("/" + project.getName() + "/" + name + "/", true);
}
 
Example 19
Source File: DefaultUITraceURIConverterTest.java    From xtext-eclipse with Eclipse Public License 2.0 4 votes vote down vote up
private void assertConversion(String expected, IFile source) {
	AbsoluteURI sourceURI = new AbsoluteURI(URI.createPlatformResourceURI(source.getFullPath().toString(), true));
	IProjectConfig projectConfig = projectConfigProvider.createProjectConfig(project.getProject());
	SourceRelativeURI traceUri = converter.getURIForTrace(projectConfig, sourceURI);
	assertEquals(expected, traceUri.toString());
}
 
Example 20
Source File: PlatformResourceURITest.java    From n4js with Eclipse Public License 1.0 4 votes vote down vote up
@Override
protected URI createRawURI(String withoutScheme) {
	return URI.createPlatformResourceURI(withoutScheme, true);
}