Exemplo n.º 1
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;
  }
  @Test
  public void testMerge() throws IOException, MatchException {
    resourceSet
        .getResourceFactoryRegistry()
        .getExtensionToFactoryMap()
        .put("*", new UUIDResourceFactoryImpl());

    // load models
    Resource originModelResource =
        (XMLResource)
            resourceSet.getResource(
                URI.createFileURI(new File(originalModelPath).getAbsolutePath()), true);
    Resource leftModelResource =
        (XMLResource)
            resourceSet.getResource(
                URI.createFileURI(new File(leftModelPath).getAbsolutePath()), true);
    Resource rightModelResource =
        (XMLResource)
            resourceSet.getResource(
                URI.createFileURI(new File(rightModelPath).getAbsolutePath()), true);

    // compute differences
    ComparisonResourceSnapshot leftCRS =
        diffService.generateComparisonResourceSnapshot(
            matchService.generateMatchModel(originModelResource, leftModelResource));
    ComparisonResourceSnapshot rightCRS =
        diffService.generateComparisonResourceSnapshot(
            matchService.generateMatchModel(originModelResource, rightModelResource));

    // create three way diff view
    ThreeWayDiffProvider threeWayDiff = new ThreeWayDiffProvider(leftCRS, rightCRS);

    // detect conflicts
    ConflictReport conflictReport =
        conflictDetectionEngine.detectConflicts(threeWayDiff, new NullProgressMonitor());

    // perform the merge
    MergerImpl merger = new MergerImpl();
    merger.setMergeStrategy(mergeStrategy);
    Resource mergedModelResource =
        resourceSet.createResource(URI.createFileURI(new File(mergedModelPath).getAbsolutePath()));
    merger.merge(conflictReport, mergedModelResource, new NullProgressMonitor());

    // save the merged model
    mergedModelResource.save(null);

    // save the conflict report
    Resource conflictReportResource =
        resourceSet.createResource(
            URI.createFileURI(new File(conflictReportPath).getAbsolutePath()));
    conflictReportResource.getContents().add(conflictReport);
    conflictReportResource.save(null);

    // unload all resources
    originModelResource.unload();
    leftModelResource.unload();
    rightModelResource.unload();
    conflictReportResource.unload();
    mergedModelResource.unload();
  }
Exemplo n.º 3
0
  @Test
  @Ignore
  public void shouldCreateEpatchForMovedElement() throws Exception {
    // given
    ResourceSet rs = new ResourceSetImpl();
    rs.getResourceFactoryRegistry()
        .getExtensionToFactoryMap()
        .put("ecore", new EcoreResourceFactoryImpl());
    rs.getResourceFactoryRegistry()
        .getExtensionToFactoryMap()
        .put("xmi", new XMIResourceFactoryImpl());
    // ...loaded metamodel
    Resource meta = rs.getResource(URI.createFileURI("res/in/movebug/MoveBug.ecore"), true);
    meta.load(null);

    // register package nsuri
    EPackage pckage = (EPackage) meta.getContents().get(0);
    rs.getPackageRegistry().put(pckage.getNsURI(), pckage);
    // ...loaded models
    Resource originModel = rs.getResource(URI.createFileURI("res/in/movebug/Original.xmi"), true);
    originModel.load(null);
    Resource changedModel = rs.getResource(URI.createFileURI("res/in/movebug/Moved.xmi"), true);
    changedModel.load(null);

    // when
    MatchModel matchModel = MatchService.doResourceMatch(originModel, changedModel, null);
    DiffModel diffModel = DiffService.doDiff(matchModel);
    // then
    // ... epatch creation fails because of move between different containers
    Epatch epatch = DiffEpatchService.createEpatch(matchModel, diffModel, "buggyPatch");
  }
 @Override
 public URI getFileURI(final String resourceId) {
   URI _xifexpression = null;
   boolean _endsWith = this.resourceBase.endsWith(File.separator);
   if (_endsWith) {
     _xifexpression = URI.createFileURI((this.resourceBase + resourceId));
   } else {
     _xifexpression = URI.createFileURI(((this.resourceBase + File.separator) + resourceId));
   }
   return _xifexpression;
 }
