Пример #1
0
 protected Item copyFromResource(Resource createResource, String newItemLabel)
     throws PersistenceException, BusinessException {
   if (newItemLabel != null) {
     Item newItem =
         (Item)
             EcoreUtil.getObjectByType(
                 createResource.getContents(), PropertiesPackage.eINSTANCE.getItem());
     Property property = newItem.getProperty();
     property.setId(getNextId());
     property.setAuthor(getRepositoryContext().getUser());
     property.setLabel(newItemLabel);
     property.setDisplayName(newItemLabel);
     // BUG TDI-25050:If here throw exception,it will block the copy action
     // if (!isNameAvailable(getRepositoryContext().getProject(), property.getItem(), null)) {
     // throw new
     // BusinessException(Messages.getString("AbstractEMFRepositoryFactory.cannotGenerateItem"));
     // //$NON-NLS-1$
     // }
     EcoreUtil.resolveAll(createResource);
     return newItem;
   } else {
     boolean changeLabelWithCopyPrefix = true;
     return copyFromResource(createResource, changeLabelWithCopyPrefix);
   }
 }
Пример #2
0
          public boolean visit(IResourceDelta delta) {
            if (delta.getResource().getType() != IResource.FILE) {
              return true;
            }
            int deltaKind = delta.getKind();
            if (deltaKind == IResourceDelta.CHANGED && delta.getFlags() != IResourceDelta.MARKERS) {
              URI platformURI = URI.createPlatformResourceURI(delta.getFullPath().toString(), true);
              Resource changedResource = resourceSet.getResource(platformURI, false);
              if (changedResource != null) {
                changedResource.unload();
                com.github.funthomas424242.rezeptsammler.rezept.resource.rezept.IRezeptTextResource
                    currentResource = getResource();
                if (changedResource.equals(currentResource)) {
                  // reload the resource displayed in the editor
                  resourceSet.getResource(currentResource.getURI(), true);
                }
                if (currentResource != null && currentResource.getErrors().isEmpty()) {
                  EcoreUtil.resolveAll(currentResource);
                }
                // reset the selected element in outline and properties by text position
                if (highlighting != null) {
                  highlighting.updateEObjectSelection();
                }
              }
            }

            return true;
          }
Пример #3
0
 /**
  * Tries to resolve all unresolved proxy objects in the given resource. If all proxies were
  * resolved true is returned. If some could not be resolved, false is returned.
  *
  * @param resource the resource containing the proxy object
  * @return true on success
  */
 public static boolean resolveAll(org.eclipse.emf.ecore.resource.Resource resource) {
   org.eclipse.emf.ecore.util.EcoreUtil.resolveAll(resource);
   if (findUnresolvedProxies(resource).size() > 0) {
     return false;
   } else {
     return true;
   }
 }
Пример #4
0
 private void setResource(
     com.github.funthomas424242.rezeptsammler.rezept.resource.rezept.IRezeptTextResource
         resource) {
   assert resource != null;
   this.resource = resource;
   if (this.resource.getErrors().isEmpty()) {
     EcoreUtil.resolveAll(this.resource);
   }
 }
  @Override
  protected List<DiffElement> detectDifferences(EObject left, EObject right)
      throws InterruptedException {

    Map<String, Object> options = Collections.emptyMap();

    leftRes = left.eResource();
    rightRes = right.eResource();
    EcoreUtil.resolveAll(left);
    EcoreUtil.resolveAll(right);
    left.eResource().getContents().clear();
    right.eResource().getContents().clear();

    MatchModel match = MatchService.doMatch(left, right, options);
    DiffModel diff = DiffService.doDiff(match);

    EList<DiffElement> differences = diff.getDifferences();
    return differences;
  }
 public Query parse(String input) {
   resourceSet.getResources().clear();
   Resource resource = resourceSet.createResource(createURI("MyQuery.__query"));
   try {
     resource.load(new StringInputStream(input), null);
     EcoreUtil.resolveAll(resource);
   } catch (IOException e) {
     throw new RuntimeException(e);
   }
   return filter(resource.getContents(), Query.class).iterator().next();
 }
