private void applyToServer(
      final ComponentSubscriber subscriber, final SyncInfo[] infos, IProgressMonitor monitor)
      throws InvocationTargetException, InterruptedException {
    if (Utils.isEmpty(infos)) {
      return;
    }

    logChange(infos, "server");

    WorkspaceModifyOperation operation =
        new WorkspaceModifyOperation() {
          @Override
          public void execute(IProgressMonitor monitor)
              throws InvocationTargetException, InterruptedException {
            if (monitor != null) {
              monitor.beginTask(OPERATION_TITLE, 4 * infos.length);
            }
            try {
              getSyncController().applyToServer(subscriber, infos, monitor);
            } catch (InterruptedException e) {
              logger.warn("Operation cancelled: " + e.getMessage());
            } catch (Exception e) {
              throw new InvocationTargetException(e);
            } finally {
              if (monitor != null) {
                monitor.done();
              }
            }
          }
        };

    // go!!!
    operation.run(monitor);
  }
  /*
   * (non-Javadoc)
   *
   * @see org.eclipse.jface.wizard.Wizard#performFinish()
   */
  @Override
  public boolean performFinish() {

    final String packageName = page.getPackageName();

    /* make sure the package does exist */
    if (packageName.length() > 0) {
      WorkspaceModifyOperation createPkg =
          new NewPackageCreationOperation(page.getSourceFolder(), packageName);

      try {
        createPkg.run(null);
      } catch (InvocationTargetException e) {
        e.printStackTrace();
        return false;
      } catch (InterruptedException e) {
        e.printStackTrace();
        return false;
      }
    }
    WorkspaceModifyOperation modifyOp =
        new NewFragmentCreationOperation(
            page.getSourceFolder(), packageName, page.getTypeName(), page.getFragmentKind());
    try {
      this.getContainer().run(false, false, modifyOp);
    } catch (InvocationTargetException e) {
      e.printStackTrace();
      return false;
    } catch (InterruptedException e) {
      e.printStackTrace();
      return false;
    }

    return true;
  }
예제 #3
0
  /** Selects and reveals the given offset and length in the given editor part. */
  public static void revealInEditor(IEditorPart editor, final int offset, final int length) {
    if (editor instanceof ITextEditor) {
      ((ITextEditor) editor).selectAndReveal(offset, length);
      return;
    }

    // Support for non-text editor - try IGotoMarker interface
    if (editor instanceof IGotoMarker) {
      final IEditorInput input = editor.getEditorInput();
      if (input instanceof IFileEditorInput) {
        final IGotoMarker gotoMarkerTarget = (IGotoMarker) editor;
        WorkspaceModifyOperation op =
            new WorkspaceModifyOperation() {
              @Override
              protected void execute(IProgressMonitor monitor) throws CoreException {
                IMarker marker = null;
                try {
                  marker = ((IFileEditorInput) input).getFile().createMarker(IMarker.TEXT);
                  marker.setAttribute(IMarker.CHAR_START, offset);
                  marker.setAttribute(IMarker.CHAR_END, offset + length);

                  gotoMarkerTarget.gotoMarker(marker);

                } finally {
                  if (marker != null) {
                    marker.delete();
                  }
                }
              }
            };

        try {
          op.run(null);
        } catch (InvocationTargetException ex) {
          // reveal failed
        } catch (InterruptedException e) {
          Assert.isTrue(false, "this operation can not be canceled"); // $NON-NLS-1$
        }
      }
      return;
    }

    /*
     * Workaround: send out a text selection XXX: Needs to be improved, see
     * https://bugs.eclipse.org/bugs/show_bug.cgi?id=32214
     */
    if (editor != null && editor.getEditorSite().getSelectionProvider() != null) {
      IEditorSite site = editor.getEditorSite();
      if (site == null) {
        return;
      }

      ISelectionProvider provider = editor.getEditorSite().getSelectionProvider();
      if (provider == null) {
        return;
      }

      provider.setSelection(new TextSelection(offset, length));
    }
  }
  private void create_device_project(
      final IPath projectPath,
      final String deviceType,
      final String lang,
      final String codegenId,
      final String templateId,
      final IProgressMonitor progressMonitor)
      throws CoreException {
    final SubMonitor monitor = SubMonitor.convert(progressMonitor, 1);

    final String projectName = projectPath.lastSegment();
    final java.net.URI locationURI = projectPath.toFile().toURI();

    final ICodeGeneratorDescriptor code_gen = findCodeGen(lang, codegenId);

    final ITemplateDesc template = findCodeGenTemplate(templateId, code_gen);

    // Create the implementation
    final SoftPkg spd = SpdFactory.eINSTANCE.createSoftPkg();
    final Implementation impl = SpdFactory.eINSTANCE.createImplementation();
    spd.getImplementation().add(impl);
    final ImplementationSettings settings = CodegenFactory.eINSTANCE.createImplementationSettings();

    initializeSoftPkg(lang, projectName, code_gen, template, spd, impl, settings);

    final WorkspaceModifyOperation operation =
        new WorkspaceModifyOperation() {

          @Override
          protected void execute(final IProgressMonitor progress_monitor)
              throws CoreException, InvocationTargetException, InterruptedException {
            final SubMonitor monitor = SubMonitor.convert(progress_monitor, 2);

            final IProject project =
                DeviceProjectCreator.createEmptyProject(
                    projectName, locationURI, monitor.newChild(1));

            DeviceProjectCreator.createDeviceFiles(
                project, spd.getName(), spd.getId(), "", deviceType, false, monitor.newChild(1));

            ProjectCreator.addImplementation(
                project, spd.getName(), impl, settings, monitor.newChild(1));

            // Setup the IDL Path
            ResourceUtils.createIdlLibraryResource(project, monitor.newChild(1));
          }
        };
    try {
      operation.run(monitor.newChild(1));
    } catch (final InvocationTargetException e) {
      throw new CoreException(
          new Status(
              IStatus.ERROR, CodegeneratorApplication.PLUGIN_ID, "Failure creating project", e));
    } catch (final InterruptedException e) {
      // pass
    }
  }