Exemplo n.º 5
0
 /**
  * sets the org.eclipse.uml2.uml.resources uri for standalone execution
  *
  * @param pathToUMLResources which is typically "../org.eclipse.uml2.uml.resources"
  */
 public void setUmlResourcesUri(String pathToUMLResources) {
   File f = new File(pathToUMLResources);
   if (!f.exists())
     throw new ConfigurationException(
         "The pathToUMLResources location '" + pathToUMLResources + "' does not exist");
   if (!f.isDirectory())
     throw new ConfigurationException("The pathToUMLResources location must point to a directory");
   String path = f.getAbsolutePath();
   try {
     path = f.getCanonicalPath();
   } catch (IOException e) {
     log.error("Error when registering UML Resources location", e);
   }
   log.info("Registering UML Resources uri '" + path + "'");
   ResourceSet targetResourceSet = null;
   Resource.Factory.Registry resourceFactoryRegistry =
       targetResourceSet != null
           ? targetResourceSet.getResourceFactoryRegistry()
           : Resource.Factory.Registry.INSTANCE;
   resourceFactoryRegistry
       .getExtensionToFactoryMap()
       .put(UMLResource.FILE_EXTENSION, UMLResource.Factory.INSTANCE);
   resourceFactoryRegistry
       .getExtensionToFactoryMap()
       .put(CMOF2UMLResource.FILE_EXTENSION, CMOF2UMLResource.Factory.INSTANCE);
   Map<URI, URI> uriMap =
       targetResourceSet != null
           ? targetResourceSet.getURIConverter().getURIMap()
           : URIConverter.URI_MAP;
   //	uriMap.put(URI.createURI(UMLEnvironment.OCL_STANDARD_LIBRARY_NS_URI),
   // URI.createFileURI(oclLocation + "/model/oclstdlib.uml")); //$NON-NLS-1$
   uriMap.put(
       URI.createURI(UMLResource.PROFILES_PATHMAP),
       URI.createFileURI(path + "/profiles/")); // $NON-NLS-1$
   uriMap.put(
       URI.createURI(UMLResource.METAMODELS_PATHMAP),
       URI.createFileURI(path + "/metamodels/")); // $NON-NLS-1$
   uriMap.put(
       URI.createURI(UMLResource.LIBRARIES_PATHMAP),
       URI.createFileURI(path + "/libraries/")); // $NON-NLS-1$
   EPackage.Registry registry2 = registry; // Workaround JDT invisible class anomally
   registry2.put(Ecore2XMLPackage.eNS_URI, Ecore2XMLPackage.eINSTANCE);
   UMLPlugin.getEPackageNsURIToProfileLocationMap()
       .put(
           "http://www.eclipse.org/uml2/schemas/Ecore/5",
           URI.createURI("pathmap://UML_PROFILES/Ecore.profile.uml#_0"));
   UMLPlugin.getEPackageNsURIToProfileLocationMap()
       .put(
           "http://www.eclipse.org/uml2/schemas/Standard/1",
           URI.createURI("pathmap://UML_PROFILES/Standard.profile.uml#_0"));
 }
    /** {@inheritDoc} */
    @Override
    public IStatus validate(final Object value) {
      final String s = ((String) value).trim(); // Project names are
      // always stripped of
      // whitespace (see the
      // Java Project Wizard)
      if ((s == null) || (s.length() == 0)) {
        return ValidationStatus.error("Enter a SAD file.");
      }
      final File sadFile = new File(s);
      if (!sadFile.exists()) {
        return ValidationStatus.error("SAD file does not exist.");
      }

      final URI fileURI = URI.createFileURI(sadFile.getAbsolutePath());
      try {
        final SoftwareAssembly sad = ModelUtil.loadSoftwareAssembly(fileURI);
        if (sad == null) {
          return ValidationStatus.error("Invalid SAD file selected.");
        }
      } catch (final Exception e) { // SUPPRESS CHECKSTYLE Logged Error
        return ValidationStatus.error("Unable to parse SAD file.");
      }

      return ValidationStatus.ok();
    }
  @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);
  }