Пример #7
0
  protected Resource parserInputFile(String pathName) throws IOException {
    TheaterResourceFactory factory = new TheaterResourceFactory();

    ResourceSet rs = new ResourceSetImpl();
    rs.getResourceFactoryRegistry().getExtensionToFactoryMap().put("theater", factory);

    Resource resource = rs.createResource(URI.createFileURI(pathName));
    resource.load(Collections.EMPTY_MAP);
    EcoreUtil.resolveAll(resource);
    return resource;
  }
 protected JvmTypeReference ref(java.lang.reflect.Type type, JvmTypeReference... arguments) {
   JvmTypeReference result = factory.createTypeReference(type);
   if (arguments.length > 0) {
     for (JvmTypeReference typeArgument : arguments) {
       ((JvmParameterizedTypeReference) result).getArguments().add(typeArgument);
     }
   }
   Resource syntheticResource = getSyntheticResource();
   syntheticResource.getContents().add(result);
   EcoreUtil.resolveAll(syntheticResource);
   return result;
 }
 private void copyProfileApplicationViaResources(URI originalPaURI, URI newPaURI)
     throws IOException {
   ResourceSet resourceSet = new ResourceSetImpl();
   Resource originalPaResource = resourceSet.getResource(originalPaURI, true);
   EcoreUtil.resolveAll(originalPaResource);
   Resource newPaResource = resourceSet.createResource(newPaURI);
   newPaResource.getContents().addAll(originalPaResource.getContents());
   HashMap<String, Object> options = new HashMap<String, Object>();
   options.put(XMIResource.OPTION_SCHEMA_LOCATION, true);
   newPaResource.save(null);
   originalPaResource.unload();
   newPaResource.unload();
 }
Пример #10
0
  /**
   * Computes the import list given the <b>initial</b> imported file. This will recursively walk the
   * import tree of that initial file.
   *
   * @param initialImport The initial imported file from which to compute the imort list.
   * @param resourceSet The resource set in which the list will be loaded.
   * @return The whole import list.
   */
  public Set<URI> computeImportList(IFile initialImport, ResourceSet resourceSet) {
    Resource moduleImport = getModule(initialImport, resourceSet);
    if (moduleImport != null) {
      EcoreUtil.resolveAll(resourceSet);
    }

    final Set<URI> dependencies = new LinkedHashSet<URI>();
    for (Resource res : resourceSet.getResources()) {
      dependencies.add(res.getURI());
    }

    return dependencies;
  }
 private void copyProfileApplicationViaCopier(URI originalPaURI, URI newPaURI) throws IOException {
   ResourceSet resourceSet = new ResourceSetImpl();
   Resource originalPaResource = resourceSet.getResource(originalPaURI, true);
   EcoreUtil.resolveAll(originalPaResource);
   Resource newPaResource = resourceSet.createResource(newPaURI);
   Copier copier = new Copier();
   originalPaResource
       .getContents()
       .stream()
       .forEach(eObject -> newPaResource.getContents().add(copier.copy(eObject)));
   copier.copyReferences();
   newPaResource.save(null);
   originalPaResource.unload();
   newPaResource.unload();
 }
Пример #12
0
 /**
  * This will try and resolve all logical resources that constitute this model in the local
  * resource set.
  *
  * @return The list of all logical resources that constitute this model.
  */
 private void resolveLocalResourceSet() {
   Iterator<ModelResolverDescriptor> modelResolverIterator =
       EMFCompareExtensionRegistry.getRegisteredModelResolvers().iterator();
   boolean resolved = false;
   while (!resolved && modelResolverIterator.hasNext()) {
     ModelResolverDescriptor descriptor = modelResolverIterator.next();
     if (descriptor.canResolve(new ModelIdentifier(emfResource))) {
       descriptor.getModelResolver().resolve(file, emfResource);
       resolved = true;
     }
   }
   if (!resolved) {
     EcoreUtil.resolveAll(localResourceSet);
   }
 }
