org.eclipse.emf.common.util.URI Java Examples

The following examples show how to use org.eclipse.emf.common.util.URI. 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: TestCatalogSupplier.java    From n4js with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Same as {@link #get(Function)}, except that this method can be configured to not emit property "endpoint" to the
 * returned JSON string, by passing in <code>true</code> as argument for parameter
 * <code>suppressEndpointProperty</code>.
 */
public String get(Function<? super URI, ? extends ResourceSet> resourceSetAccess,
		boolean suppressEndpointProperty) {
	try {
		final TestTree testTree = getTreeForAllTests(resourceSetAccess);

		final Object testCatalogObject = suppressEndpointProperty
				? treeTransformer.apply(testTree, Collections.emptyMap())
				: treeTransformer.apply(testTree);

		return objectMapper.writeValueAsString(testCatalogObject);

	} catch (final Throwable e) {
		throw new RuntimeException("Error while assembling test catalog.", e);
	}
}
 
Example #2
Source File: PathTraverser.java    From xtext-core with Eclipse Public License 2.0 6 votes vote down vote up
protected Set<URI> traverseDir(File file, final Predicate<URI> isValidPredicate) {
	Set<URI> result = Sets.newHashSet();
	File[] files = file.listFiles();
	if (files == null)
		return result;
	for (File f : files) {
		if (f.isDirectory()) {
			result.addAll(traverseDir(f, isValidPredicate));
		} else {
			URI uri = URI.createFileURI(f.getAbsolutePath());
			if (isValidPredicate.apply(uri)) {
				result.add(uri);
			}
		}
	}
	return result;
}
 
Example #3
Source File: TxtUMLToUML2.java    From txtUML with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Exports the txtUML model to a org.eclipse.uml2.uml.Model representation
 * 
 * @param sourceProject
 *            name of the source project, where the txtUML model can be find
 * @param packageName
 *            fully qualified name of the txtUML model
 * @param outputDirectory
 *            where the result model should be saved
 * @param folder
 *            the target folder for generated model
 */
public static Model exportModel(String sourceProject, String packageName, URI outputDirectory,
		ExportMode exportMode, String folder) throws NotFoundException, JavaModelException, IOException {

	Model model = exportModel(sourceProject, packageName, exportMode, folder);

	File file = new File(model.eResource().getURI().toFileString());
	file.getParentFile().mkdirs();
	model.eResource().save(null);

	IFile createdFile = ResourcesPlugin.getWorkspace().getRoot().findFilesForLocationURI(file.toURI())[0];
	try {
		createdFile.refreshLocal(IResource.DEPTH_INFINITE, new NullProgressMonitor());
	} catch (CoreException e) {
		throw new RuntimeException(e);
	}

	return model;
}
 
Example #4
Source File: LinkingErrorTest.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
@Test public void testSemanticIssueResolution() throws Exception {
	IFile dslFile = dslFile(MODEL_WITH_LINKING_ERROR);
	XtextEditor xtextEditor = openEditor(dslFile);
	URI uriToProblem = xtextEditor.getDocument().readOnly(new IUnitOfWork<URI, XtextResource>() {
		@Override
		public URI exec(XtextResource state) throws Exception {
			Main main = (Main) state.getContents().get(0);
			Element element = main.getElements().get(1);
			return EcoreUtil.getURI(element);
		}
	});
	Issue.IssueImpl issue = new Issue.IssueImpl();
	issue.setUriToProblem(uriToProblem);
	issue.setCode(QuickfixCrossrefTestLanguageQuickfixProvider.SEMANTIC_FIX_ID);

	List<IssueResolution> resolutions = issueResolutionProvider.getResolutions(issue);
	assertEquals(1, resolutions.size());
	IssueResolution issueResolution = resolutions.get(0);
	issueResolution.apply();
	xtextEditor.doSave(null);
	List<Issue> issues = getAllValidationIssues(xtextEditor.getDocument());
	assertTrue(issues.isEmpty());
}
 
Example #5
Source File: LabelProviderFactory.java    From gama with GNU General Public License v3.0 6 votes vote down vote up
@SuppressWarnings ("unchecked")
@Override
public Object create(final Class serviceInterface, final IServiceLocator parentLocator,
		final IServiceLocator locator) {
	if (serviceProvider == null) {
		// if (dependencyInjector != null)
		// return dependencyInjector.getInstance(c);
		try {
			serviceProvider = IResourceServiceProvider.Registry.INSTANCE
					.getResourceServiceProvider(URI.createPlatformResourceURI("dummy/dummy.gaml", false));
		} catch (final Exception e) {
			DEBUG.ERR("Exception in initializing injector: " + e.getMessage());
		}
	}
	return serviceProvider.get(serviceInterface);
}
 
Example #6
Source File: AbstractXtextTests.java    From xtext-extras with Eclipse Public License 2.0 6 votes vote down vote up
public final XtextResource getResourceAndExpect(InputStream in, URI uri, int expectedErrors) throws Exception {
	XtextResource resource = doGetResource(in, uri);
	checkNodeModel(resource);
	if (expectedErrors != UNKNOWN_EXPECTATION) {
		if (expectedErrors == EXPECT_ERRORS)
			assertFalse(Joiner.on('\n').join(resource.getErrors()), resource.getErrors().isEmpty());
		else
			assertEquals(Joiner.on('\n').join(resource.getErrors()), expectedErrors, resource.getErrors().size());
	}
	for(Diagnostic d: resource.getErrors()) {
		if (d instanceof ExceptionDiagnostic)
			fail(d.getMessage());
	}
	if (expectedErrors == 0 && resource.getContents().size() > 0 && shouldTestSerializer(resource)) {
		SerializerTestHelper tester = get(SerializerTestHelper.class);
		EObject obj = resource.getContents().get(0);
		tester.assertSerializeWithNodeModel(obj);
		tester.assertSerializeWithoutNodeModel(obj);
	}
	return resource;
}
 
Example #7
Source File: ExternalContentSupportTest.java    From xtext-core with Eclipse Public License 2.0 6 votes vote down vote up
@Test public void testCreateResource_02() throws IOException {
	String grammarInstead = "grammar org.foo.bar with org.eclipse.xtext.common.Terminals\n" +
			"generate something 'http://something'\n" +
			"Model: name=ID;";
	XtextResourceSet resourceSet = get(XtextResourceSet.class);
	resourceSet.setClasspathURIContext(getClass());
	URI normalized = resourceSet.getURIConverter().normalize(URI.createURI("classpath:/org/eclipse/xtext/Xtext.xtext"));
	uriToContent.put(normalized, grammarInstead);
	support.configureResourceSet(resourceSet, this);
	Resource resource = resourceSet.createResource(normalized);
	assertNotNull(resource);
	assertFalse(resource.isLoaded());
	resource.load(Collections.emptyMap());
	assertEquals(1, resource.getContents().size());
	assertEquals("org.foo.bar", ((Grammar) resource.getContents().get(0)).getName());
}
 
Example #8
Source File: CheckPreferencesHelper.java    From dsl-devkit with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Internal operation to unmarshal a single string into a string array.
 *
 * @param marshaled
 *          as read from preferences
 * @param typeId
 *          of expected element type.
 * @return array of individual string representations of the elements.
 */
private static String[] unmarshalArray(final String marshaled, final char typeId) {
  if (marshaled == null) {
    return new String[0];
  }
  String[] values = marshaled.split(SEPARATOR);
  if (values.length == 0) {
    return values;
  }
  if (values[0] == null || values[0].length() < 1) {
    return new String[0];
  }
  // Remove the type indicator from the first element, and type check:
  if (typeId != values[0].charAt(0)) {
    throw new IllegalStateException();
  }
  for (int i = 0; i < values.length; i++) {
    values[i] = URI.decode(i == 0 ? values[i].substring(1) : values[i]);
  }
  return values;
}
 
Example #9
Source File: TemplateCustomPropertiesTests.java    From M2Doc with Eclipse Public License 1.0 6 votes vote down vote up
@Test
public void getMissingVariables() throws IOException, InvalidFormatException {
    try (XWPFDocument document = POIServices.getInstance().getXWPFDocument(URIConverter.INSTANCE,
            URI.createFileURI("resources/document/properties/missingVariables.docx"));) {
        final TemplateCustomProperties properties = new TemplateCustomProperties(document);
        final List<String> missingVariables = properties.getMissingVariables();

        assertEquals(16, missingVariables.size());
        assertEquals("linkNamelinkText", missingVariables.get(0));
        assertEquals("bookmarkName", missingVariables.get(1));
        assertEquals("queryInBookmark", missingVariables.get(2));
        assertEquals("ifCondition", missingVariables.get(3));
        assertEquals("queryInIf", missingVariables.get(4));
        assertEquals("elseIfCondition", missingVariables.get(5));
        assertEquals("queryInElseIf", missingVariables.get(6));
        assertEquals("queryInElse", missingVariables.get(7));
        assertEquals("letExpression", missingVariables.get(8));
        assertEquals("queryInLet", missingVariables.get(9));
        assertEquals("forExpression", missingVariables.get(10));
        assertEquals("queryInFor", missingVariables.get(11));
        assertEquals("queryExpression", missingVariables.get(12));
        assertEquals("aqlInSelect", missingVariables.get(13));
        assertEquals("aqlLetExpression", missingVariables.get(14));
        assertEquals("aqlLetBody", missingVariables.get(15));
    }
}
 
Example #10
Source File: MasterSelectionDialog.java    From neoscada with Eclipse Public License 1.0 6 votes vote down vote up
private MasterServer loadLastSelection ()
{
    final String lastUri = this.dialogSettings.get ( SETTINGS_LAST_SELECTION );
    if ( lastUri == null )
    {
        return null;
    }

    try
    {
        final EObject lastSelection = this.world.eResource ().getResourceSet ().getEObject ( URI.createURI ( lastUri ), true );
        if ( lastSelection instanceof MasterServer )
        {
            return (MasterServer)lastSelection;
        }
    }
    catch ( final Exception e )
    {
    }
    return null;
}
 
Example #11
Source File: ConfigurationEditor.java    From neoscada with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * This is the method called to load a resource into the editing domain's resource set based on the editor's input.
 * <!-- begin-user-doc -->
 * <!-- end-user-doc -->
 * @generated
 */
public void createModel ()
{
    URI resourceURI = EditUIUtil.getURI ( getEditorInput () );
    Exception exception = null;
    Resource resource = null;
    try
    {
        // Load the resource through the editing domain.
        //
        resource = editingDomain.getResourceSet ().getResource ( resourceURI, true );
    }
    catch ( Exception e )
    {
        exception = e;
        resource = editingDomain.getResourceSet ().getResource ( resourceURI, false );
    }

    Diagnostic diagnostic = analyzeResourceProblems ( resource, exception );
    if ( diagnostic.getSeverity () != Diagnostic.OK )
    {
        resourceToDiagnosticMap.put ( resource, analyzeResourceProblems ( resource, exception ) );
    }
    editingDomain.getResourceSet ().eAdapters ().add ( problemIndicationAdapter );
}
 
Example #12
Source File: Reader.java    From xtext-core with Eclipse Public License 2.0 6 votes vote down vote up
@Override
protected void invokeInternal(WorkflowContext ctx, ProgressMonitor monitor, Issues issues) {
	ResourceSet resourceSet = getResourceSet();
	Multimap<String, URI> uris = getPathTraverser().resolvePathes(pathes, new Predicate<URI>() {
		@Override
		public boolean apply(URI input) {
			boolean result = true;
			if (getUriFilter() != null)
				result = getUriFilter().matches(input);
			if (result)
				result = getRegistry().getResourceServiceProvider(input) != null;
			return result;
		}
	});
	IAllContainersState containersState = containersStateFactory.getContainersState(pathes, uris);
	installAsAdapter(resourceSet, containersState);
	populateResourceSet(resourceSet, uris);
	getValidator().validate(resourceSet, getRegistry(), issues);
	addModelElementsToContext(ctx, resourceSet);
}
 
Example #13
Source File: GenconfUtils.java    From M2Doc with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Gets the {@link Map} of options from the given {@link Generation}.
 * 
 * @param generation
 *            the {@link Generation}
 * @return the {@link Map} of options from the given {@link Generation}
 */
public static Map<String, String> getOptions(Generation generation) {
    final Map<String, String> res = new LinkedHashMap<String, String>();

    final Resource eResource = generation.eResource();
    if (eResource != null && eResource.getURI() != null) {
        res.put(GENCONF_URI_OPTION, eResource.getURI().toString());
    }
    if (generation.getTemplateFileName() != null) {
        res.put(M2DocUtils.TEMPLATE_URI_OPTION,
                getResolvedURI(generation, URI.createURI(generation.getTemplateFileName(), false)).toString());
    }
    if (generation.getResultFileName() != null) {
        res.put(M2DocUtils.RESULT_URI_OPTION,
                getResolvedURI(generation, URI.createURI(generation.getResultFileName(), false)).toString());
    }
    if (generation.getValidationFileName() != null) {
        res.put(M2DocUtils.VALIDATION_URI_OPTION,
                getResolvedURI(generation, URI.createURI(generation.getValidationFileName(), false)).toString());
    }
    for (Option option : generation.getOptions()) {
        res.put(option.getName(), option.getValue());
    }

    return res;
}
 
Example #14
Source File: EcoreGeneratorFragment.java    From xtext-extras with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Use {@link GenModelAccess#getGenPackage(EPackage, ResourceSet)}
 */
@Deprecated
protected List<GenPackage> loadReferencedGenModels(ResourceSet rs) {
	List<GenPackage> result = Lists.newArrayList();
	if (getReferencedGenModels() != null) {
		for (String uri : getReferencedGenModels().split(",")) {
			try {
				Resource resource = rs.getResource(URI.createURI(uri.trim()), true);
				GenModel genmodel = (GenModel) resource.getContents().get(0);
				EList<GenPackage> genPackages = genmodel.getGenPackages();
				for (GenPackage genPackage : genPackages) {
					genPackage.getEcorePackage().getEClassifiers();
					result.add(genPackage);
				}
			} catch (Exception e) {
				log.error("Couldn't find genmodel for uri '" + uri + "'");
				throw new WrappedException(e);
			}
		}
	}
	return result;
}
 
Example #15
Source File: GlobalURIEditorOpener.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
protected IEditorPart openDefaultEditor(URI uri, EReference crossReference, int indexInList, boolean select) {
	Iterator<Pair<IStorage, IProject>> storages = mapper.getStorages(uri.trimFragment()).iterator();
	if (storages != null && storages.hasNext()) {
		try {
			IStorage storage = storages.next().getFirst();
			IEditorPart editor = null;
			if (storage instanceof IFile) {
				editor = openDefaultEditor((IFile) storage);
			} else {
				editor = openDefaultEditor(storage, uri);
			}
			selectAndReveal(editor, uri, crossReference, indexInList, select);
			return editor;
		} catch (WrappedException e) {
			logger.error("Error while opening editor part for EMF URI '" + uri + "'", e.getCause());
		} catch (PartInitException partInitException) {
			logger.error("Error while opening editor part for EMF URI '" + uri + "'", partInitException);
		}
	}
	return null;
}
 
Example #16
Source File: AbapgitexternalrepoResourceFactoryImpl.java    From ADT_Frontend with MIT License 6 votes vote down vote up
/**
 * Creates an instance of the resource.
 * <!-- begin-user-doc -->
 * <!-- end-user-doc -->
 * @generated
 */
@Override
public Resource createResource(URI uri) {
	XMLResource result = new AbapgitexternalrepoResourceImpl(uri);
	result.getDefaultSaveOptions().put(XMLResource.OPTION_EXTENDED_META_DATA, Boolean.TRUE);
	result.getDefaultLoadOptions().put(XMLResource.OPTION_EXTENDED_META_DATA, Boolean.TRUE);

	result.getDefaultSaveOptions().put(XMLResource.OPTION_SCHEMA_LOCATION, Boolean.TRUE);

	result.getDefaultLoadOptions().put(XMLResource.OPTION_USE_ENCODED_ATTRIBUTE_STYLE, Boolean.TRUE);
	result.getDefaultSaveOptions().put(XMLResource.OPTION_USE_ENCODED_ATTRIBUTE_STYLE, Boolean.TRUE);

	result.getDefaultLoadOptions().put(XMLResource.OPTION_USE_LEXICAL_HANDLER, Boolean.TRUE);
	result.getDefaultLoadOptions().put(XMLResource.OPTION_RECORD_UNKNOWN_FEATURE, Boolean.TRUE);

	return result;
}
 
Example #17
Source File: N4JSModel.java    From n4js with Eclipse Public License 1.0 6 votes vote down vote up
protected Optional<? extends IN4JSSourceContainer> findN4JSSourceContainerInProject(IN4JSProject project,
		URI nestedLocation) {
	IN4JSSourceContainer matchingContainer = null;
	int matchingSegmentCount = -1;
	if (project != null) {
		for (IN4JSSourceContainer n4jsSourceContainer : project.getSourceContainers()) {
			if (isLocationInNestedInContainer(nestedLocation, n4jsSourceContainer)) {
				// support for nested source folders
				int segmentCount = n4jsSourceContainer.getLocation().toURI().segmentCount();
				if (segmentCount > matchingSegmentCount) {
					matchingContainer = n4jsSourceContainer;
					matchingSegmentCount = segmentCount;
				}
			}
		}
	}
	return Optional.fromNullable(matchingContainer);
}
 
Example #18
Source File: ValidationTestHelper.java    From xtext-core with Eclipse Public License 2.0 6 votes vote down vote up
protected StringBuilder doGetIssuesAsString(Resource resource, final Iterable<Issue> issues, StringBuilder result) {
	for (Issue issue : issues) {
		URI uri = issue.getUriToProblem();
		result.append(issue.getSeverity());
		result.append(" (");
		result.append(issue.getCode());
		result.append(") '");
		result.append(issue.getMessage());
		result.append("'");
		if (uri != null) {
			EObject eObject = resource.getResourceSet().getEObject(uri, true);
			result.append(" on ");
			result.append(eObject.eClass().getName());
		}
		result.append(", offset " + issue.getOffset() + ", length " + issue.getLength());
		result.append("\n");
	}
	return result;
}
 
Example #19
Source File: AbstractUtilTest.java    From dsl-devkit with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Prepare mocks for all tests.
 */
public static void prepareMocksBase() {
  oldDesc = mock(IResourceDescription.class);
  newDesc = mock(IResourceDescription.class);
  delta = mock(Delta.class);
  resource = mock(Resource.class);
  uriCorrect = mock(URI.class);
  when(uriCorrect.isPlatformResource()).thenReturn(true);
  when(uriCorrect.isFile()).thenReturn(true);
  when(uriCorrect.toFileString()).thenReturn(DUMMY_PATH);
  when(uriCorrect.toPlatformString(true)).thenReturn(DUMMY_PATH);
  when(delta.getNew()).thenReturn(newDesc);
  when(delta.getOld()).thenReturn(oldDesc);
  when(delta.getUri()).thenReturn(uriCorrect);
  when(resource.getURI()).thenReturn(uriCorrect);
  file = ResourcesPlugin.getWorkspace().getRoot().getFile(new Path(uriCorrect.toPlatformString(true)));
  Iterable<Pair<IStorage, IProject>> storages = singleton(Tuples.<IStorage, IProject> create(file, file.getProject()));
  mapperCorrect = mock(Storage2UriMapperImpl.class);
  when(mapperCorrect.getStorages(uriCorrect)).thenReturn(storages);
}
 
Example #20
Source File: EObjectContentProviderTest.java    From dsl-devkit with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Mocks XtextEditor and XtextElementSelectionListener to return an element selection that has:
 * - given EAttribute with a specific value (AttributeValuePair)
 * - given EStructuralFeature
 * - given EOperation.
 *
 * @param attributeValuePair
 *          EAttribute with a specific value
 * @param feature
 *          the EStructuralFeature
 * @param operation
 *          the EOperation
 * @return the EClass of the "selected" element
 */
@SuppressWarnings("unchecked")
private EClass mockSelectedElement(final AttributeValuePair attributeValuePair, final EStructuralFeature feature, final EOperation operation) {
  EClass mockSelectionEClass = mock(EClass.class);
  when(mockSelectionListener.getSelectedElementType()).thenReturn(mockSelectionEClass);
  // Mockups for returning AttributeValuePair
  URI elementUri = URI.createURI("");
  when(mockSelectionListener.getSelectedElementUri()).thenReturn(elementUri);
  XtextEditor mockEditor = mock(XtextEditor.class);
  when(mockSelectionListener.getEditor()).thenReturn(mockEditor);
  IXtextDocument mockDocument = mock(IXtextDocument.class);
  when(mockEditor.getDocument()).thenReturn(mockDocument);
  when(mockDocument.<ArrayList<AttributeValuePair>> readOnly(any(IUnitOfWork.class))).thenReturn(newArrayList(attributeValuePair));
  // Mockups for returning EOperation
  BasicEList<EOperation> mockEOperationsList = new BasicEList<EOperation>();
  mockEOperationsList.add(operation);
  when(mockSelectionEClass.getEAllOperations()).thenReturn(mockEOperationsList);
  // Mockups for returning EStructuralFeature
  BasicEList<EStructuralFeature> mockEStructuralFeatureList = new BasicEList<EStructuralFeature>();
  mockEStructuralFeatureList.add(feature);
  mockEStructuralFeatureList.add(attributeValuePair.getAttribute());
  when(mockSelectionEClass.getEAllStructuralFeatures()).thenReturn(mockEStructuralFeatureList);
  return mockSelectionEClass;
}
 
Example #21
Source File: XtendReferenceUpdater.java    From xtext-xtend with Eclipse Public License 2.0 5 votes vote down vote up
@Override
protected void createReferenceUpdate(final EObject referringElement, final URI referringResourceURI, final EReference reference, final int indexInList, final EObject newTargetElement, final IRefactoringUpdateAcceptor updateAcceptor) {
  if ((((referringElement instanceof XConstructorCall) && (referringElement.eContainer() instanceof AnonymousClass)) && (newTargetElement instanceof JvmType))) {
    return;
  }
  super.createReferenceUpdate(referringElement, referringResourceURI, reference, indexInList, newTargetElement, updateAcceptor);
}
 
Example #22
Source File: DefaultResourceUIServiceProvider.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Compute whether the given storage is interesting in the context of Xtext.
 * By default, it will delegate to {@link #canHandle(URI)} and perform a subsequent
 * check to filter storages from Java target folders.
 * @return <code>true</code> if the <code>uri / storage</code> pair should be processed.
 */
@Override
public boolean canHandle(URI uri, IStorage storage) {
	if (delegate.canHandle(uri)) {
		if (isJavaCoreAvailable()) {
			return !isJavaTargetFolder(storage);
		}
		return true;
	}
	return false;
}
 
Example #23
Source File: GamlResourceServices.java    From gama with GNU General Public License v3.0 5 votes vote down vote up
public static void updateState(final URI uri, final ModelDescription model, final boolean newState,
		final ValidationContext status) {
	// DEBUG.LOG("Beginning updating the state of editor in
	// ResourceServices for " + uri.lastSegment());
	final URI newURI = properlyEncodedURI(uri);

	final IGamlBuilderListener listener = resourceListeners.get(newURI);
	if (listener == null) { return; }
	// DEBUG.LOG("Finishing updating the state of editor for " +
	// uri.lastSegment());
	final Iterable exps = model == null ? newState ? Collections.EMPTY_SET : null
			: Iterables.filter(model.getExperiments(), each -> !each.isAbstract());
	listener.validationEnded(exps, status);
}
 
Example #24
Source File: ModelMapProvider.java    From txtUML with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * @param directory
 *            Directory of the saved mapping.
 * @param filename
 *            File name of the saved mapping (without extension).
 * @throws ModelMapException
 * @throws FileNotFoundException
 * @throws IOException
 * @throws ClassNotFoundException
 */
public ModelMapProvider(URI directory, String filename) throws ModelMapException {
	uriFragmentMapper = new URIFragmentMapper(directory, filename);

	ResourceSet resourceSet = new ResourceSetImpl();
	UMLResourcesUtil.init(resourceSet);
	URI modelURI = URI.createURI(uriFragmentMapper.getModelPath());
	if (modelURI == null) {
		throw new ModelMapException(CANNOT_LOAD_MODEL);
	}
	resource = resourceSet.getResource(modelURI, true);
	if (resource == null) {
		throw new ModelMapException(CANNOT_LOAD_MODEL);
	}
}
 
Example #25
Source File: AbstractEMFRepositoryStore.java    From bonita-studio with GNU General Public License v2.0 5 votes vote down vote up
protected Resource getTmpEMFResource(final String fileName,
        final File originalFile) throws IOException {
    final EditingDomain editingDomain = getEditingDomain();
    final File tmpFile = File.createTempFile("tmp", fileName,
            ProjectUtil.getBonitaStudioWorkFolder());
    Files.copy(originalFile, tmpFile);
    return editingDomain.getResourceSet()
            .createResource(
                    URI.createFileURI(tmpFile.getAbsolutePath()));

}
 
Example #26
Source File: URIBasedFileSystemAccess.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public void generateFile(String fileName, String outputCfgName, InputStream content) throws RuntimeIOException {
	try {
		URI uri = getURI(fileName, outputCfgName);
		try (OutputStream out = converter.createOutputStream(uri)) {
			ByteStreams.copy(beforeWrite.beforeWrite(uri, outputCfgName, content), out);
		}
	} catch (IOException t) {
		throw new RuntimeIOException(t);
	}
}
 
Example #27
Source File: PersistableResourceDescriptionsTest.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
@Test public void testMultipleAdd() throws Exception {
	addToFileSystem("bar", "namespace bar { object B }");
	addToFileSystem("foo", "namespace foo { object A references bar.B}");
	Map<URI, Delta> reload = update(uris("foo", "bar"), null); // update
	assertNull(reload.get(uri("bar")).getOld());
	assertNull(reload.get(uri("foo")).getOld());
	assertNotNull(reload.get(uri("bar")).getNew());
	assertNotNull(reload.get(uri("foo")).getNew());
}
 
Example #28
Source File: Proxies.java    From xtext-extras with Eclipse Public License 2.0 5 votes vote down vote up
protected JvmEnumerationLiteral createEnumLiteral(String literalName, BinaryTypeSignature typeName) {
	JvmEnumerationLiteral enumLiteralProxy = TypesFactory.eINSTANCE.createJvmEnumerationLiteral();
	InternalEObject internalEObject = (InternalEObject) enumLiteralProxy;
	BinarySimpleMemberSignature fieldSignature = typeName.appendField(literalName);
	URI uri = fieldSignature.getURI();
	internalEObject.eSetProxyURI(uri);
	return enumLiteralProxy;
}
 
Example #29
Source File: DirtyStateAwareResourceDescriptions2.java    From dsl-devkit with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * determine whether a given resource description contains any reference to a set of other resources identified by their URIs.
 * 
 * @param desc
 *          Resource description to test
 * @param targetResources
 *          URIs of the target resources
 * @return true, if {@code desc} links to one of the {@code targetResources}.
 */
private boolean hasReferenceTo(final IResourceDescription desc, final Set<URI> targetResources) {
  if (desc == null || targetResources.contains(desc.getURI())) {
    return false;
  }
  return !Iterables.isEmpty(Iterables.filter(desc.getReferenceDescriptions(), new Predicate<IReferenceDescription>() {
    public boolean apply(final IReferenceDescription input) {
      return targetResources.contains(input.getTargetEObjectUri().trimFragment());
    }
  }));
}
 
Example #30
Source File: WorkspaceManagerTest.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void testDoRead() {
  StringConcatenation _builder = new StringConcatenation();
  _builder.append("type Test {");
  _builder.newLine();
  _builder.append("    ");
  _builder.append("string foo");
  _builder.newLine();
  _builder.append("}");
  _builder.newLine();
  final URI path = this.operator_mappedTo("MyType1.testlang", _builder);
  this.workspaceManger.doBuild(Collections.<URI>unmodifiableList(CollectionLiterals.<URI>newArrayList(path)), CollectionLiterals.<URI>emptyList(), null);
  StringConcatenation _builder_1 = new StringConcatenation();
  _builder_1.append("type Test {");
  _builder_1.newLine();
  _builder_1.append("    ");
  _builder_1.append("Test foo");
  _builder_1.newLine();
  _builder_1.append("}");
  _builder_1.newLine();
  final String inMemContents = _builder_1.toString();
  this.workspaceManger.didOpen(path, Integer.valueOf(1), inMemContents).build(null);
  final Function2<Document, XtextResource, String> _function = (Document $0, XtextResource $1) -> {
    return $0.getContents();
  };
  Assert.assertEquals(inMemContents, this.workspaceManger.<String>doRead(path, _function));
}