/**
   * SIMPLY COPIED;
   *
   * @param diagram
   * @return
   */
  private IProject getProjectFromDiagram(Diagram diagram) {
    IProject currentProject = null;
    Resource resource = diagram.eResource();

    URI uri = resource.getURI();
    URI uriTrimmed = uri.trimFragment();

    if (uriTrimmed.isPlatformResource()) {
      String platformString = uriTrimmed.toPlatformString(true);
      IResource fileResource = ResourcesPlugin.getWorkspace().getRoot().findMember(platformString);

      if (fileResource != null) {
        currentProject = fileResource.getProject();
      }
    } else {
      IResource fileResource =
          ResourcesPlugin.getWorkspace().getRoot().findMember(uriTrimmed.toString());

      if (fileResource != null) {
        currentProject = fileResource.getProject();
      }
    }

    return currentProject;
  }
Example #2
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;
  }
 private static IResource getIResource(Resource r) {
   final URI uri = r.getURI();
   final IPath path = new Path(uri.toPlatformString(true));
   final IResource resource = ResourcesPlugin.getWorkspace().getRoot().findMember(path);
   if (resource == null) {
     throw new RuntimeException("Unable to get IResource for Resource: " + r);
   }
   return resource;
 }
 private String relative(String path) {
   path = substitute(path);
   URI sourceURI = source.eResource().getURI();
   URI result = URI.createURI(path).resolve(sourceURI);
   if (result.isFile()) {
     return result.path();
   } else if (result.isPlatformResource()) {
     return getFileFromProjectPath(result.toPlatformString(true));
   }
   return "";
 }
 /* @NonNull */
 @Override
 public Iterable<Pair<IStorage, IProject>> getStorages(/* @NonNull */ URI uri) {
   List<Pair<IStorage, IProject>> result = newArrayListWithCapacity(1);
   List<PackageFragmentRootData> packageFragmentRootDatas;
   synchronized (cachedPackageFragmentRootData) {
     packageFragmentRootDatas = newArrayList(cachedPackageFragmentRootData.values());
   }
   Iterator<PackageFragmentRootData> iterator = packageFragmentRootDatas.iterator();
   while (iterator.hasNext()) {
     PackageFragmentRootData data = iterator.next();
     if (data.exists()) {
       if (data.uriPrefix == null || uri.toString().startsWith(data.uriPrefix.toString())) {
         IStorage storage = data.uri2Storage.get(uri);
         if (storage != null) {
           for (IPackageFragmentRoot root : data.associatedRoots.values()) {
             result.add(Tuples.create(storage, root.getJavaProject().getProject()));
           }
         }
       }
     } else {
       iterator.remove();
     }
   }
   if (result.isEmpty() && uri.isArchive()) {
     String authority = uri.authority();
     authority = authority.substring(0, authority.length() - 1);
     URI archiveURI = URI.createURI(authority);
     if (archiveURI.isFile() || archiveURI.isPlatformResource()) {
       IPath archivePath =
           new Path(
               archiveURI.isPlatformResource()
                   ? archiveURI.toPlatformString(true)
                   : archiveURI.toFileString());
       for (PackageFragmentRootData data : packageFragmentRootDatas) {
         if (data.uriPrefix != null && archivePath.equals(data.getPath())) {
           // prefixes have an empty last segment.
           URI prefix =
               data.uriPrefix.lastSegment().length() == 0
                   ? data.uriPrefix.trimSegments(1)
                   : data.uriPrefix;
           URI expectedURI = prefix.appendSegments(uri.segments());
           IStorage storage = data.uri2Storage.get(expectedURI);
           if (storage != null) {
             for (IPackageFragmentRoot root : data.associatedRoots.values()) {
               result.add(Tuples.create(storage, root.getJavaProject().getProject()));
             }
           }
         }
       }
     }
   }
   return result;
 }
  public static IFile getFile(URI uri) {
    if (uri == null) {
      return null;
    }

    String platformString = uri.toPlatformString(true);
    if (platformString == null) {
      return null;
    }

    return ResourcesPlugin.getWorkspace().getRoot().getFile(new Path(platformString));
  }