Пример #13
0
  protected Item copyFromResource(Resource createResource, boolean changeLabelWithCopyPrefix)
      throws PersistenceException, BusinessException {
    Item newItem =
        (Item)
            EcoreUtil.getObjectByType(
                createResource.getContents(), PropertiesPackage.eINSTANCE.getItem());
    Property property = newItem.getProperty();
    property.setId(getNextId());
    property.setAuthor(getRepositoryContext().getUser());

    if (changeLabelWithCopyPrefix) {
      setPropNewName(property);
    }
    EcoreUtil.resolveAll(createResource);
    return newItem;
  }
Пример #14
0
 public void executeTransformation(IExecutionInformation executionInformation) throws Exception {
   ResourceSet resourceSet = new ResourceSetImpl();
   Resource resource =
       resourceSet.createResource(locator.getEMFURI(inputModels.get(0).getModel()));
   resource.load(null);
   EcoreUtil.resolveAll(resourceSet);
   GenModel genModel = (GenModel) resource.getContents().get(0);
   genModel.setCanGenerate(true);
   // generate the code
   Generator generator = new Generator();
   generator.setInput(genModel);
   generator.generate(
       genModel,
       GenBaseGeneratorAdapter.MODEL_PROJECT_TYPE,
       new BasicMonitor.Printing(System.err));
   for (File file : outputFiles) {
     executionEnvironment.fileReady(file, transformation);
   }
 }
Пример #15
0
  /**
   * {@inheritDoc}
   *
   * @see
   *     org.eclipse.core.resources.mapping.ResourceMapping#getTraversals(org.eclipse.core.resources.mapping.ResourceMappingContext,
   *     org.eclipse.core.runtime.IProgressMonitor)
   */
  @Override
  public ResourceTraversal[] getTraversals(ResourceMappingContext context, IProgressMonitor monitor)
      throws CoreException {
    if (!isResolved) {
      resolveLocalResourceSet();

      if (context instanceof RemoteResourceMappingContext) {
        RemoteResourceMappingContext remoteContext = (RemoteResourceMappingContext) context;

        for (Resource eResource : localResourceSet.getResources()) {
          final IFile localFile;
          if (eResource == emfResource) {
            localFile = file;
          } else {
            localFile = (IFile) EclipseModelUtils.findIResource(eResource);
          }

          IStorage remoteContents = remoteContext.fetchRemoteContents(localFile, monitor);
          IStorage ancestorContents = remoteContext.fetchBaseContents(localFile, monitor);

          if (remoteContents != null) {
            if (remoteResourceSet == null) {
              remoteResourceSet = createRemoteResourceSet(localFile, remoteContents);
            } else {
              RevisionedURIConverter converter =
                  (RevisionedURIConverter) remoteResourceSet.getURIConverter();
              converter.setStorage(remoteContents);
            }
            loadRemoteResource(eResource.getURI(), remoteContents, remoteResourceSet);
          }
          if (ancestorContents != null) {
            if (ancestorResourceSet == null) {
              ancestorResourceSet = createRemoteResourceSet(localFile, ancestorContents);
            } else {
              RevisionedURIConverter converter =
                  (RevisionedURIConverter) ancestorResourceSet.getURIConverter();
              converter.setStorage(ancestorContents);
            }
            loadRemoteResource(eResource.getURI(), ancestorContents, ancestorResourceSet);
          }
        }

        // There is a chance that the resource did not exist on the repository
        if (remoteResourceSet != null) {
          EcoreUtil.resolveAll(remoteResourceSet);
        }
        if (ancestorResourceSet != null) {
          EcoreUtil.resolveAll(ancestorResourceSet);
        }
      }

      resolvePhysicalResources();

      isResolved = true;
    }

    /*
     * All of our resource sets are now fully resolved. Browse them to find all IResources than constitute
     * this logical model, whether they exist locally or not.
     */

    ResourceTraversal traversal =
        new ResourceTraversal(
            iResourcesInScope.toArray(new IResource[iResourcesInScope.size()]),
            IResource.DEPTH_ONE,
            IResource.NONE);

    return new ResourceTraversal[] {
      traversal,
    };
  }