Exemplo n.º 8
0
 /**
  * Allows user to select file and loads it as a model.
  *
  * @generated
  */
 public static Resource openModel(
     Shell shell, String description, TransactionalEditingDomain editingDomain) {
   FileDialog fileDialog = new FileDialog(shell, SWT.OPEN);
   if (description != null) {
     fileDialog.setText(description);
   }
   fileDialog.open();
   String fileName = fileDialog.getFileName();
   if (fileName == null || fileName.length() == 0) {
     return null;
   }
   if (fileDialog.getFilterPath() != null) {
     fileName = fileDialog.getFilterPath() + File.separator + fileName;
   }
   URI uri = URI.createFileURI(fileName);
   Resource resource = null;
   try {
     resource = editingDomain.getResourceSet().getResource(uri, true);
   } catch (WrappedException we) {
     RoxgtDiagramEditorPlugin.getInstance()
         .logError("Unable to load resource: " + uri, we); // $NON-NLS-1$
     MessageDialog.openError(
         shell,
         Messages.RoxgtDiagramEditorUtil_OpenModelResourceErrorDialogTitle,
         NLS.bind(Messages.RoxgtDiagramEditorUtil_OpenModelResourceErrorDialogMessage, fileName));
   }
   return resource;
 }
  @BeforeClass
  public static void setUpBeforeClass() throws Exception {
    File projectDir = new File("");
    testFileDir = new File(projectDir.getAbsolutePath(), "files");

    // init
    BPELPlugin bpelPlugin = new BPELPlugin();
    Resource.Factory.Registry.INSTANCE
        .getExtensionToFactoryMap()
        .put("bpel", new BPELResourceFactoryImpl());
    Resource.Factory.Registry.INSTANCE
        .getExtensionToFactoryMap()
        .put("wsdl", new WSDLResourceFactoryImpl());
    Resource.Factory.Registry.INSTANCE
        .getExtensionToFactoryMap()
        .put("xsd", new XSDResourceFactoryImpl());

    // load bpel resource
    ResourceSet resourceSet = new ResourceSetImpl();
    URI uri =
        URI.createFileURI(
            testFileDir.getAbsolutePath()
                + "\\OrderInfoSimple3\\bpelContent\\OrderingProcessSimple3.bpel");
    Resource resource = resourceSet.getResource(uri, true);
    process = (Process) resource.getContents().get(0);

    // analyse
    analysis = de.uni_stuttgart.iaas.bpel_d.algorithm.analysis.Process.analyzeProcessModel(process);
  }
Exemplo n.º 10
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;
   }
 }
 private SoftPkg getSoftPkg(final IProject project) {
   final ResourceSet set = ScaResourceFactoryUtil.createResourceSet();
   final IFile softPkgFile = project.getFile(project.getName() + ".spd.xml");
   final Resource resource =
       set.getResource(URI.createFileURI(softPkgFile.getLocation().toString()), true);
   return SoftPkg.Util.getSoftPkg(resource);
 }
 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());
 }
Exemplo n.º 13
0
  // this method is used to generate source-code based on the Java model as input.
  public void generate() throws IOException {

    XMIResourceFactoryImpl xmiResourceFactoryImpl =
        new XMIResourceFactoryImpl() {
          public Resource createResource(URI uri) {
            XMIResource xmiResource = new XMIResourceImpl(uri);
            return xmiResource;
          }
        };

    Resource.Factory.Registry.INSTANCE
        .getExtensionToFactoryMap()
        .put("xmi", xmiResourceFactoryImpl);

    // TesteModisco.javaxmi

    // Generate_JavaStructures jcva = new Generate_JavaStructures(modelURI, targetFolder, arguments)

    GenerateJavaExtended javaGenerator =
        new GenerateJavaExtended(
            URI.createFileURI(
                "/Users/rafaeldurelli/Documents/workspace/GeneratingJavaFromJavaModel/website/novo/TESTEValter/JavaModelRefactoring.javaxmi"),
            new File("/Users/rafaeldurelli/Desktop/src/codigoGerado"),
            new ArrayList<Object>());

    // Generate_JavaStructures javaGenerator = new Generate_JavaStructures(
    // URI.createFileURI("/Users/rafaeldurelli/Documents/workspaceMODISCO/TesteGeneralization/website/TesteModisco.javaxmi"),
    // new File("/Users/rafaeldurelli/Desktop/src/codigoGerado"), new ArrayList<Object>());

    System.out.println("Esta gerando...");
    javaGenerator.doGenerate(null);
    System.out.println("Gerou");
  }
  @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("-----------------------------------------------------");
  }
