Example #1
1
 public ResourceSet createResourceSet() {
   Environment.Registry.INSTANCE.registerEnvironment(
       new UMLEnvironmentFactory().createEnvironment());
   ResourceSet resourceSet = new ResourceSetImpl();
   OCL.initialize(resourceSet);
   // Make sure that the UML metamodel and primitive types
   //   libraries are loaded
   umlMetamodel =
       (Package)
           resourceSet
               .getResource(URI.createURI(UMLResource.UML_METAMODEL_URI), true)
               .getContents()
               .get(0);
   umlPrimitiveTypes =
       (Package)
           resourceSet
               .getResource(URI.createURI(UMLResource.UML_PRIMITIVE_TYPES_LIBRARY_URI), true)
               .getContents()
               .get(0);
   ecorePrimitiveTypes =
       (Package)
           resourceSet
               .getResource(URI.createURI(UMLResource.ECORE_PRIMITIVE_TYPES_LIBRARY_URI), true)
               .getContents()
               .get(0);
   return resourceSet;
 }
Example #2
0
 protected void installImports() {
   URI baseURI = getBaseURI(ecoreResource);
   List<Import> allImports = pivotModel.getOwnedImports();
   for (EObject eContent : ecoreResource.getContents()) {
     if (eContent instanceof EModelElement) {
       EAnnotation importAnnotation =
           ((EModelElement) eContent).getEAnnotation(PivotConstants.IMPORT_ANNOTATION_SOURCE);
       if (importAnnotation != null) {
         EMap<String, String> details = importAnnotation.getDetails();
         for (String key : details.keySet()) {
           URI uri = URI.createURI(details.get(key));
           if (baseURI != null) {
             uri = uri.resolve(baseURI);
           }
           try {
             assert uri != null;
             Element importedObject =
                 metamodelManager.loadResource(uri, null, ecoreResource.getResourceSet());
             if (importedObject instanceof Namespace) {
               Import anImport = PivotFactory.eINSTANCE.createImport();
               anImport.setName(key);
               anImport.setImportedNamespace((Namespace) importedObject);
               allImports.add(anImport);
             }
           } catch (ParserException e) {
             error(e.getMessage());
           }
         }
       }
     }
   }
 }