Пример #16
0
 public static Resource loadModelPath(String path, ResourceSet rs) throws IOException {
   Resource res = rs.createResource(EMFUtil.createFileURI(path));
   res.load(null);
   EcoreUtil.resolveAll(rs); // IMPORTANT
   return res;
 }
Пример #17
0
 public static Resource loadModelURI(String uri, ResourceSet rs) throws IOException {
   Resource res = rs.createResource(URI.createURI(uri));
   res.load(null);
   EcoreUtil.resolveAll(rs); // IMPORTANT
   return res;
 }
Пример #18
0
 public void setURI(org.eclipse.emf.common.util.URI uri) {
   // because of the context dependent proxy resolving it is essential to resolve all
   // proxies before the URI is changed which can cause loss of object identities
   org.eclipse.emf.ecore.util.EcoreUtil.resolveAll(this);
   super.setURI(uri);
 }
Пример #19
0
  @Override
  public void execute() throws BuildException {
    checkParameters();

    AntClassLoader taskloader = setClassLoader();

    registerResourceFactories();
    try {
      log("loading syntax file...");
      ICsTextResource csResource = CsResourceUtil.getResource(syntaxFile);
      EList<EObject> contents = csResource.getContents();
      if (contents.size() < 1) {
        if (!csResource.getErrors().isEmpty()) {
          log("Resource has the following errors:");
          logErrors(csResource);
        }
        throw new BuildException(
            "Generation failed, because the syntax file could not be loaded. Probably it contains syntactical errors.");
      }
      ResourceSet resourceSet = csResource.getResourceSet();
      EcoreUtil.resolveAll(resourceSet);
      Set<EObject> unresolvedProxies = CsResourceUtil.findUnresolvedProxies(resourceSet);
      logUnresolvedProxies(unresolvedProxies);
      if (unresolvedProxies.size() > 0) {
        throw new BuildException(
            "Generation failed, because the syntax file contains unresolved proxy objects.");
      }
      ConcreteSyntax syntax = (ConcreteSyntax) contents.get(0);
      performPreprocessing(syntax);

      IFileSystemConnector folderConnector =
          new IFileSystemConnector() {

            public File getProjectFolder(IPluginDescriptor plugin) {
              return new File(rootFolder.getAbsolutePath() + File.separator + plugin.getName());
            }
          };

      Result result = null;

      boolean useUIJob = false;
      if (Platform.isRunning()) {
        File wsFolder = new File(ResourcesPlugin.getWorkspace().getRoot().getLocationURI());
        if (rootFolder.equals(wsFolder)) useUIJob = true;
      }

      AntProblemCollector problemCollector = new AntProblemCollector(this);
      if (useUIJob) {
        UIGenerationContext context =
            new UIGenerationContext(folderConnector, problemCollector, syntax);
        UICreateResourcePluginsJob job = new UICreateResourcePluginsJob();
        result = job.run(context, new AntLogMarker(this), new AntDelegateProgressMonitor(this));
      } else {
        AntGenerationContext context =
            new AntGenerationContext(
                folderConnector,
                problemCollector,
                syntax,
                rootFolder,
                syntaxProjectName,
                generateANTLRPlugin,
                generateModelCode);
        AntResourcePluginGenerator generator = new AntResourcePluginGenerator();
        result =
            generator.run(context, new AntLogMarker(this), new AntDelegateProgressMonitor(this));
      }

      if (result != Result.SUCCESS) {
        if (result == Result.ERROR_FOUND_UNRESOLVED_PROXIES) {
          logUnresolvedProxies(result.getUnresolvedProxies());

          resetClassLoader(taskloader);
          throw new BuildException("Generation failed " + result);
        } else {
          logErrors(syntax.eResource());

          resetClassLoader(taskloader);
          throw new BuildException("Generation failed " + result);
        }
      }

      Collection<GenerationProblem> errors = problemCollector.getErrors();
      if (!errors.isEmpty()) {
        for (GenerationProblem error : errors) {
          log("Found problem: " + error.getMessage(), Project.MSG_ERR);
        }
        throw new BuildException(
            "Generation failed. Found "
                + errors.size()
                + " problem(s) while generating text resource plug-ins.");
      }
    } catch (Exception e) {
      resetClassLoader(taskloader);
      log("Exception while generation text resource: " + e.getMessage(), Project.MSG_ERR);
      e.printStackTrace();
      throw new BuildException(e);
    }
    resetClassLoader(taskloader);
  }