Exemplo n.º 15
0
  public static void createPatchFromXML(String newFilePath, String patchFile, String newFileName)
      throws IOException {
    Resource.Factory.Registry reg = Resource.Factory.Registry.INSTANCE;
    Map<String, Object> m = reg.getExtensionToFactoryMap();
    m.put(".sgd", new SoundgatesFactoryImpl());

    Patch patch = getPatchXML(patchFile);

    if (patch != null) {
      ResourceSet resSet = new ResourceSetImpl();
      Resource resource = resSet.createResource(URI.createFileURI(newFilePath));
      resource.getContents().add(patch);

      Diagram diag =
          ViewService.createDiagram(
              patch,
              PatchEditPart.MODEL_ID,
              SoundgatesDiagramEditorPlugin.DIAGRAM_PREFERENCES_HINT);

      resource.getContents().add(diag);

      resource.save(Collections.EMPTY_MAP);

      MessageDialogs.patchtWasImported(newFileName);
    }
  }
Exemplo n.º 16
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));
  }
Exemplo n.º 17
0
 /**
  * Opens the editors for the files selected using the file dialog.
  * <!-- begin-user-doc -->
  * <!-- end-user-doc -->
  *
  * @generated
  */
 @Override
 public void run(IAction action) {
   String[] filePaths = openFilePathDialog(getWindow().getShell(), SWT.OPEN, null);
   if (filePaths.length > 0) {
     openEditor(getWindow().getWorkbench(), URI.createFileURI(filePaths[0]));
   }
 }
 /**
  *
  * <!-- begin-user-doc -->
  * <!-- end-user-doc -->
  *
  * @generated
  */
 public URI getFileURI() {
   try {
     return URI.createFileURI(fileField.getText());
   } catch (Exception exception) {
     // Ignore
   }
   return null;
 }
Exemplo n.º 19
0
 @Override
 protected void readTableOfContents(File tocFile) throws IOException {
   ResourceSet resourceSet = new ResourceSetImpl();
   URI fileURI = URI.createFileURI(tocFile.getAbsolutePath());
   Resource resource = resourceSet.createResource(fileURI);
   resource.load(null);
   ncxTOC = (Ncx) resource.getContents().get(0);
 }
 public static void main(String[] args) {
   ResourceSet resourceSet = new ResourceSetImpl();
   Resource resource =
       resourceSet.createResource(URI.createFileURI("pathToPropJavaFile.propjava"));
   if (resource instanceof PropjavaResource) {
     new PropertiesJavaPostProcessor().process((PropjavaResource) resource);
   }
 }