Example #3
0
 public String copy(String basePath, ImageRef source, String targetDirName) {
   try {
     ByteBuffer buffer = ByteBuffer.allocate(16 * 1024);
     Resource res = source.eResource();
     URI uri = source.eResource().getURI();
     URI inPath = URI.createURI(source.getPath()).resolve(uri);
     URI outPath =
         URI.createURI(source.getPath())
             .resolve(URI.createFileURI(new File(targetDirName).getAbsolutePath()));
     ReadableByteChannel inChannel =
         Channels.newChannel(res.getResourceSet().getURIConverter().createInputStream(inPath));
     WritableByteChannel outChannel =
         Channels.newChannel(res.getResourceSet().getURIConverter().createOutputStream(outPath));
     while (inChannel.read(buffer) != -1) {
       buffer.flip();
       outChannel.write(buffer);
       buffer.compact();
     }
     buffer.flip();
     while (buffer.hasRemaining()) {
       outChannel.write(buffer);
     }
     outChannel.close();
     return outPath.toFileString();
   } catch (IOException e) {
     // TODO Auto-generated catch block
     logger.error(e);
     return null;
   }
 }
  @Override
  protected void setUp() throws Exception {
    super.setUp();

    domain = TransactionalEditingDomain.Factory.INSTANCE.createEditingDomain();
    refreshEditorsPrecommitListener = new RefreshEditorsPrecommitListener(domain);

    resourceSet = domain.getResourceSet();
    sessionResourceURI =
        URI.createPlatformPluginURI(SiriusTestsPlugin.PLUGIN_ID + PATH + "vp1753.aird", true);
    semanticResourceURI =
        URI.createPlatformPluginURI(SiriusTestsPlugin.PLUGIN_ID + PATH + "vp1753.ecore", true);

    sessionResource = resourceSet.getResource(sessionResourceURI, true);

    final DRepresentation firstDRepresentation =
        getFirstElement(sessionResource, DRepresentation.class);
    refreshFilterStub = new RefreshFilterStub(firstDRepresentation);
    RefreshFilterManager.INSTANCE.addRefreshFilter(refreshFilterStub);

    oldRefreshAutoMode =
        Platform.getPreferencesService()
            .getBoolean(
                SiriusPlugin.ID, SiriusPreferencesKeys.PREF_AUTO_REFRESH.name(), false, null);
    InstanceScope.INSTANCE
        .getNode(SiriusPlugin.ID)
        .putBoolean(SiriusPreferencesKeys.PREF_AUTO_REFRESH.name(), true);
  }
 /** @since 2.3 */
 @Override
 public List<?> getTargetObjects(Object object, IMarker marker) {
   if (object instanceof AdapterFactoryEditingDomain) {
     ArrayList<Object> result = new ArrayList<Object>();
     AdapterFactoryEditingDomain editingDomain = (AdapterFactoryEditingDomain) object;
     String uriAttribute = marker.getAttribute(EValidator.URI_ATTRIBUTE, null);
     if (uriAttribute != null) {
       URI uri = URI.createURI(uriAttribute);
       EObject eObject = editingDomain.getResourceSet().getEObject(uri, true);
       if (eObject != null) {
         result.add(editingDomain.getWrapper(eObject));
       }
     }
     String relatedURIsAttribute = marker.getAttribute(EValidator.RELATED_URIS_ATTRIBUTE, null);
     if (relatedURIsAttribute != null) {
       for (String relatedURI : relatedURIsAttribute.split(" ")) {
         URI uri = URI.createURI(URI.decode(relatedURI));
         EObject eObject = editingDomain.getResourceSet().getEObject(uri, true);
         if (eObject != null) {
           result.add(editingDomain.getWrapper(eObject));
         }
       }
     }
     return result;
   } else {
     return super.getTargetObjects(object, marker);
   }
 }
 @Override
 public @NonNull String getInitialContentsAsString(
     @NonNull IFile newFile, @NonNull AbstractFileDialog dialog) {
   URI ecoreURI = URI.createPlatformResourceURI(newFile.getFullPath().toString(), true);
   URI oclInEcoreURI = ecoreURI.trimFileExtension().appendFileExtension("oclinecore");
   String initialContentsAsString = super.getInitialContentsAsString(newFile, dialog);
   @SuppressWarnings("null")
   OCL ocl = OCL.newInstance(EPackage.Registry.INSTANCE);
   ResourceSet resourceSet2 = ocl.getResourceSet();
   BaseCSResource csResource =
       ClassUtil.nonNullState((BaseCSResource) resourceSet2.createResource(oclInEcoreURI));
   try {
     ByteArrayInputStream inputStream =
         new ByteArrayInputStream(initialContentsAsString.getBytes());
     csResource.load(inputStream, null);
     ASResource asResource = ocl.cs2as(csResource);
     Resource eResource = ocl.as2ecore(asResource, ecoreURI);
     ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
     eResource.save(outputStream, null);
     @SuppressWarnings("null")
     @NonNull
     String string = outputStream.toString();
     return string;
   } catch (IOException e) {
     logger.error("Failed to create " + ecoreURI, e);
   }
   return initialContentsAsString;
 }
Example #7
0
  @Test
  public void testResolveElements() throws Exception {
    URI resourceURI = URI.createFileURI("testresource.refactoringtestlanguage");
    String textualModel = "A { B { C { ref A.B } } ref B }";
    XtextResource resource = getResource(textualModel, resourceURI.toString());
    Element elementA = (Element) resource.getContents().get(0).eContents().get(0);
    Element elementB = elementA.getContained().get(0);
    Element elementC = elementB.getContained().get(0);

    URI uriB = EcoreUtil.getURI(elementB);
    URI uriC = EcoreUtil.getURI(elementC);
    String newName = "newB";

    List<URI> renamedElementURIs = newArrayList(uriB, uriC);
    IRenameStrategy renameStrategy =
        getInjector().getInstance(IRenameStrategy.Provider.class).get(elementB, null);

    IRenamedElementTracker renamedElementTracker = new RenamedElementTracker();
    Map<URI, URI> original2newElementURIs =
        renamedElementTracker.renameAndTrack(
            renamedElementURIs, newName, resource.getResourceSet(), renameStrategy, null);

    assertEquals("B", elementB.getName());
    assertEquals(2, original2newElementURIs.size());
    assertEquals(resourceURI.appendFragment(newName), original2newElementURIs.get(uriB));
    assertEquals(uriC, original2newElementURIs.get(uriC));
  }
 @Override
 public String softwareProfile() {
   URI uri =
       URI.createPlatformPluginURI(
           "gov.redhawk.ide.tests.ui/resources/analogDevice/analogDevice.spd.xml", true);
   return uri.toString();
 }