Example #7
0
 public static void saveToModelFile(final EObject obj, final Diagram d)
     throws CoreException, IOException {
   URI uri = d.eResource().getURI();
   uri = uri.trimFragment();
   uri = uri.trimFileExtension();
   uri = uri.appendFileExtension("model");
   ResourceSet rSet = d.eResource().getResourceSet();
   final IWorkspaceRoot workspaceRoot = ResourcesPlugin.getWorkspace().getRoot();
   IResource file = workspaceRoot.findMember(uri.toPlatformString(true));
   if (file == null || !file.exists()) {
     Resource createResource = rSet.createResource(uri);
     createResource.save(new HashMap());
     createResource.setTrackingModification(true);
   }
   final Resource resource = rSet.getResource(uri, true);
   resource.getContents().add(obj);
 }
  @Override
  protected void generateGenFile(
      IWorkflowContext context, EcoreGenerator ecoreGenerator, URI genmodelURI) {
    // IProject           project      = (IProject) context.get(PROJECT);
    // IFile              genmodelFile = project.getRoot().getFile(genmodelFileString);
    IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
    IFile genmodelFile = root.getFile(new Path(genmodelURI.toPlatformString(true)));
    MarkerErrorHandler errorHandler = new MarkerErrorHandler(genmodelFile);

    deleteMarkers(genmodelFile);

    ecoreGenerator.addErrorHandler(errorHandler);

    super.generateGenFile(context, ecoreGenerator, genmodelURI);

    ecoreGenerator.removeErrorHandler(errorHandler);
  }
  @Override
  protected IResource createElementResource(IProgressMonitor monitor, IPath path) {
    try {

      if (monitor == null) {
        monitor = new NullProgressMonitor();
      }

      monitor.beginTask(Messages.NewMechanoidOpsFileWizard_Progress_Message, 1);

      URI newEmfResourceURI =
          URI.createURI(
              "platform:/resource"
                  + //$NON-NLS-1$
                  path.toPortableString());

      Resource emfResource = mResourceSet.createResource(newEmfResourceURI);

      Model model = OpServiceModelFactory.eINSTANCE.createModel();
      model.setPackageName(mSelectedPackageName);

      emfResource.getContents().add(model);

      ServiceBlock service = (ServiceBlock) OpServiceModelFactory.eINSTANCE.createServiceBlock();
      service.setName(mSelectedElementName);
      model.setService(service);

      emfResource.save(Collections.EMPTY_MAP);

      IResource resource =
          ResourcesPlugin.getWorkspace()
              .getRoot()
              .findMember(newEmfResourceURI.toPlatformString(true));

      monitor.worked(1);

      return resource;

    } catch (Exception e) {
      e.printStackTrace();
    }

    return null;
  }
 @Override
 public InputStream loadFile(Resource resource, String filename) {
   if (resource == null) return null;
   URI uri = resource.getURI();
   if (uri.isPlatformResource()) {
     IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
     IFile modelFile = root.getFile(new Path(uri.toPlatformString(false)));
     IContainer modelParent = modelFile.getParent();
     if (modelParent instanceof IFolder) {
       IFolder modelDir = (IFolder) modelParent;
       IFile file = modelDir.getFile(filename);
       try {
         return file.getContents();
       } catch (CoreException e) {
         LOGGER.warn("Can't handle file '" + filename + "': " + e.getMessage());
       }
     }
   }
   LOGGER.warn("Can't find file '" + filename + "' in project");
   return null;
 }
 private GenModel loadGenmodel(String resourceOrNsURI, ResourceSet resourceSet) {
   URI uri = null;
   try {
     uri = URI.createURI(resourceOrNsURI);
     if (uri.fragment() == null) {
       Resource resource = resourceSet.getResource(uri, true);
       return (GenModel) resource.getContents().get(0);
     }
     return (GenModel) resourceSet.getEObject(uri, true);
   } catch (IllegalArgumentException ex) {
     LOG.trace("Invalid package URI: '" + resourceOrNsURI + "'", ex);
     return null;
   } catch (RuntimeException ex) {
     if (uri != null && uri.isPlatformResource()) {
       String platformString = uri.toPlatformString(true);
       URI platformPluginURI = URI.createPlatformPluginURI(platformString, true);
       return loadGenmodel(platformPluginURI.toString(), resourceSet);
     }
     LOG.trace("Cannot load package with URI '" + resourceOrNsURI + "'", ex);
     return null;
   }
 }
  @Override
  public void complete_ImageExpression(
      EObject model,
      RuleCall ruleCall,
      ContentAssistContext context,
      ICompletionProposalAcceptor acceptor) {
    Resource res = model.eResource();
    URI uri = res.getURI().appendSegment("..").appendSegment("Images");

    String platformResourceString = uri.toPlatformString(true);
    IFolder folder =
        ResourcesPlugin.getWorkspace().getRoot().getFolder(new Path(platformResourceString));
    try {
      IResource[] members = folder.members();
      for (IResource member : members) {
        String proposal = getValueConverter().toString(member.getName(), "STRING");
        ICompletionProposal completionProposal = createCompletionProposal(proposal, context);
        acceptor.accept(completionProposal);
      }
    } catch (CoreException e) {
      log.error(e.getMessage(), e);
    }
  }
  public PlwebAddProductWizard(
      URI domainModelURI, DiagramRoot diagramRoot, TransactionalEditingDomain editingDomain) {
    assert domainModelURI != null : "Domain model uri must be specified"; // $NON-NLS-1$
    assert diagramRoot != null : "Doagram root element must be specified"; // $NON-NLS-1$
    assert editingDomain != null : "Editing domain must be specified"; // $NON-NLS-1$

    variativitySelectionPage =
        new VariativitySelectionPage(Messages.AddProduct_VariativityPageName);
    variativitySelectionPage.setTitle(Messages.AddProduct_VariativityPageName);
    variativitySelectionPage.setDescription(Messages.AddProduct_VariativityResolveItems);
    Area area = diagramRoot.getArea();
    variativitySelectionPage.setModelElement(area);
    variativitySelectionPage.setDiagram(diagramRoot);

    IWorkspace workspace = ResourcesPlugin.getWorkspace();
    IWorkspaceRoot root = workspace.getRoot();
    IPath location = root.getLocation();
    String resourcePath = domainModelURI.toPlatformString(true);
    filePath = location + (new Path(resourcePath)).toString();
    projectName = resourcePath.substring(1, resourcePath.indexOf("/", 1));

    myEditingDomain = editingDomain;
    this.diagramRoot = diagramRoot;
  }
 private File getFile(URI uri) {
   IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
   IFile f = root.getFile(new Path(uri.toPlatformString(true)));
   return f.getLocation().toFile();
 }
  @Override
  public Object execute(ExecutionEvent event) throws ExecutionException {
    if (generator == null) {
      throw new RuntimeException("Generator is null");
    }

    final IWorkbench wb = PlatformUI.getWorkbench();
    final IWorkbenchWindow window = wb.getActiveWorkbenchWindow();
    if (!Utils.checkOcarina(window)) {
      return null;
    }

    this.systemImplementation = SelectionHelper.getSelectedSystemImplementation();
    if (this.systemImplementation != null) {
      // Get the project that contains the system implementation
      final URI uri = systemImplementation.eResource().getURI();
      final IPath projectPath = new Path(uri.toPlatformString(true)).uptoSegment(1);
      final IResource projectResource =
          ResourcesPlugin.getWorkspace().getRoot().findMember(projectPath);
      this.ocarinaWorkingDirectory =
          new File(projectResource.getLocation().toFile(), "ocarina_out");
      this.ocarinaWorkingDirectory.mkdir();

      onBeforeStartJob();

      // Create a job to run the analysis
      Job job =
          new Job(jobName) {
            @Override
            protected IStatus run(IProgressMonitor monitor) {
              // Get the AADL source resources to use during the analysis
              sourceResources = getTransitiveClosure(systemImplementation);

              // Remove all markers from the source resources
              resetMarkers();

              // Launch Ocarina
              try {
                launchOcarina();
                handleOcarinaResults();
              } catch (InterruptedException e) {
                throw new RuntimeException("Interrupted");
              }

              // Refresh the project
              try {
                projectResource.refreshLocal(IResource.DEPTH_INFINITE, null);
              } catch (CoreException ex) {
                throw new RuntimeException(ex);
              }

              return Status.OK_STATUS;
            }
          };

      job.setPriority(Job.LONG);
      job.schedule();
    } else {
      MessageDialog.openError(
          window.getShell(),
          PreferenceConstants.PLUGIN_ID,
          "Please select a System Implementation");
    }

    return null;
  }