Exemplo n.º 21
0
 public static Resource createComponentCacheResource(String installLocation) {
   String filePath =
       ComponentManager.TALEND_COMPONENT_CACHE
           + LanguageManager.getCurrentLanguage().toString().toLowerCase()
           + ComponentManager.TALEND_FILE_NAME;
   URI uri = URI.createFileURI(installLocation).appendSegment(filePath);
   ComponentCacheResourceFactoryImpl compFact = new ComponentCacheResourceFactoryImpl();
   return compFact.createResource(uri);
 }
  /** Add the specified list any external resource for this EReference feature */
  protected void processReferenceValue(
      final Resource eResource,
      final EObject eObject,
      final EReference eReference,
      final EObject value,
      final List externalResources,
      final Set unresolvedResourceURIs) {
    if (value == null) {
      return;
    }

    // Check if the object is an EMF proxy ...
    if (value.eIsProxy()) {
      if (value instanceof InternalEObject) {
        final InternalEObject iObject = (InternalEObject) value;
        final URI proxyUri = iObject.eProxyURI();
        CoreArgCheck.isNotNull(proxyUri);

        // Get the URI of the resource ...
        URI resourceUri = proxyUri.trimFragment();

        // Make the relative URI absolute if necessary
        URI baseLocationUri = eResource.getURI();
        URI proxyLocationUri = UriHelper.makeAbsoluteUri(baseLocationUri, resourceUri);
        // URI proxyLocationUri = resourceUri;
        // if (baseLocationUri.isHierarchical() && !baseLocationUri.isRelative() &&
        // proxyUri.isRelative()) {
        // proxyLocationUri = proxyLocationUri.resolve(baseLocationUri);
        // }
        Resource rsrc = findByURI(proxyLocationUri, true);

        // If the resource URI is a workspace relative path (e.g. "/project/.../model.xmi")
        if (rsrc == null && baseLocationUri.isFile() && resourceUri.toString().charAt(0) == '/') {
          String baseLocation = URI.decode(baseLocationUri.toFileString());
          String projectName = resourceUri.segment(0);
          String proxyLocation = URI.decode(resourceUri.toString());
          int index = baseLocation.indexOf(projectName);
          if (index != -1) {
            proxyLocation = baseLocation.substring(0, index - 1) + proxyLocation;
            rsrc = findByURI(URI.createFileURI(proxyLocation), true);
          }
        }

        if (rsrc != null && eResource != rsrc && !externalResources.contains(rsrc)) {
          externalResources.add(rsrc);
        } else if (rsrc == null) {
          unresolvedResourceURIs.add(resourceUri);
        }
      }
    } else {
      Resource rsrc = value.eResource();
      if (eResource != rsrc && !externalResources.contains(rsrc)) {
        externalResources.add(rsrc);
      }
    }
  }