Example #9
0
 /** @since 2.3 */
 protected void registerURI(Resource resource) {
   Map<URI, Resource> map = getURIResourceMap();
   if (map != null) {
     final URI uri = resource.getURI();
     if (uri != null) {
       URI normalized = getURIConverter().normalize(uri);
       if (!normalized.equals(uri)) {
         Resource previous = map.put(normalized, resource);
         if (previous != null && previous != resource) {
           throw new IllegalStateException(
               "A resource with the normalized URI '"
                   + normalized
                   + "' was already registered. The resource with the URI '"
                   + previous
                   + "' is no longer registered with the normalized form.");
         }
       }
     }
     Resource previous = map.put(uri, resource);
     if (previous != null && previous != resource) {
       throw new IllegalStateException(
           "A different resource with the URI '" + uri + "' was already registered.");
     }
   }
 }
Example #10
0
 public URI getFullURI(IVariableBinding binding) {
   SegmentSequence.Builder builder = SegmentSequence.newBuilder("");
   URI uri = getFullURI(binding.getDeclaringClass(), builder);
   builder.append(".");
   builder.append(binding.getName());
   return uri.appendFragment(builder.toString());
 }
 /**
  * Returns the normalized form of the URI, using the given multiple candidates (this means that
  * more than 2 modules had a matching name).
  *
  * @param uri The URI that is to be normalized.
  * @param candidateURIs URIs of the modules that can potentially be a match for <code>uri</code>.
  * @return the normalized form
  */
 private URI findBestMatchFor(URI uri, Set<URI> candidateURIs) {
   URI normalized = null;
   final Iterator<URI> candidatesIterator = candidateURIs.iterator();
   final List<String> referenceSegments = Arrays.asList(uri.segments());
   Collections.reverse(referenceSegments);
   int highestEqualFragments = 0;
   while (candidatesIterator.hasNext()) {
     final URI next = candidatesIterator.next();
     int equalFragments = 0;
     final List<String> candidateSegments = Arrays.asList(next.segments());
     Collections.reverse(candidateSegments);
     for (int i = 0; i < Math.min(candidateSegments.size(), referenceSegments.size()); i++) {
       if (candidateSegments.get(i) == referenceSegments.get(i)) {
         equalFragments++;
       } else {
         break;
       }
     }
     if (equalFragments > highestEqualFragments) {
       highestEqualFragments = equalFragments;
       normalized = next;
     }
   }
   return normalized;
 }
 public static String getAbsoluteLocation(final File base, final String relativePath) {
   final URI baseLocation = URI.createFileURI(base.getAbsolutePath());
   URI relLocation = URI.createURI(relativePath, false);
   if (baseLocation.isHierarchical() && !baseLocation.isRelative() && relLocation.isRelative())
     relLocation = relLocation.resolve(baseLocation);
   return URI.decode(relLocation.toString());
 }
  @Test
  public void testInterfaceGeneration() {
    System.out.println("*** BinaryProtocolGeneratorTest / Datatype Generation");

    // load example Franca IDL interface
    String inputfile = TestConfiguration.fdeployBinaryProtocolFile;
    URI root = URI.createURI("classpath:/");
    URI loc = URI.createFileURI(inputfile);
    FDModel fdmodel = loader.loadModel(loc, root);
    assertNotNull(fdmodel);

    // get first interface referenced by FDeploy model
    FDModelExtender fdmodelExt = new FDModelExtender(fdmodel);
    List<FDInterface> interfaces = fdmodelExt.getFDInterfaces();
    assertTrue(interfaces.size() > 0);
    FDInterface api = interfaces.get(0);

    // create wrapper and generate code from it
    FDeployedInterface deployed = new FDeployedInterface(api);
    ExampleBinaryProtocolGenerator generator = new ExampleBinaryProtocolGenerator();
    String code = generator.generateProtocol(deployed).toString();

    // simply print the generated code to console
    System.out.println("Generated code:\n" + code);
    System.out.println("-----------------------------------------------------");
  }
 /**
  * Tells if the current {@link Resource} corresponds to a modeler resource (*.odesign).
  *
  * @return true if it is a modeler resource
  */
 public boolean isModelerResource() {
   URI uri = getUri();
   if (uri != null) {
     return new FileQuery(uri.fileExtension()).isVSMFile();
   }
   return false;
 }
  @Test
  public void execute_update() throws IncQueryException, IOException {
    ResourceSet set = new ResourceSetImpl();

    URI uri = URI.createPlatformResourceURI("/tcp2/src/tcp2/c/Closed.java", true);
    Resource res = set.getResource(uri, true);
    Resource chartRes =
        set.createResource(
            URI.createFileURI(
                "/Users/stampie/git/programunderstanding-ttc2011/transformation/hu.bme.mit.viatra2.examples.reveng.tests/tcp2.inc.statemachine"));

    AdvancedIncQueryEngine engine = AdvancedIncQueryEngine.createUnmanagedEngine(new EMFScope(set));
    UnprocessedStateClassMatcher matcher2 = UnprocessedStateClassMatcher.on(engine);
    matcher2.forEachMatch(
        new UnprocessedStateClassProcessor() {

          @Override
          public void process(Class pCl) {
            System.out.println(pCl.getName());
          }
        });
    ReengineeringTransformation transformation =
        new ReengineeringTransformation(res, chartRes, engine);
    transformation.reengineer_update();

    //		System.out.println(Joiner.on("\n").join(chartRes.getAllContents()));

    chartRes.save(null);
  }