Пример #20
0
 public static void resolveAll(Resource resource) {
   EcoreUtil.resolveAll(resource.getResourceSet());
 }
Пример #21
0
  public void setUri(String uri) {
    ResourceSet rs = forcedResourceSet != null ? forcedResourceSet : new XtextResourceSet();
    for (String loadedResource : loadedResources) {
      URI loadedResourceUri = URI.createURI(loadedResource);
      if (equal(loadedResourceUri.fileExtension(), "genmodel")) {
        IResourceServiceProvider resourceServiceProvider =
            IResourceServiceProvider.Registry.INSTANCE.getResourceServiceProvider(
                loadedResourceUri);
        if (resourceServiceProvider == null) {
          try {
            Class<?> genModelSupport =
                Class.forName("org.eclipse.emf.codegen.ecore.xtext.GenModelSupport");
            Object instance = genModelSupport.newInstance();
            genModelSupport
                .getDeclaredMethod("createInjectorAndDoEMFRegistration")
                .invoke(instance);
          } catch (ClassNotFoundException e) {
            LOG.error("Couldn't initialize GenModel support. Is it on the classpath?");
            LOG.debug(e.getMessage(), e);
          } catch (Exception e) {
            LOG.error("Couldn't initialize GenModel support.", e);
          }
        }
      } else if (equal(loadedResourceUri.fileExtension(), "ecore")) {
        IResourceServiceProvider resourceServiceProvider =
            IResourceServiceProvider.Registry.INSTANCE.getResourceServiceProvider(
                loadedResourceUri);
        if (resourceServiceProvider == null) {
          EcoreSupportStandaloneSetup.setup();
        }
      } else if (equal(loadedResourceUri.fileExtension(), "xcore")) {
        IResourceServiceProvider resourceServiceProvider =
            IResourceServiceProvider.Registry.INSTANCE.getResourceServiceProvider(
                loadedResourceUri);
        if (resourceServiceProvider == null) {
          try {
            Class<?> xcore = Class.forName("org.eclipse.emf.ecore.xcore.XcoreStandaloneSetup");
            xcore.getDeclaredMethod("doSetup", new Class[0]).invoke(null);
          } catch (ClassNotFoundException e) {
            LOG.error("Couldn't initialize Xcore support. Is it on the classpath?");
            LOG.debug(e.getMessage(), e);
          } catch (Exception e) {
            LOG.error("Couldn't initialize Xcore support.", e);
          }
        }
        URI xcoreLangURI =
            URI.createPlatformResourceURI(
                "/org.eclipse.emf.ecore.xcore.lib/model/XcoreLang.xcore", true);
        try {
          rs.getResource(xcoreLangURI, true);
        } catch (WrappedException e) {
          LOG.error("Could not load XcoreLang.xcore.", e);
          Resource brokenResource = rs.getResource(xcoreLangURI, false);
          rs.getResources().remove(brokenResource);
        }
      }
      rs.getResource(loadedResourceUri, true);
    }
    if (!rs.getResources().isEmpty()) {
      installIndex(rs);
      for (int i = 0, size = rs.getResources().size(); i < size; i++) {
        Resource res = rs.getResources().get(i);
        if (res.getContents().isEmpty()) LOG.error("Error loading '" + res.getURI() + "'");
        else if (!res.getErrors().isEmpty())
          LOG.error(
              "Error loading '" + res.getURI() + "':\n" + Joiner.on('\n').join(res.getErrors()));
      }
      EcoreUtil.resolveAll(rs);
    }
    XtextResource resource = (XtextResource) rs.getResource(URI.createURI(uri), true);
    if (resource.getContents().isEmpty()) {
      throw new IllegalArgumentException("Couldn't load grammar for '" + uri + "'.");
    }
    if (!resource.getErrors().isEmpty()) {
      LOG.error(resource.getErrors());
      throw new IllegalStateException(
          "Problem parsing '" + uri + "':\n" + Joiner.on('\n').join(resource.getErrors()));
    }

    final Grammar grammar = (Grammar) resource.getContents().get(0);
    validateGrammar(grammar);
    this.grammar = grammar;
  }