Exemplo n.º 23
0
  @Override
  protected void setUp() {
    super.setUp();

    instanceResource = resourceSet.createResource(URI.createFileURI("/tmp/instances.uml"));

    instancePackage = umlf.createPackage();
    instancePackage.setName("instances");
    instanceResource.getContents().add(instancePackage);
  }
 /**
  * {@inheritDoc}
  *
  * @see
  *     org.eclipse.acceleo.parser.compiler.AbstractAcceleoCompiler#computeDependencies(java.util.List,
  *     java.util.Map)
  */
 protected void computeDependencies(List<URI> dependenciesURIs, Map<URI, URI> mapURIs) {
   // USED TO FIX COMPILER WITH TYCHO
   Iterator<String> identifiersIt = dependenciesIDs.iterator();
   for (Iterator<File> dependenciesIt = dependencies.iterator();
       dependenciesIt.hasNext() && identifiersIt.hasNext(); ) {
     File requiredFolder = dependenciesIt.next();
     String identifier = identifiersIt.next();
     if (requiredFolder != null && requiredFolder.exists() && requiredFolder.isDirectory()) {
       List<File> emtlFiles = new ArrayList<File>();
       members(emtlFiles, requiredFolder, IAcceleoConstants.EMTL_FILE_EXTENSION);
       for (File emtlFile : emtlFiles) {
         String requiredFolderAbsolutePath = requiredFolder.getAbsolutePath();
         if (requiredFolderAbsolutePath.endsWith("target/classes")) {
           // using tycho
           String[] splited = requiredFolderAbsolutePath.split("\\/");
           StringBuffer buf = new StringBuffer(requiredFolderAbsolutePath.length());
           for (int i = 0; i < splited.length - 3; i++) {
             buf.append(splited[i]);
             buf.append("/");
           }
           requiredFolderAbsolutePath = buf.toString();
           String emtlAbsolutePath = emtlFile.getAbsolutePath();
           URI emtlFileURI = URI.createFileURI(emtlAbsolutePath);
           dependenciesURIs.add(emtlFileURI);
           String emtlModifiedPath = emtlAbsolutePath.replaceAll("target\\/|classes\\/", "");
           IPath relativePath =
               new Path(emtlModifiedPath.substring(requiredFolderAbsolutePath.length()));
           URI relativeURI = URI.createPlatformPluginURI(relativePath.toString(), false);
           mapURIs.put(emtlFileURI, relativeURI);
         } else {
           // normal behavior
           String emtlAbsolutePath = emtlFile.getAbsolutePath();
           URI emtlFileURI = URI.createFileURI(emtlAbsolutePath);
           dependenciesURIs.add(emtlFileURI);
           IPath relativePath =
               new Path(identifier)
                   .append(emtlAbsolutePath.substring(requiredFolderAbsolutePath.length()));
           mapURIs.put(emtlFileURI, URI.createPlatformPluginURI(relativePath.toString(), false));
         }
       }
     }
   }
 }
 /**
  *
  * <!-- begin-user-doc -->
  * <!-- end-user-doc -->
  *
  * @see junit.framework.TestCase#setUp()
  */
 @Override
 protected void setUp() throws Exception {
   TstGeneral.activateTracer();
   String baseDir = System.getProperty("java.io.tmpdir");
   if (!baseDir.endsWith(File.separator)) {
     baseDir = baseDir + File.separator;
   }
   fRootTestDir = new File(baseDir + fGroupPathStr + File.separator);
   fGroupPath = URI.createFileURI(fRootTestDir.getAbsolutePath());
 }
 private static void saveRestartFile(File file, Annotation annotation) {
   try {
     Resource resource =
         SetupCoreUtil.createResourceSet().createResource(URI.createFileURI(file.toString()));
     resource.getContents().add(annotation);
     resource.save(null);
   } catch (Exception ex) {
     // Ignore
   }
 }
 /** @generated */
 public void run(IAction action) {
   FileDialog fileDialog = new FileDialog(getWindow().getShell(), SWT.OPEN);
   fileDialog.open();
   if (fileDialog.getFileName() != null && fileDialog.getFileName().length() > 0) {
     openEditor(
         getWindow().getWorkbench(),
         URI.createFileURI(
             fileDialog.getFilterPath() + File.separator + fileDialog.getFileName()));
   }
 }
  private RepositoryRegistry loadRepositories() {
    ResourceSet rset = new ResourceSetImpl();
    rset.getResourceFactoryRegistry()
        .getExtensionToFactoryMap()
        .put("xml", new XMLResourceFactoryImpl()); // $NON-NLS-1$

    File repositoriesFile =
        new File(
            Activator.getDefault().getStateLocation().toFile(), "repositories.xml"); // $NON-NLS-1$
    URI uri = URI.createFileURI(repositoriesFile.getAbsolutePath());
    Resource resource = rset.createResource(uri);

    if (storage != null) {
      try {
        InputStream input = storage.createInputStream();
        if (input != null) {
          try {
            resource.load(input, null);
          } finally {
            IOUtil.closeSilent(input);
          }
        }
      } catch (Exception e) {
        Activator.log.error(
            "Failed to load repository registry from custom storage.", //$NON-NLS-1$
            e);
      }
    } else {
      if (repositoriesFile.exists()) {
        try {
          resource.load(null);
        } catch (Exception e) {
          Activator.log.error(
              "Failed to load repository registry.", //$NON-NLS-1$
              e);
          // if there's any junk, clear it out
          resource.getContents().clear();
        }
      } else {
        resource = rset.createResource(uri);
      }
    }

    RepositoryRegistry result =
        (RepositoryRegistry)
            EcoreUtil.getObjectByType(
                resource.getContents(), RepositoriesPackage.Literals.REPOSITORY_REGISTRY);

    if (result == null) {
      result = RepositoriesFactory.eINSTANCE.createRepositoryRegistry();
      resource.getContents().add(result);
    }

    return result;
  }
Exemplo n.º 29
0
 public static Resource getXMLResource(String pathName) {
   try {
     ResourceSet resourceSet = createXMLResourceSet();
     URI uri = URI.createFileURI(pathName);
     Resource resource = resourceSet.getResource(uri, true);
     return resource;
   } catch (Exception ex) {
     logger.error("Problem while loading XML resource " + pathName, ex);
     return null;
   }
 }
Exemplo n.º 30
0
  @Test
  public void testLoad() throws Exception {
    if (!EMFPlugin.IS_ECLIPSE_RUNNING) return;

    try {
      new ResourceSetImpl().getResource(URI.createFileURI(getFilename()), true);
    } catch (WrappedException e) {
      if (e.exception() instanceof PackageNotFoundException) fail("Package not found during load.");
      throw e;
    }
  }