Example #16
0
  /**
   * Loads a new instance of an aspect. This is required, because lower-level aspects that contain
   * dependencies will be modified, i.e., it's dependencies are woven into it. If this (lower-level)
   * aspect is loaded somewhere else, e.g., a GUI, the modifications are reflected there, which is
   * unwanted behavior. If the aspect were cloned, it would require the mappings of the
   * instantiation for this lower-level aspect to be updated to the new elements, which would be
   * more time-consuming to do. Therefore, to circumvent this, the aspect is saved in a temporary
   * file and loaded again using a separate resource set, which forces to load other aspects to be
   * loaded as new instances. Otherwise the existing resource set would get the resources for the
   * lower-level aspects from its cache.
   *
   * @param aspect the aspect to load a new instance for
   * @return a new instance of the given aspect
   */
  public Aspect loadNewInstance(Aspect aspect) {
    // Given aspect has to be cloned. Otherwise, when adding the aspect to the new resource
    // it gets removed from its current resource. This will mean that the given aspect
    // is directly modified.
    Aspect result = EcoreUtil.copy(aspect);
    String pathName = TEMPORARY_ASPECT.getAbsolutePath();

    // Use our own resource set for saving and loading to workaround the issue.
    ResourceSet resourceSet = new ResourceSetImpl();

    // Create a resource to temporarily save the aspect.
    Resource resource = resourceSet.createResource(URI.createFileURI(pathName));
    resource.getContents().add(result);

    try {
      resource.save(Collections.EMPTY_MAP);

      // Load the temporary aspect ...
      resource = resourceSet.getResource(URI.createFileURI(pathName), true);
      result = (Aspect) resource.getContents().get(0);

      // Copy the aspect to loose the reference to the temporary file...
      result = EcoreUtil.copy(result);
    } catch (IOException e) {
      e.printStackTrace();
    }

    // Delete the temporary file ...
    TEMPORARY_ASPECT.delete();

    return result;
  }
 public void propertyChange(PropertyChangeEvent event) {
   if (event.getProperty().equals(TefkatPlugin.URIMAP_PREFERENCE)) {
     if (null != event.getOldValue()) {
       List list = TefkatPlugin.convertFromString((String) event.getOldValue());
       for (final Iterator itr = list.iterator(); itr.hasNext(); ) {
         URIMap map = (URIMap) itr.next();
         if (map.enabled) {
           URI uri = URI.createURI(map.source);
           URIConverter.URI_MAP.remove(uri);
         }
       }
     }
     if (null != event.getNewValue()) {
       List list = TefkatPlugin.convertFromString((String) event.getNewValue());
       for (final Iterator itr = list.iterator(); itr.hasNext(); ) {
         URIMap map = (URIMap) itr.next();
         if (map.enabled) {
           URI sourceUri = URI.createURI(map.source);
           URI targetUri = URI.createURI(map.target);
           URIConverter.URI_MAP.put(sourceUri, targetUri);
         }
       }
     }
   }
 }