Пример #22
0
 @Test
 public void testLoadFromStorage() {
   try {
     StringConcatenation _builder = new StringConcatenation();
     _builder.append("package mypack");
     _builder.newLine();
     _builder.newLine();
     _builder.append("class MyClass {");
     _builder.newLine();
     _builder.append("\t");
     _builder.append("public def void foo() {");
     _builder.newLine();
     _builder.append("\t");
     _builder.append("}");
     _builder.newLine();
     _builder.append("}");
     _builder.newLine();
     final IFile file = this.helper.createFile("src/mypack/MyClass.xtend", _builder.toString());
     StringConcatenation _builder_1 = new StringConcatenation();
     _builder_1.append("package mypack");
     _builder_1.newLine();
     _builder_1.newLine();
     _builder_1.append("class OtherClass extends MyClass {");
     _builder_1.newLine();
     _builder_1.append("\t");
     _builder_1.append("override foo() {");
     _builder_1.newLine();
     _builder_1.append("\t");
     _builder_1.append("}");
     _builder_1.newLine();
     _builder_1.append("}");
     _builder_1.newLine();
     final IFile file2 =
         this.helper.createFile("src/mypack/OtherClass.xtend", _builder_1.toString());
     IResourcesSetupUtil.waitForAutoBuild();
     final URI uri = this.uriMapper.getUri(file);
     final URI uri2 = this.uriMapper.getUri(file2);
     IProject _project = file.getProject();
     final ResourceSet resourceSet = this.resourceSetProvider.get(_project);
     SourceLevelURIsAdapter.setSourceLevelUris(
         resourceSet, Collections.<URI>unmodifiableList(CollectionLiterals.<URI>newArrayList()));
     Resource _resource = resourceSet.getResource(uri2, true);
     final StorageAwareResource resource2 = ((StorageAwareResource) _resource);
     boolean _isLoadedFromStorage = resource2.isLoadedFromStorage();
     Assert.assertTrue(_isLoadedFromStorage);
     EcoreUtil.resolveAll(resource2);
     IResourceDescription _resourceDescription = resource2.getResourceDescription();
     Iterable<IEObjectDescription> _exportedObjects = _resourceDescription.getExportedObjects();
     final Function1<IEObjectDescription, String> _function =
         new Function1<IEObjectDescription, String>() {
           @Override
           public String apply(final IEObjectDescription it) {
             QualifiedName _name = it.getName();
             return _name.toString();
           }
         };
     Iterable<String> _map =
         IterableExtensions.<IEObjectDescription, String>map(_exportedObjects, _function);
     String _join = IterableExtensions.join(_map, ",");
     Assert.assertEquals("mypack.OtherClass", _join);
     Resource _resource_1 = resourceSet.getResource(uri, false);
     final StorageAwareResource resource = ((StorageAwareResource) _resource_1);
     boolean _isLoadedFromStorage_1 = resource.isLoadedFromStorage();
     Assert.assertTrue(_isLoadedFromStorage_1);
     IResourceDescription _resourceDescription_1 = resource.getResourceDescription();
     Iterable<IEObjectDescription> _exportedObjects_1 =
         _resourceDescription_1.getExportedObjects();
     final Function1<IEObjectDescription, String> _function_1 =
         new Function1<IEObjectDescription, String>() {
           @Override
           public String apply(final IEObjectDescription it) {
             QualifiedName _name = it.getName();
             return _name.toString();
           }
         };
     Iterable<String> _map_1 =
         IterableExtensions.<IEObjectDescription, String>map(_exportedObjects_1, _function_1);
     String _join_1 = IterableExtensions.join(_map_1, ",");
     Assert.assertEquals("mypack.MyClass", _join_1);
   } catch (Throwable _e) {
     throw Exceptions.sneakyThrow(_e);
   }
 }