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

The following examples show how to use org.eclipse.emf.common.util.URI. These examples are extracted from open source projects. 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
/**
 * 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 2
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 3
/**
 * 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 4
Source Project: dsl-devkit   Source File: AbstractUtilTest.java    License: 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 5
Source Project: M2Doc   Source File: GenconfUtils.java    License: 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 6
Source Project: neoscada   Source File: MasterSelectionDialog.java    License: 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 7
Source Project: gama   Source File: LabelProviderFactory.java    License: 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 8
Source Project: txtUML   Source File: TxtUMLToUML2.java    License: 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 9
Source Project: xtext-core   Source File: PathTraverser.java    License: 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 10
Source Project: neoscada   Source File: ConfigurationEditor.java    License: 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 11
/**
 * 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 12
Source Project: n4js   Source File: TestCatalogSupplier.java    License: 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 13
Source Project: xtext-core   Source File: ValidationTestHelper.java    License: 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 14
Source Project: xtext-eclipse   Source File: LinkingErrorTest.java    License: 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 15
Source Project: xtext-core   Source File: Reader.java    License: 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 16
@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 17
@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 18
Source Project: dsl-devkit   Source File: CheckPreferencesHelper.java    License: 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 19
Source Project: n4js   Source File: N4JSModel.java    License: 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 20
Source Project: xtext-extras   Source File: AbstractXtextTests.java    License: 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 21
@Override
public XtextResource doGetResource(final InputStream in, final URI uri) throws Exception {
  XtextResourceSet rs = this.<XtextResourceSet>get(XtextResourceSet.class);
  rs.setClasspathURIContext(this.getClass());
  Resource _createResource = this.getResourceFactory().createResource(uri);
  final XtextResource resource = ((XtextResource) _createResource);
  rs.getResources().add(resource);
  XtextLinker linker = new XtextLinker() {
    @Override
    protected Xtext2EcoreTransformer createTransformer(final Grammar grammar, final IDiagnosticConsumer consumer) {
      Xtext2EcoreTransformer result = super.createTransformer(grammar, consumer);
      ErrorAcceptor _errorAcceptor = result.getErrorAcceptor();
      Xtext2EcoreTransformerTest.MyErrorAcceptor _myErrorAcceptor = new Xtext2EcoreTransformerTest.MyErrorAcceptor(_errorAcceptor, Xtext2EcoreTransformerTest.this.errorAcceptorMock);
      result.setErrorAcceptor(_myErrorAcceptor);
      return result;
    }
  };
  ILinker _linker = resource.getLinker();
  linker.setScopeProvider(((XtextLinker) _linker).getScopeProvider());
  ILinker _linker_1 = resource.getLinker();
  linker.setLinkingService(((Linker) _linker_1).getLinkingService());
  ILinker _linker_2 = resource.getLinker();
  linker.setLinkingHelper(((Linker) _linker_2).getLinkingHelper());
  XtextLinker.PackageRemover _packageRemover = new XtextLinker.PackageRemover();
  linker.setPackageRemover(_packageRemover);
  LinkingDiagnosticMessageProvider _linkingDiagnosticMessageProvider = new LinkingDiagnosticMessageProvider();
  linker.setDiagnosticMessageProvider(_linkingDiagnosticMessageProvider);
  OnChangeEvictingCache _onChangeEvictingCache = new OnChangeEvictingCache();
  linker.setCache(_onChangeEvictingCache);
  resource.setLinker(linker);
  resource.load(in, null);
  return resource;
}
 
Example 22
@Override
public void generate(Grammar grammar, XpandExecutionContext ctx) {
	RuleNames.ensureAdapterInstalled(grammar);
	super.generate(grammar, ctx);

	final ResourceSaveIndicator isSaving = new ResourceSaveIndicator();
	// create a defensive clone
	Grammar copy = deepCopy(grammar, isSaving);
	ResourceSet set = copy.eResource().getResourceSet();

	// save grammar model
	String path;
	if (xmlVersion == null) {
		path = GrammarUtil.getClasspathRelativePathToBinGrammar(copy);
	} else {
		log.warn("'xmlVersion' has been specified for this "
				+ GrammarAccessFragment.class.getSimpleName()
				+ ". Therefore, the grammar is persisted as XMI and not as binary. This can be a performance drawback.");
		path = GrammarUtil.getClasspathRelativePathToXmi(copy);
	}
	URI uri = URI.createURI(ctx.getOutput().getOutlet(Generator.SRC_GEN).getPath() + "/" + path);
	Resource resource = set.createResource(uri, ContentHandler.UNSPECIFIED_CONTENT_TYPE);
	addAllGrammarsToResource(resource, copy, new HashSet<Grammar>());
	isSaving.set(Boolean.TRUE);
	Map<String, Object> saveOptions = Maps.newHashMap();
	if (resource instanceof XMLResource) {
		((XMLResource) resource).setXMLVersion(getXmlVersion());
	} else if (resource instanceof BinaryResourceImpl){
		saveOptions.put(BinaryResourceImpl.OPTION_VERSION, BinaryResourceImpl.BinaryIO.Version.VERSION_1_1);
		saveOptions.put(BinaryResourceImpl.OPTION_STYLE_DATA_CONVERTER, Boolean.TRUE);
	}
	try {
		resource.save(saveOptions);
	} catch (IOException e) {
		log.error(e.getMessage(), e);
	} finally {
		isSaving.set(Boolean.FALSE);
	}
}
 
Example 23
public DefaultResourceDescriptionDelta(IResourceDescription old, IResourceDescription _new) {
	super();
	if (old == _new) {
		throw new AssertionError("'old!=_new' constraint violated");
	}
	if (_new != null && old != null && !old.getURI().equals(_new.getURI())) {
		URI oldURI = old.getURI();
		URI newURI = _new.getURI();
		throw new AssertionError(
				"'_new!=null && old!=null && !old.getURI().equals(_new.getURI())' constraint violated, old was "
						+ oldURI + " new was: " + newURI);
	}
	this.old = old;
	this._new = _new;
}
 
Example 24
@Override
public boolean visit(final IResourceDelta delta) throws CoreException {
  if (((!this.existsListeners.isEmpty()) && this.hasExistsChanged(delta))) {
    final Set<URI> interestedFiles = this.existsListeners.removeAll(delta.getResource().getFullPath().toString());
    boolean _isEmpty = interestedFiles.isEmpty();
    boolean _not = (!_isEmpty);
    if (_not) {
      this.queueURIs(interestedFiles);
    }
  }
  if (((!this.childrenListeners.isEmpty()) && (this.hasExistsChanged(delta) || this.hasChildrenChanged(delta)))) {
    final Set<URI> interestedFiles_1 = this.childrenListeners.removeAll(delta.getResource().getFullPath().toString());
    boolean _isEmpty_1 = interestedFiles_1.isEmpty();
    boolean _not_1 = (!_isEmpty_1);
    if (_not_1) {
      this.queueURIs(interestedFiles_1);
    }
  }
  if (((!this.charsetListeners.isEmpty()) && (this.hasExistsChanged(delta) || this.hasCharsetChanged(delta)))) {
    final Set<URI> interestedFiles_2 = this.charsetListeners.removeAll(delta.getResource().getFullPath().toString());
    boolean _isEmpty_2 = interestedFiles_2.isEmpty();
    boolean _not_2 = (!_isEmpty_2);
    if (_not_2) {
      this.queueURIs(interestedFiles_2);
    }
  }
  if (((!this.contentsListeners.isEmpty()) && (this.hasExistsChanged(delta) || this.hasContentsChanged(delta)))) {
    final Set<URI> interestedFiles_3 = this.contentsListeners.removeAll(delta.getResource().getFullPath().toString());
    boolean _isEmpty_3 = interestedFiles_3.isEmpty();
    boolean _not_3 = (!_isEmpty_3);
    if (_not_3) {
      this.queueURIs(interestedFiles_3);
    }
  }
  return true;
}
 
Example 25
protected boolean isFile(final URI uri) {
  boolean _xblockexpression = false;
  {
    final Object directory = this.getAttribute(uri, URIConverter.ATTRIBUTE_DIRECTORY);
    boolean _xifexpression = false;
    if ((directory instanceof Boolean)) {
      _xifexpression = (!((Boolean) directory).booleanValue());
    } else {
      _xifexpression = false;
    }
    _xblockexpression = _xifexpression;
  }
  return _xblockexpression;
}
 
Example 26
@Override
protected void createTextChange(ITextRegion referenceTextRegion, String newReferenceText, EObject referringElement,
		EObject newTargetElement, EReference reference, URI referringResourceURI,
		IRefactoringUpdateAcceptor updateAcceptor) {
	if (newReferenceText != null && updateAcceptor instanceof ImportAwareUpdateAcceptor && isReferenceToJvmType(newTargetElement, reference)) {
		JvmType newTargetType = (JvmType) newTargetElement;
		ImportAwareUpdateAcceptor importAwareUpdateAcceptor = (ImportAwareUpdateAcceptor) updateAcceptor;
		
		Pair<JvmDeclaredType, QualifiedName> importedTypeAndRelativeName = getImportedTypeAndRelativeName(newTargetType, importAwareUpdateAcceptor.getImportSection());
		if(importedTypeAndRelativeName != null) {
			JvmDeclaredType importedType = importedTypeAndRelativeName.getFirst();
			QualifiedName importRelativeName = importedTypeAndRelativeName.getSecond();
			
			importAwareUpdateAcceptor.removeImport(importedType, false, false, null);
			if (isReferencedByQualifiedName(referringElement, newTargetType, importRelativeName)) {
				QualifiedName newTypeQualifiedName = qualifiedNameProvider.getFullyQualifiedName(newTargetElement);
				newReferenceText = getLinkText(newTypeQualifiedName, newReferenceText);
			} else {
				if(!isEmpty(importedType.getPackageName())) { 
					importAwareUpdateAcceptor.acceptImport(importedType, false, false, null);
				}
				newReferenceText = getLinkText(importRelativeName, newReferenceText);
			}
		}
	}
	super.createTextChange(referenceTextRegion, newReferenceText, referringElement, newTargetElement, reference,
			referringResourceURI, updateAcceptor);
}
 
Example 27
@Test
public void testJarToPlatformMapping() {
	initBuilder(new TestLanguageConfiguration(false));
	testBuilder.setSourceDirs(ImmutableList.of("test-data/standalone.with.reference/model"));
	testBuilder.setClassPathEntries(ImmutableList.of("test-data/standalone.with.reference/target/classes/",
			"test-data/model.in.eclipse.project.jar"));

	assertTrue("Builder launch returned false", testBuilder.launch());
	URI uri = EcorePlugin.getPlatformResourceMap().get("model.in.eclipse.project");
	assertNotNull("No platform mapping found for 'model.in.eclipse.project'", uri);
	assertTrue("Platform mapping is archive", uri.toString().startsWith("archive:file:/"));
	assertTrue("Platform mapping points to jared project",
			uri.toString().endsWith("test-data/model.in.eclipse.project.jar!/"));
}
 
Example 28
@Deprecated
protected Map<EObject, URI> createExportedElementsMap(final Resource resource) {
	return new ForwardingMap<EObject, URI>() {

		private Map<EObject, URI> delegate;
		
		@Override
		protected Map<EObject, URI> delegate() {
			if (delegate != null) {
				return delegate;
			}
			URI uri = EcoreUtil2.getPlatformResourceOrNormalizedURI(resource);
			IResourceServiceProvider resourceServiceProvider = getServiceProviderRegistry().getResourceServiceProvider(uri);
			if (resourceServiceProvider == null) {
				return delegate = Collections.emptyMap();
			}
			IResourceDescription.Manager resourceDescriptionManager = resourceServiceProvider.getResourceDescriptionManager();
			if (resourceDescriptionManager == null) {
				return delegate = Collections.emptyMap();
			}
			IResourceDescription resourceDescription = resourceDescriptionManager.getResourceDescription(resource);
			Map<EObject, URI> exportedElementMap = newIdentityHashMap();
			if (resourceDescription != null) {
				for (IEObjectDescription exportedEObjectDescription : resourceDescription.getExportedObjects()) {
					EObject eObject = resource.getEObject(exportedEObjectDescription.getEObjectURI().fragment());
					if (eObject != null)
						exportedElementMap.put(eObject, exportedEObjectDescription.getEObjectURI());
				}
			}
			return delegate = exportedElementMap;
		}

		
	};
}
 
Example 29
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 30
private IProject projectWithName(String projectName) {
	IN4JSEclipseProject n4jsProject = eclipseN4jsCore.findProject(URI.createPlatformResourceURI(projectName, true))
			.orNull();
	if (null == n4jsProject) {
		throw new IllegalArgumentException("Could not find project with name '" + projectName + "'");
	}
	return n4jsProject.getProject();
}