Example #18
0
  /**
   * Create a resource from the given URI and append a new Network instance to its contents. The
   * resourceSet used must be authorized to write on the disk. This means that the default
   * EditingDomain's resourceSet must be used in a write transaction (for example). If it is not
   * possible, do not provide a resourceSet, the default one will be used.
   *
   * @param resourceSet
   * @param uri
   * @return The created network
   * @throws IOException
   */
  public static Network createNetworkResource(final ResourceSet resourceSet, final URI uri)
      throws IOException {

    final String fileName;
    if (uri.isPlatform()) {
      fileName = uri.toPlatformString(true);
    } else {
      fileName = uri.toString();
    }

    // Create the network
    final Network network = DfFactory.eINSTANCE.createNetwork(fileName);

    // Compute the new network name
    final Path networkPath = new Path(uri.trimFileExtension().path());
    // 3 first segments are resource/<PROJECT>/src
    network.setName(networkPath.removeFirstSegments(3).toString().replace('/', '.'));

    // Create the resource
    Resource res = resourceSet.createResource(uri);
    res.getContents().add(network);
    res.save(Collections.EMPTY_MAP);

    return network;
  }
Example #19
0
 /**
  * @param input
  * @return
  */
 public static URI getUri(IEditorInput input, String editorID) {
   String uriString = null;
   if (input instanceof URIEditorInput) {
     uriString = PathsUtil.getRelativeWorkspaceFromEditorInputWithFragment(input);
   } else {
     uriString = PathsUtil.getRelativeWorkspaceFromEditorInput(input);
     String fragment = MDTUtil.getLastOpenedDiagramPropertyForEditor(uriString, editorID);
     if (fragment != null) {
       uriString = URI.createURI(uriString).appendFragment(fragment).toString();
     }
   }
   if (input != null) {
     URI uri = URI.createURI(uriString);
     if (uri.hasFragment()) {
       return uri;
     }
     ResourceSet resourceSet = new ResourceSetImpl();
     try {
       resourceSet
           .getResourceFactoryRegistry()
           .getExtensionToFactoryMap()
           .put(Resource.Factory.Registry.DEFAULT_EXTENSION, new XMIResourceFactoryImpl());
       Resource resource = resourceSet.getResource(uri, true);
       Diagram diagram = MDTUtil.getFirstDiagramFromResource(resource);
       if (diagram != null) {
         String fragment = resource.getURIFragment(diagram);
         uri = uri.appendFragment(fragment);
       }
     } finally {
       EMFHelper.unload(resourceSet);
     }
     return uri;
   }
   return null;
 }
  @Override
  public void setUp() throws Exception {

    super.setUp();

    EcoreFactory factory = EcoreFactory.eINSTANCE;
    EPackage p = factory.createEPackage();
    p.setName("TestPackage1");
    EClass class0 = factory.createEClass();
    class0.setName("Class0");
    EClass class1 = factory.createEClass();
    class1.setName("Class1");
    EClass class2 = factory.createEClass();
    class2.setName("Class2");

    p.getEClassifiers().add(class0);
    p.getEClassifiers().add(class1);
    p.getEClassifiers().add(class2);

    leftModel = EcoreUtil.copy(p);
    URI leftURI = URI.createURI("leftmodel.ecore");
    ModelUtils.attachResource(leftURI, leftModel);

    expectedModel = EcoreUtil.copy(leftModel);
    URI expectedURI = URI.createURI("expectedmodel.ecore");
    ModelUtils.attachResource(expectedURI, expectedModel);

    p.getEClassifiers().remove(class1);
    rightModel = EcoreUtil.copy(p);
    URI rightURI = URI.createURI("rightmodel.ecore");
    ModelUtils.attachResource(rightURI, rightModel);
  }
  @Override
  protected URI createScriptUri(String scriptName) {
    if (myUseFilename) {
      return URI.createPlatformPluginURI(
          "/"
              + TestUtil.BUNDLE
              + "/"
              + ROOT_DIR_NAME //$NON-NLS-1$ //$NON-NLS-2$
              + "/"
              + scriptName
              + "/"
              + scriptName
              + MDAConstants.QVTO_FILE_EXTENSION_WITH_DOT,
          false); //$NON-NLS-1$ //$NON-NLS-2$
    }

    return URI.createPlatformPluginURI(
        "/"
            + ROOT_DIR_NAME //$NON-NLS-1$
            + "."
            + scriptName
            + "."
            + scriptName,
        false); //$NON-NLS-1$ //$NON-NLS-2$
  }
 public static String convertLocationsToPref(List<URI> locs) {
   StringBuffer buffer = new StringBuffer();
   for (URI l : locs) {
     buffer.append(l.toString()).append("\n");
   }
   return buffer.toString();
 }
  /**
   * @param appContext
   * @return
   */
  private URI determineApplicationModelURI(IApplicationContext appContext) {
    Optional<String> appModelPath = getArgValue(IWorkbench.XMI_URI_ARG, appContext, false);

    String appModelPathValue =
        appModelPath
            .filter(path -> !path.isEmpty())
            .orElseGet(
                () -> {
                  Bundle brandingBundle = appContext.getBrandingBundle();
                  if (brandingBundle != null) {
                    return brandingBundle.getSymbolicName()
                        + "/"
                        + E4Application.APPLICATION_MODEL_PATH_DEFAULT;
                  } else {
                    Logger logger = new WorkbenchLogger(PLUGIN_ID);
                    logger.error(
                        new Exception(),
                        "applicationXMI parameter not set and no branding plugin defined. "); //$NON-NLS-1$
                  }
                  return null;
                });

    URI applicationModelURI = null;

    // check if the appModelPath is already a platform-URI and if so use it
    if (URIHelper.isPlatformURI(appModelPathValue)) {
      applicationModelURI = URI.createURI(appModelPathValue, true);
    } else {
      applicationModelURI = URI.createPlatformPluginURI(appModelPathValue, true);
    }
    return applicationModelURI;
  }
  /** @return a list of uris of all xmi files registered */
  public static Map<URI, Map<String, String>> getExtensionURIS() {
    final Map<URI, Map<String, String>> ret = new LinkedHashMap<URI, Map<String, String>>();
    final IConfigurationElement[] files =
        Platform.getExtensionRegistry().getConfigurationElementsFor(FILE_EXTENSION);
    final URIConverter converter = new ResourceSetImpl().getURIConverter();
    for (final IConfigurationElement file : files) {
      final String filePath = file.getAttribute(FILEPATH_ATTRIBUTE);

      final IConfigurationElement[] children = file.getChildren(FILTER_ELEMENT);
      final Map<String, String> keyValuePairs = new LinkedHashMap<String, String>();
      for (final IConfigurationElement child : children) {
        final String key = child.getAttribute(FILTER_KEY_ATTRIBUTE);
        final String value = child.getAttribute(FILTER_VALUE_ATTRIBUTE);
        keyValuePairs.put(key, value);
      }

      URI uri;
      final String bundleName = file.getContributor().getName();
      final String path = bundleName + '/' + filePath;
      uri = URI.createPlatformPluginURI(path, false);
      if (converter.exists(uri, null)) {
        ret.put(uri, keyValuePairs);
      } else {
        uri = URI.createPlatformResourceURI(filePath, false);
        if (converter.exists(uri, null)) {
          ret.put(uri, keyValuePairs);
        }
      }
    }
    return ret;
  }
  /**
   * @param projectId
   * @param changePackage
   * @param projectHistory
   * @param newVersion
   * @param newProjectState
   * @throws FatalESException
   */
  private void trySave(
      ProjectId projectId,
      AbstractChangePackage changePackage,
      final ProjectHistory projectHistory,
      Version newVersion,
      final Project newProjectState)
      throws FatalESException {
    getResourceHelper()
        .createResourceForProject(
            newProjectState, newVersion.getPrimarySpec(), projectHistory.getProjectId());
    getResourceHelper()
        .createResourceForChangePackage(changePackage, newVersion.getPrimarySpec(), projectId);
    if (FileBasedChangePackage.class.isInstance(changePackage)) {
      try {
        /* move the temporary file to the project folder */
        final URI uri = changePackage.eResource().getURI();
        final URI normalizedUri =
            changePackage.eResource().getResourceSet().getURIConverter().normalize(uri);
        final String filePath = normalizedUri.toFileString() + ".1"; // $NON-NLS-1$
        FileBasedChangePackage.class.cast(changePackage).move(filePath);
        ModelUtil.saveResource(changePackage.eResource(), ModelUtil.getResourceLogger());
      } catch (final IOException ex) {
        throw new FatalESException(StorageException.NOSAVE, ex);
      }
    }

    getResourceHelper().createResourceForVersion(newVersion, projectHistory.getProjectId());

    newVersion.setProjectStateResource(newProjectState.eResource());
    newVersion.setChangeResource(changePackage.eResource());
  }