예제 #5
0
  public void open() {

    WorkspaceModifyOperation operation = createResourceOperationForEvent(eventFile);

    try {
      operation.run(null);
    } catch (InvocationTargetException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (InterruptedException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }

    EventClassesDefinitionDialog dialog =
        new EventClassesDefinitionDialog(new Shell(), eventResource);
    dialog.open();
  }
  private IProject openProject(final IPath projectPath) throws CoreException {
    final ResourceSet set = ScaResourceFactoryUtil.createResourceSet();
    final IProgressMonitor progressMonitor = new NullProgressMonitor();
    final IWorkspace workspace = ResourcesPlugin.getWorkspace();
    final IWorkspaceRoot root = workspace.getRoot();
    final IWorkspaceDescription description = workspace.getDescription();
    final File projectPathFile = projectPath.toFile();
    final IPath projectDescriptionPath = projectPath.append(".project");

    if (!projectPathFile.isDirectory()) {
      throw new IllegalStateException("Provided project path must be a directory");
    }

    if (!projectDescriptionPath.toFile().exists()) {
      throw new IllegalStateException("Provided project path must include .project file");
    }

    final IProjectDescription projDesc = workspace.loadProjectDescription(projectDescriptionPath);
    final IProject project = root.getProject(projDesc.getName());

    if (project.exists()) {
      // If the project exists, make sure that it is the same project the user requested
      // ...this should only happen if the user forced a workspace with -data
      // that already contained a project with the same name but different path
      // from the one provided on the command line
      if (!project.getLocation().equals(projectPath.makeAbsolute())) {
        throw new IllegalStateException(
            "Provided project path conflicts with existing project in workspace");
      }
    } else {
      // If the project doesn't exist in the workspace, create a linked project
      projDesc.setName(projDesc.getName());
      if (Platform.getLocation().isPrefixOf(projectPath)) {
        projDesc.setLocation(null);
      } else {
        projDesc.setLocation(projectPath);
      }

      final WorkspaceModifyOperation operation =
          new WorkspaceModifyOperation() {

            @Override
            protected void execute(final IProgressMonitor monitor)
                throws CoreException, InvocationTargetException, InterruptedException {

              final SubMonitor progressMonitor = SubMonitor.convert(monitor, 1);
              System.out.println(
                  "Loading project " + projDesc.getName() + " " + projDesc.getLocation());
              project.create(projDesc, progressMonitor.newChild(1));
            }
          };

      try {
        operation.run(new NullProgressMonitor());
      } catch (final InvocationTargetException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
      } catch (final InterruptedException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
      }
    }

    // Finally open the project
    Assert.isTrue(project.exists());

    final WorkspaceModifyOperation operation =
        new WorkspaceModifyOperation() {
          @Override
          protected void execute(final IProgressMonitor monitor)
              throws CoreException, InvocationTargetException, InterruptedException {
            project.open(monitor);
          }
        };

    try {
      operation.run(new NullProgressMonitor());
    } catch (final InvocationTargetException e1) {
      // TODO Auto-generated catch block
      e1.printStackTrace();
    } catch (final InterruptedException e1) {
      // TODO Auto-generated catch block
      e1.printStackTrace();
    }

    return project;
  }
  // TODO - turn this into an OSGi command
  private void generate_code(
      final String project_path,
      final String lang,
      String codegenId,
      final String templateId,
      final String[] preserveFiles,
      final NullProgressMonitor progressMonitor)
      throws CoreException {
    final SubMonitor monitor = SubMonitor.convert(progressMonitor, 2);

    final ResourceSet set = ScaResourceFactoryUtil.createResourceSet();

    final IPath projectPath = new Path(project_path);
    final IProject project = openProject(projectPath);
    final SoftPkg softPkg = getSoftPkg(project);

    if (softPkg == null) {
      throw new IllegalStateException("Could not load spd.xml for project");
    }

    // Create or open the existing settings
    final WaveDevSettings waveDev = getWaveDevSettings(set, softPkg, codegenId, templateId);
    if (waveDev == null) {
      throw new IllegalStateException("Could not load wavedev settings for project");
    }

    final EMap<String, ImplementationSettings> implSet = waveDev.getImplSettings();

    // Try generate each implementation, or just the specified language
    for (final Implementation impl : softPkg.getImplementation()) {
      final String currLang = impl.getProgrammingLanguage().getName();
      if ((lang != null) && !lang.equals(currLang.toLowerCase())) {
        continue;
      }

      // Prepare for generation
      final ImplementationSettings settings = implSet.get(impl.getId());
      final ArrayList<FileToCRCMap> crcMap = new ArrayList<FileToCRCMap>();

      System.out.println("\n\nGenerating " + currLang + " code for " + softPkg.getName());

      // Validate the settings name
      final String implName = CodegenFileHelper.safeGetImplementationName(impl, settings);
      if (!implName.equals(CodegenUtil.getValidName(implName))) {
        System.err.println("Invalid characters in implementation name for " + implName);
        continue;
      } else if (settings.getGeneratorId() != null) {
        // Find the desired code generator
        codegenId = settings.getGeneratorId();
        final ICodeGeneratorDescriptor codeGenDesc =
            RedhawkCodegenActivator.getCodeGeneratorsRegistry().findCodegen(codegenId);
        if (codeGenDesc == null) {
          System.err.println(
              "The code generator(" + codegenId + ") for this implementation could not be found.");
          continue;
        }
        // Get the actual code generator
        final IScaComponentCodegen generator = codeGenDesc.getGenerator();
        // Get files to generate
        final Set<FileStatus> fileStatusSet = generator.getGeneratedFilesStatus(settings, softPkg);
        final Set<String> fileList = new HashSet<String>();
        for (FileStatus s : fileStatusSet) {
          fileList.add(s.getFilename());
        }
        // Remove files we don't want to delete
        if (preserveFiles.length != 0) {
          if ("*".equals(preserveFiles[0])) {
            fileList.clear();
          } else {
            for (final String f : preserveFiles) {
              if (fileList.contains(f)) {
                fileList.remove(f);
              }
            }
          }
        }
        // Generate the files
        final IStatus status =
            generator.generate(
                settings,
                impl,
                System.out,
                System.err,
                monitor.newChild(1),
                fileList.toArray(new String[0]),
                generator.shouldGenerate(),
                crcMap);
        // Save the workspace
        final WorkspaceModifyOperation operation =
            new WorkspaceModifyOperation() {

              @Override
              protected void execute(final IProgressMonitor monitor)
                  throws CoreException, InvocationTargetException, InterruptedException {
                final IStatus saveStatus = ResourcesPlugin.getWorkspace().save(true, monitor);
                // Check the save results, hopefully this worked
                if (!saveStatus.isOK()) {
                  System.err.println(
                      "Generated files, but there was a problem saving the workspace: "
                          + saveStatus.getMessage());
                }
              }
            };
        try {
          operation.run(monitor.newChild(1));
        } catch (final InvocationTargetException e) {
          throw new CoreException(
              new Status(
                  IStatus.ERROR, CodegeneratorApplication.PLUGIN_ID, "Error saving resources", e));
        } catch (final InterruptedException e) {
          throw new CoreException(
              new Status(
                  IStatus.ERROR, CodegeneratorApplication.PLUGIN_ID, "Error saving resources", e));
        }

        // Check the results
        if (!status.isOK()) {
          System.err.println(
              "\nErrors occurred generating " + currLang + " code: " + status.getMessage());
          continue;
        } else {
          System.out.println("\nDone generating " + currLang + " code!");
        }
      } else {
        System.err.println(
            "No generator specified for implementation: " + implName + ". No code generated.");
      }
    }

    project.build(IncrementalProjectBuilder.FULL_BUILD, monitor.newChild(1));
  }
예제 #8
0
  /**
   * Process the EGit history associated with a given project.
   *
   * @param selectedProject selected project, presumably an object contribution selection
   * @throws CoreException
   * @throws IOException
   */
  public void processHistory(IProject selectedProject, IProgressMonitor monitor)
      throws CoreException, IOException {

    // find the repository mapping for the project
    // if none found, return
    RepositoryMapping repositoryMapping = RepositoryMapping.getMapping((IResource) selectedProject);
    if (repositoryMapping == null) {
      CertWareLog.logWarning(
          String.format("%s %s", "Missing repository for project", selectedProject.getName()));
      return;
    }

    // build the commit history model, load it from the tree walk
    final CommitHistory commitHistory = ScoFactory.eINSTANCE.createCommitHistory();
    Repository repo = repositoryMapping.getRepository();
    RevWalk revWalk = new RevWalk(repo);
    ObjectId headObject = repo.resolve("HEAD");
    revWalk.markStart(revWalk.parseCommit(headObject));

    final Set<String> repositoryPaths =
        Collections.singleton(repositoryMapping.getRepoRelativePath(selectedProject));
    revWalk.setTreeFilter(PathFilterGroup.createFromStrings(repositoryPaths));

    for (RevCommit commit : revWalk) {
      String commitName = commit.getName();
      ArtifactCommit artifactCommit = ScoFactory.eINSTANCE.createArtifactCommit();
      artifactCommit.setCommitIdentifier(commitName);
      commitHistory.getCommitRecord().add(artifactCommit);
    }

    revWalk.dispose();

    // use the Git provider to find the file history, then converge into the model
    GitProvider provider = (GitProvider) RepositoryProvider.getProvider(selectedProject);
    IFileHistoryProvider fileHistoryProvider = provider.getFileHistoryProvider();
    IResource[] projectMembers = selectedProject.members();

    monitor.beginTask("Processing project resources", projectMembers.length);
    for (IResource resource : projectMembers) {
      processResource(resource, fileHistoryProvider, commitHistory, monitor);
      monitor.worked(1);
      if (monitor.isCanceled()) {
        return;
      }
    }

    // model complete with commit history and associated file sizes
    // write the resulting model to an SCO file
    // expecting preference to have no extension, so add it if necessary
    IPreferenceStore store = Activator.getDefault().getPreferenceStore();
    String fileName = store.getString(PreferenceConstants.P_FILENAME_SCO);
    if (fileName.endsWith(ICertWareConstants.SCO_EXTENSION) == false) {
      fileName = fileName + '.' + ICertWareConstants.SCO_EXTENSION;
    }

    // fully specify the path to the new file given the container project
    final String modelFile =
        selectedProject.getFullPath().toPortableString() + IPath.SEPARATOR + fileName;

    // create the resource in a workspace modify operation
    WorkspaceModifyOperation operation =
        new WorkspaceModifyOperation() {
          @Override
          protected void execute(IProgressMonitor progressMonitor) {
            try {
              // create a resource set and resource for a new file
              ResourceSet resourceSet = new ResourceSetImpl();
              URI fileURI = URI.createPlatformResourceURI(modelFile, true);
              Resource resource = resourceSet.createResource(fileURI);
              resource.getContents().add(commitHistory);

              // save the contents of the resource to the file system
              Map<Object, Object> options = new HashMap<Object, Object>();
              options.put(XMLResource.OPTION_ENCODING, FILE_ENCODING);
              resource.save(options);
            } catch (Exception e) {
              CertWareLog.logError(String.format("%s %s", "Saving SCO file", modelFile), e);
            }
          }
        };

    // modify the workspace
    try {
      operation.run(monitor);
    } catch (Exception e) {
      CertWareLog.logError(
          String.format("%s %s", "Modifying workspace for", selectedProject.getName()), e);
    }

    monitor.done();
  }