Example #26
0
  protected void fillRequirements(RequirementSource requirementSource) throws Exception {
    requirementSource.clearContent();
    Collection<MappingElement> mapping = requirementSource.getMappings();
    ResourceSet resourceSet = new ResourceSetImpl();

    String repositoryUri = requirementSource.getRepositoryUri();

    Resource resource =
        resourceSet.getResource(URI.createPlatformResourceURI(repositoryUri, true), true);
    OCLEvaluator evaluator =
        ZigguratOCLPlugin.compileOCL(
            resourceSet, URI.createPlatformResourceURI(bean.getOclUri(), true));

    TreeIterator<EObject> contents = resource.getAllContents();
    Collection<IRequirementType> requirementTypes = bean.getDataPackage().getRequirementTypes();
    while (contents.hasNext()) {
      EObject eObject = contents.next();
      for (IRequirementType reqType : requirementTypes) {
        if (OCLUtilities.isDataType(evaluator, eObject, reqType)) {
          AbstractElement requirement = createRequirement(evaluator, mapping, eObject, reqType);
          dataManager.addElementsToSource(requirementSource, requirement);
        }
      }
    }
  }
 private void parseUrl(String url) {
   if (url == null) return;
   this.uri = null;
   try {
     // TODO check parsing url
     // URL has some valid protocol.
     // Check to see if it is a valid url.
     URL url_inst = new URL(url);
     String protocol2 = url_inst.getProtocol();
     if (protocol2 != null) {
       // XXX : HACK Extreme hacking on...
       // there should be a proper way to handle with spaces and URIs.
       if (protocol2.equalsIgnoreCase(HTTP_PROTOCOL)) {
         this.uri =
             URI.createURI(
                 URI.decode(
                     url.replace("http://platform", "platform:")
                         .replace(
                             "platform::/",
                             "platform:/"))); // .replaceAll("%20", " ")); //$NON-NLS-1$
                                              // //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
       } else if (protocol2.equalsIgnoreCase(PLATFORM_PROTOCOL)) {
         this.uri = URI.createURI(URI.decode(url));
       }
     }
   } catch (MalformedURLException e) {
     // not a valid URL. Just return.
   }
 }
Example #28
0
  public static String getProjectName(URI uri) {
    if ("platform".equals(uri.scheme())) {
      if (uri.segmentCount() < 3) {
        return null;
      }

      String[] segments = uri.segments();
      if (!"resource".equals(segments[0])) {
        return null;
      }

      return segments[1];
    }

    if ("file".equals(uri.scheme())) {
      // TODO getLocation() not working for linked projects!!!
      String[] wsSegments = ResourcesHelper.ROOT.getLocation().segments();
      String[] uriSegments = uri.segments();
      if (uriSegments.length - 1 < wsSegments.length) {
        return null;
      }

      for (int i = 0; i < wsSegments.length; i++) {
        String wsSegment = wsSegments[i];
        String uriSegment = uriSegments[i];
        if (!uriSegment.equals(wsSegment)) {
          return null;
        }
      }

      return uriSegments[wsSegments.length];
    }

    return null;
  }
 /**
  * Get the absolute type URI for a given custom primitive.
  *
  * @param custom Custom primitive.
  * @return Absolute type URI.
  */
 public static URI getAbsoluteTypeURI(CustomPrimitive custom) {
   URI uri = getTypeURI(custom);
   if (uri != null && uri.isRelative() && custom.eResource() != null) {
     uri = uri.resolve(custom.eResource().getURI());
   }
   return uri;
 }
Example #30
0
 public @NonNull Model importObjects(
     @NonNull Collection<EObject> ecoreContents, @NonNull URI pivotURI) {
   EPackage libraryEPackage = isLibrary(ecoreContents);
   if (libraryEPackage != null) {
     newCreateMap = new HashMap<@NonNull EObject, @NonNull Element>();
     org.eclipse.ocl.pivot.Package asLibrary = standardLibrary.getPackage();
     newCreateMap.put(libraryEPackage, asLibrary);
     List<org.eclipse.ocl.pivot.Class> ownedType = asLibrary.getOwnedClasses();
     //			int prefix = LibraryConstants.ECORE_STDLIB_PREFIX.length();
     for (@SuppressWarnings("null") @NonNull
     EClassifier eClassifier : libraryEPackage.getEClassifiers()) {
       String name =
           environmentFactory.getTechnology().getOriginalName(eClassifier); // .substring(prefix);
       Type asType = NameUtil.getNameable(ownedType, name);
       if (asType != null) {
         newCreateMap.put(eClassifier, asType);
       }
     }
     Model containingRoot = PivotUtil.getContainingModel(asLibrary);
     return ClassUtil.nonNullModel(containingRoot);
   }
   @NonNull
   ASResource asResource = metamodelManager.getResource(pivotURI, ASResource.ECORE_CONTENT_TYPE);
   //		try {
   if ((metamodelManager.getLibraryResource() == null) && isPivot(ecoreContents)) {
     String nsURI = ((EPackage) ecoreContents.iterator().next()).getNsURI();
     if (nsURI != null) {
       String stdlibASUri = LibraryConstants.STDLIB_URI + PivotConstants.DOT_OCL_AS_FILE_EXTENSION;
       OCLstdlib library = OCLstdlib.create(stdlibASUri);
       metamodelManager.installResource(library);
       //					metamodelManager.installAs(nsURI, OCLstdlibTables.PACKAGE);
     }
   }
   URI uri = ecoreURI != null ? ecoreURI : ecoreResource.getURI();
   Model pivotModel2 = null;
   if (asResource.getContents().size() > 0) {
     EObject eObject = asResource.getContents().get(0);
     if (eObject instanceof Model) {
       pivotModel2 = (Model) eObject;
     }
   }
   if (pivotModel2 == null) {
     pivotModel2 = pivotModel = PivotUtil.createModel(uri.toString());
   }
   pivotModel = pivotModel2;
   //			installImports();
   update(asResource, ecoreContents);
   //		}
   //		catch (Exception e) {
   //			if (errors == null) {
   //				errors = new ArrayList<Resource.Diagnostic>();
   //			}
   //			errors.add(new XMIException("Failed to load '" + pivotURI + "'", e));
   //		}
   List<Diagnostic> errors2 = errors;
   if (errors2 != null) {
     asResource.getErrors().addAll(ClassUtil.nullFree(errors2));
   }
   return pivotModel2;
 }