public static void BuildAndVerify(BoardDescriptor boardid) {

    IProject theTestProject = null;
    CodeDescriptor codeDescriptor = CodeDescriptor.createDefaultIno();
    NullProgressMonitor monitor = new NullProgressMonitor();
    String projectName = String.format("%03d_", new Integer(mCounter++)) + boardid.getBoardID();
    try {

      theTestProject =
          boardid.createProject(
              projectName,
              null,
              ConfigurationDescriptor.getDefaultDescriptors(),
              codeDescriptor,
              monitor);
      Shared.waitForAllJobsToFinish(); // for the indexer
    } catch (Exception e) {
      e.printStackTrace();
      fail("Failed to create the project:" + projectName);
      return;
    }
    try {
      theTestProject.build(IncrementalProjectBuilder.FULL_BUILD, monitor);
      if (Shared.hasBuildErrors(theTestProject)) {
        fail("Failed to compile the project:" + projectName + " build errors");
      }
    } catch (CoreException e) {
      e.printStackTrace();
      fail("Failed to compile the project:" + boardid.getBoardName() + " exception");
    }
  }
Example #2
0
  /**
   * Check if model version is changed and rebuild PHP projects if necessary.
   *
   * @see PHPCoreConstants.STRUCTURE_VERSION
   */
  private void rebuildProjects() {
    IEclipsePreferences preferences = InstanceScope.INSTANCE.getNode(ID);
    String modelVersion = preferences.get(PHPCoreConstants.STRUCTURE_VERSION_PREFERENCE, null);
    if (PHPCoreConstants.STRUCTURE_VERSION.equals(modelVersion)) {
      return;
    }

    preferences.put(
        PHPCoreConstants.STRUCTURE_VERSION_PREFERENCE, PHPCoreConstants.STRUCTURE_VERSION);
    try {
      preferences.flush();
    } catch (BackingStoreException e1) {
      Logger.logException(e1);
    }

    IWorkspace workspace = ResourcesPlugin.getWorkspace();
    IProject[] projects = workspace.getRoot().getProjects();
    if (workspace.isAutoBuilding()) {
      try {
        for (IProject project : projects) {
          if (PHPToolkitUtil.isPhpProject(project)) {
            project.build(IncrementalProjectBuilder.CLEAN_BUILD, null);
          }
        }
      } catch (CoreException e) {
        Logger.logException(e);
      }
    }
  }
  public void testBug148055() throws Exception {
    IProject project = createPredefinedProject("project.with.aop-ajc.xml.file"); // $NON-NLS-1$

    IResource xml = project.findMember("src/META-INF/aop-ajc.xml"); // $NON-NLS-1$
    assertNotNull("Couldn't find aop-ajc.xml file in project", xml); // $NON-NLS-1$
    assertTrue("aop-ajc.xml file doesn't exist: " + xml, xml.exists()); // $NON-NLS-1$
    File file = xml.getRawLocation().toFile();
    assertNotNull("Couldn't find aop-ajc.xml as a java.io.File", file); // $NON-NLS-1$
    assertTrue("aop-ajc.xml file doesn't exist: " + file, file.exists()); // $NON-NLS-1$

    boolean deleted = file.delete();
    assertTrue("Delete failed for file: " + file, deleted); // $NON-NLS-1$

    project.build(IncrementalProjectBuilder.FULL_BUILD, new NullProgressMonitor());
    assertTrue(
        "Regression of bug 148055: Should be no errors, but got " //$NON-NLS-1$
            + ((UIMessageHandler)
                    AspectJPlugin.getDefault()
                        .getCompilerFactory()
                        .getCompilerForProject(project)
                        .getMessageHandler())
                .getErrors(),
        ((UIMessageHandler)
                    AspectJPlugin.getDefault()
                        .getCompilerFactory()
                        .getCompilerForProject(project)
                        .getMessageHandler())
                .getErrors()
                .size()
            == 0);
  }
  // test that after a source folder is deleted, all
  // class files nd resources are removed from the
  // output folder
  public void testDeleteSourceFolder() throws Exception {
    IProject proj = createPredefinedProject("CopyDerived1");
    getWorkspace().build(IncrementalProjectBuilder.FULL_BUILD, null);

    IJavaProject jProj = JavaCore.create(proj);
    IClasspathEntry[] classpath = jProj.getRawClasspath();
    IClasspathEntry[] newClasspath = new IClasspathEntry[classpath.length - 1];

    // remove the classpath entry corresponding to src
    for (int i = 0, j = 0; i < classpath.length; i++, j++) {
      if (classpath[i].getPath().lastSegment().toString().equals("src")) {
        j--;
        continue;
      }
      newClasspath[j] = classpath[i];
    }

    jProj.setRawClasspath(newClasspath, true, null);

    proj.build(IncrementalProjectBuilder.FULL_BUILD, null);

    IFolder out = proj.getFolder("bin");
    checkFolderIsNotDerived(out, "");
    checkFileNoExist(out, "file.txt");
    checkFileNoExist(out, "Nothing.class");
    checkFileNoExist(out, "Nothing2.class");
    checkFolderNoExist(out, "package1");
    checkFileNoExist(out, "package1/file.txt");
    checkFileNoExist(out, "package1/Nothing.class");
    checkFileNoExist(out, "package1/Nothing2.class");
  }
  /** Tests a builder that requests deltas for closed and missing projects. */
  public void testRequestMissingProject() {
    // add builder and do an initial build to get the instance
    try {
      addBuilder(project1, DeltaVerifierBuilder.BUILDER_NAME);
      project1.build(IncrementalProjectBuilder.FULL_BUILD, getMonitor());
    } catch (CoreException e) {
      fail("1.0", e);
    }
    final DeltaVerifierBuilder builder = DeltaVerifierBuilder.getInstance();
    assertTrue("1.1", builder != null);
    // always check deltas for all projects
    final IProject[] allProjects = new IProject[] {project1, project2, project3, project4};
    try {
      project2.close(getMonitor());
      project3.delete(IResource.ALWAYS_DELETE_PROJECT_CONTENT, getMonitor());
    } catch (CoreException e1) {
      fail("1.99", e1);
    }
    builder.checkDeltas(allProjects);

    // modify a file in project1 to force an autobuild
    try {
      file1.setContents(getRandomContents(), IResource.NONE, getMonitor());
    } catch (CoreException e2) {
      fail("2.99", e2);
    }
  }
 public void testSetCompilerOptions() throws Exception {
   assertFalse(
       "project shouldn't have any error markers", //$NON-NLS-1$
       ProjectDependenciesUtils.projectIsMarkedWithError(project, null));
   AspectJPreferences.setCompilerOptions(project, "blah"); // $NON-NLS-1$
   project.build(IncrementalProjectBuilder.FULL_BUILD, null);
   waitForJobsToComplete();
   assertTrue(
       "build should fail because can't understand compiler options", //$NON-NLS-1$
       ProjectDependenciesUtils.projectIsMarkedWithError(project, null));
   AspectJPreferences.setCompilerOptions(project, ""); // $NON-NLS-1$
   project.build(IncrementalProjectBuilder.FULL_BUILD, null);
   waitForJobsToComplete();
   assertFalse(
       "project shouldn't have any error markers", //$NON-NLS-1$
       ProjectDependenciesUtils.projectIsMarkedWithError(project, null));
 }
  /**
   * Tests wiring validation.
   *
   * @throws Exception if a failure occurs.
   */
  public void testWiringValidation() throws Exception {
    IProject project = importProject("test-data/validator-tests/wiring-validation-tests/pom.xml");
    waitForJobsToComplete();

    project.build(IncrementalProjectBuilder.FULL_BUILD, monitor);
    waitForJobsToComplete();
    project.build(IncrementalProjectBuilder.INCREMENTAL_BUILD, monitor);
    waitForJobsToComplete();

    IFile switchYardFile = project.getFile("src/main/resources/META-INF/switchyard.xml");
    assertTrue("switchyard.xml does not exist.", switchYardFile != null && switchYardFile.exists());

    IMarker[] markers =
        switchYardFile.findMarkers(
            SwitchYardProjectValidator.SWITCHYARD_MARKER_ID, true, IFile.DEPTH_ZERO);
    int errorCount = 0;
    int warningCount = 0;
    int infoCount = 0;
    int unknownCount = 0;
    for (IMarker marker : markers) {
      switch (marker.getAttribute(IMarker.SEVERITY, -1)) {
        case IMarker.SEVERITY_ERROR:
          ++errorCount;
          break;
        case IMarker.SEVERITY_INFO:
          ++infoCount;
          break;
        case IMarker.SEVERITY_WARNING:
          ++warningCount;
          break;
        default:
          ++unknownCount;
          break;
      }
    }
    assertEquals("Expecting 14 errors: " + WorkspaceHelpers.toString(markers), 14, errorCount);
    assertEquals("Expecting 4 warnings: " + WorkspaceHelpers.toString(markers), 4, warningCount);
    assertEquals("Expecting 0 infos: " + WorkspaceHelpers.toString(markers), 0, infoCount);
    assertEquals(
        "Unexpected marker severity (not info, warning, error): "
            + WorkspaceHelpers.toString(markers),
        0,
        unknownCount);
  }
  /**
   * @throws JavaModelException
   * @throws CoreException
   */
  @Before
  public void setup() throws JavaModelException, CoreException {

    System.out.println(
        "Setup test project: "
            + ResourcesPlugin.getWorkspace().getRoot().getLocation().toOSString());

    //
    _project = ResourcesPlugin.getWorkspace().getRoot().getProject(DEFAULT_JDT_TEST_PROJECT_NAME);

    // create PDE project
    EclipseProjectUtils.createEclipsePluginProject(_project, getImportedPackages());

    //
    IFolder srcFolder = _project.getFolder("src");
    createTestSourceFiles(srcFolder);
    srcFolder.refreshLocal(IResource.DEPTH_INFINITE, null);

    //
    EclipseProjectUtils.enableDsAnnotationNature(_project);

    // TODO: Synchronize
    try {
      Thread.sleep(500);
    } catch (InterruptedException e) {
      // noop
    }

    // refresh and build
    _project.refreshLocal(IResource.DEPTH_INFINITE, null);
    try {
      _project.build(IncrementalProjectBuilder.CLEAN_BUILD, null);
      _project.build(IncrementalProjectBuilder.FULL_BUILD, null);
    } catch (Exception e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }

    //
    if (failOnErrors()) {
      EclipseProjectUtils.failOnErrors(_project);
    }
  }
  protected void setUp() throws Exception {
    super.setUp();
    origFactory = AspectJPlugin.getDefault().getCompilerFactory();
    AspectJPlugin.getDefault().setCompilerFactory(new MockCompilerFactory());

    Utils.setAutobuilding(true);

    proj2 = createPredefinedProject("ExportAsJar");
    AspectJCorePreferences.setProjectOutJar(proj2, "export.jar");
    proj2.build(IncrementalProjectBuilder.FULL_BUILD, null);
    proj1 = createPredefinedProject("JarOnInpath");
    waitForAutoBuild();
  }
  /**
   * @param project
   * @throws CoreException
   * @throws InterruptedException
   * @throws Exception
   */
  protected void assertConvertsAndBuilds(IProject project)
      throws CoreException, InterruptedException, Exception {
    // Convert the project to a Maven project (generates pom.xml, enables Maven nature)
    convert(project);

    // Checks the generated pom.xml is identical to /<projectName>/expectedPom.xml
    verifyGeneratedPom(project);

    // Checks the Maven project builds without errors
    project.build(IncrementalProjectBuilder.FULL_BUILD, monitor);
    waitForJobsToComplete();
    assertNoErrors(project);
  }
  public void testPropertiesSubstitution() throws Exception {
    IProject p1 = createExisting("t019-p1");
    waitForJobsToComplete();

    p1.build(IncrementalProjectBuilder.FULL_BUILD, monitor);

    IMavenProjectFacade f1 = manager.create(p1, monitor);
    MavenProject m1 = f1.getMavenProject(monitor);

    assertEquals("t019-p1", m1.getArtifactId());
    assertEquals("1.0.0-SNAPSHOT", m1.getVersion());
    assertEquals("plain description", m1.getDescription());
  }
  private void executeResolutions(List<QuickFixTestPackage> packages, String testResource)
      throws CoreException {
    // Some resolutions can be ignored. One example is a detector that has one or more sometimes
    // applicable quickfixes, but occasionally none apply. These are useful to include in the
    // test cases (e.g. DeadLocalStoreBugs.java), and need to be properly handled.
    // we keep a count of the ignored resolutions (QuickFixTestPackage.IGNORE_FIX) and correct
    // our progress using that
    int ignoredResolutions = 0;
    int pendingBogoFixes = 0;
    boolean skipNextScan = true;
    for (int resolutionsCompleted = 0;
        resolutionsCompleted < packages.size();
        resolutionsCompleted++) {

      if (!skipNextScan) { // Refresh, rebuild, and scan for bugs again
        // We only need to do this after the first time, as we expect the file to have
        // been scanned and checked for consistency (see checkBugsAndPerformResolution)
        testIProject.refreshLocal(IResource.DEPTH_ONE, null);
        testIProject.build(IncrementalProjectBuilder.FULL_BUILD, null);
        clearMarkersAndBugs();
        scanUntilMarkers(testResource);
      }
      skipNextScan = false;

      System.out.println(resolutionsCompleted);

      IMarker[] markers = getSortedMarkersFromFile(testResource);

      assertEquals(
          "Bug marker number was different than anticipated.  "
              + "Check to see if another bug marker was introduced by fixing another.",
          packages.size() - (resolutionsCompleted),
          markers.length - ignoredResolutions - pendingBogoFixes);

      IMarker nextNonIgnoredMarker =
          markers[
              ignoredResolutions
                  + pendingBogoFixes]; // Bug markers we ignore float to the "top" of the stack
      // ignoredResolutions can act as an index for that

      QuickFixTestPackage p = packages.get(resolutionsCompleted);
      skipNextScan = !performResolution(p, nextNonIgnoredMarker);
      if (p.resolutionToExecute == QuickFixTestPackage.IGNORE_FIX) {
        ignoredResolutions++;
      } else if (p.resolutionToExecute == QuickFixTestPackage.FIXED_BY_ANOTHER_FIX) {
        pendingBogoFixes++;
      } else {
        pendingBogoFixes = 0;
      }
    }
  }
 public void testMarkersAreAdded() throws Exception {
   myProject.build(IncrementalProjectBuilder.FULL_BUILD, new NullProgressMonitor());
   SynchronizationUtils.joinBackgroudActivities();
   assertEquals(
       "Simple AJ Project should contain 2 advice markers after building",
       2,
       myProject.findMarkers(IAJModelMarker.ADVICE_MARKER, true, IResource.DEPTH_INFINITE)
           .length); //$NON-NLS-1$
   assertEquals(
       "Simple AJ Project should contain 2 source advice markers after building",
       2,
       myProject.findMarkers(IAJModelMarker.SOURCE_ADVICE_MARKER, true, IResource.DEPTH_INFINITE)
           .length); //$NON-NLS-1$
 }
 @Override
 protected IStatus run(IProgressMonitor monitor) {
   try {
     IProgressMonitor sub = SubMonitor.convert(monitor, projects.length);
     for (IProject project : projects) {
       project.build(IncrementalProjectBuilder.FULL_BUILD, sub);
       sub.worked(1);
     }
     return Status.OK_STATUS;
   } catch (CoreException e) {
     GroovyCore.logException("Error building groovy project", e);
     return e.getStatus();
   } finally {
     monitor.done();
   }
 }
  /**
   * Executes a rebuild of the Project.
   *
   * @param editor
   * @param monitor
   */
  private void execute(EditorState editor, IProgressMonitor monitor) {
    // rebuild the project
    IProject project = this.observer.getProject();
    if (project != null) {
      int kind = IncrementalProjectBuilder.INCREMENTAL_BUILD;
      // int kind = IncrementalProjectBuilder.FULL_BUILD;

      // IProgressMonitor monitor = null;
      try {
        project.build(kind, monitor);
      } catch (CoreException e) {
        Environment.logException(e.getMessage());
        openError(editor, e.getMessage());
      }
    }
  }
  /** This test disabled until https://issues.sonatype.org/browse/MNGECLIPSE-1448 is resolved */
  public void _testExtensionPluginResolution() throws Exception {
    IProject p1 = createExisting("MNGECLIPSE380-plugin", "resources/MNGECLIPSE380/plugin");
    IProject p2 = createExisting("MNGECLIPSE380-project", "resources/MNGECLIPSE380/project");
    waitForJobsToComplete();

    p1.build(IncrementalProjectBuilder.FULL_BUILD, monitor);

    IFile pom2 = p2.getFile("pom.xml");
    assertNotNull(manager.create(pom2, false, null));

    deleteProject(p1);
    waitForJobsToComplete();
    assertNull(manager.create(pom2, false, null));

    assertNotNull(manager.create(pom2, false, null));
  }
Example #17
0
  /**
   * Creates test file with the specified content and calculates the offset at OFFSET_CHAR. Offset
   * character itself is stripped off.
   *
   * @param data File data
   * @return offset where's the offset character set.
   * @throws Exception
   */
  protected int createFile(String data) throws Exception {
    int offset = data.lastIndexOf(OFFSET_CHAR);
    if (offset == -1) {
      throw new IllegalArgumentException("Offset character is not set");
    }

    // replace the offset character
    data = data.substring(0, offset) + data.substring(offset + 1);

    testFile = project.getFile("pdttest/test.php");
    testFile.create(new ByteArrayInputStream(data.getBytes()), true, null);
    project.refreshLocal(IResource.DEPTH_ONE, null);
    project.build(IncrementalProjectBuilder.INCREMENTAL_BUILD, null);

    TestUtils.waitForIndexer();

    return offset;
  }
  /**
   * Replace the project pom.xml with a new one, triggers new build, wait for waitTime milliseconds.
   *
   * @param project
   * @param newPomName
   * @param waitTime
   * @throws Exception
   */
  protected void updateProject(IProject project, String newPomName, int waitTime) throws Exception {

    if (newPomName != null) {
      copyContent(project, newPomName, "pom.xml");
    }

    IProjectConfigurationManager configurationManager =
        MavenPlugin.getDefault().getProjectConfigurationManager();
    ResolverConfiguration configuration = new ResolverConfiguration();
    configurationManager.enableMavenNature(project, configuration, monitor);
    configurationManager.updateProjectConfiguration(project, monitor);

    waitForJobsToComplete();
    project.build(IncrementalProjectBuilder.FULL_BUILD, monitor);
    if (waitTime > 0) {
      Thread.sleep(waitTime);
    }
    waitForJobsToComplete();
  }
  /** Test for Bug #5102. Never reproduced but interesting little test, worth keeping around */
  public void testPR() throws Exception {
    // create a project with a RefreshLocalJavaFileBuilder and a SortBuilder on the classpath
    IProject project = getWorkspace().getRoot().getProject("P1");
    project.create(null);
    project.open(null);
    IProjectDescription desc = project.getDescription();
    ICommand one = desc.newCommand();
    one.setBuilderName(RefreshLocalJavaFileBuilder.BUILDER_NAME);
    ICommand two = desc.newCommand();
    two.setBuilderName(SortBuilder.BUILDER_NAME);
    desc.setBuildSpec(new ICommand[] {one, two});
    project.setDescription(desc, null);

    // do a full build
    project.build(IncrementalProjectBuilder.FULL_BUILD, null);

    // do an incremental build by creating a file
    IFile file = project.getFile("Foo");
    file.create(getRandomContents(), true, getMonitor());
  }
Example #20
0
 @Override
 protected IStatus run(IProgressMonitor monitor) {
   synchronized (getClass()) {
     if (monitor.isCanceled()) {
       return Status.CANCEL_STATUS;
     }
     Job[] buildJobs = Job.getJobManager().find(ResourcesPlugin.FAMILY_MANUAL_BUILD);
     for (int i = 0; i < buildJobs.length; i++) {
       Job curr = buildJobs[i];
       if (curr != this && curr instanceof BuildJob) {
         BuildJob job = (BuildJob) curr;
         if (job.isCoveredBy(this)) {
           curr.cancel(); // cancel all other build jobs of
           // our kind
         }
       }
     }
   }
   try {
     if (fProject != null) {
       monitor.beginTask(
           Messages.format(DLTKUIMessages.CoreUtility_buildproject_taskname, fProject.getName()),
           2);
       fProject.build(IncrementalProjectBuilder.FULL_BUILD, new SubProgressMonitor(monitor, 1));
       DLTKUIPlugin.getWorkspace()
           .build(
               IncrementalProjectBuilder.INCREMENTAL_BUILD, new SubProgressMonitor(monitor, 1));
     } else {
       monitor.beginTask(DLTKUIMessages.CoreUtility_buildall_taskname, 2);
       DLTKUIPlugin.getWorkspace()
           .build(IncrementalProjectBuilder.FULL_BUILD, new SubProgressMonitor(monitor, 2));
     }
   } catch (CoreException e) {
     return e.getStatus();
   } catch (OperationCanceledException e) {
     return Status.CANCEL_STATUS;
   } finally {
     monitor.done();
   }
   return Status.OK_STATUS;
 }
  /**
   * Existing interceptor binding, taken from TCK, is annotated @Inherited @Target({TYPE}) If this
   * test fails, first check that the existing interceptor binding has not been moved or modified.
   * In the previous version, the result of testNewInterceptorBindingWizard() was used, but that
   * turned to be not safe, since the order of tests is not guaranteed.
   *
   * @throws CoreException
   */
  public void testNewInterceptorBindingWizardWithBinding() throws CoreException {
    IProject tck = ResourcesPlugin.getWorkspace().getRoot().getProject("tck");
    tck.build(IncrementalProjectBuilder.FULL_BUILD, new NullProgressMonitor());

    WizardContext context = new WizardContext();
    context.init(
        "org.jboss.tools.cdi.ui.wizard.NewInterceptorBindingCreationWizard",
        PACK_NAME,
        INTERCEPTOR_BINDING2_NAME);

    try {
      NewInterceptorBindingWizardPage page = (NewInterceptorBindingWizardPage) context.page;
      ICDIProject cdi = CDICorePlugin.getCDIProject(context.tck, true);
      IInterceptorBinding s =
          cdi.getInterceptorBinding(EXISTING_PACK_NAME + "." + EXISTING_INTERCEPTOR_BINDING_NAME);
      assertNotNull(s);

      page.addInterceptorBinding(s);
      String message = page.getErrorMessage();
      assertNull(message);
      message = page.getMessage();
      assertNotNull(message);
      int messageType = page.getMessageType();
      assertEquals(IMessageProvider.WARNING, messageType);
      String testmessage =
          NLS.bind(
              CDIUIMessages.MESSAGE_INTERCEPTOR_BINDING_IS_NOT_COMPATIBLE,
              s.getSourceType().getElementName());
      assertEquals(testmessage, message);

      page.setTarget("TYPE");

      message = page.getErrorMessage();
      assertNull(message);
      message = page.getMessage();
      assertNull(message);

    } finally {
      context.close();
    }
  }
  public static void loadFilesThatNeedFixing() throws CoreException, IOException {
    makeJavaProject();

    TestingUtils.copyBrokenFiles(
        testIProject.getFolder(SRC_FOLDER_NAME),
        new File("classesToFix/"),
        new File("mockLibraries/"));

    // Compiles the code
    testIProject.refreshLocal(IResource.DEPTH_INFINITE, null);
    testIProject.build(IncrementalProjectBuilder.FULL_BUILD, null);

    FindbugsPlugin.setProjectSettingsEnabled(testIProject, null, true);
    UserPreferences userPrefs = FindbugsPlugin.getUserPreferences(testIProject);
    // enables categories like Security, which are disabled by default
    userPrefs.getFilterSettings().clearAllCategories();

    checkFBContribInstalled();
    checkFindSecurityBugsInstalled();

    TestingUtils.waitForUiEvents(100);
  }
  /**
   * Creates test file with the specified content and calculates the source range for the selection.
   * Selection characters themself are stripped off.
   *
   * @param data File data
   * @return offset where's the offset character set.
   * @throws Exception
   */
  protected SourceRange createFile(String data) throws Exception {
    int left = data.indexOf(SELECTION_CHAR);
    if (left == -1) {
      throw new IllegalArgumentException("Selection characters are not set");
    }
    // replace the left character
    data = data.substring(0, left) + data.substring(left + 1);

    int right = data.indexOf(SELECTION_CHAR);
    if (right == -1) {
      throw new IllegalArgumentException("Selection is not closed");
    }
    data = data.substring(0, right) + data.substring(right + 1);

    testFile = project.getFile("pdttest/test.php");
    testFile.create(new ByteArrayInputStream(data.getBytes()), true, null);
    project.refreshLocal(IResource.DEPTH_ONE, null);

    project.build(IncrementalProjectBuilder.INCREMENTAL_BUILD, null);
    PHPCoreTests.waitForIndexer();

    return new SourceRange(left, right - left);
  }
Example #24
0
  /**
   * Creates the Acceleo project.
   *
   * @param monitor The progress monitor.
   */
  private void createProject(IProgressMonitor monitor) {
    try {
      IProject project =
          ResourcesPlugin.getWorkspace().getRoot().getProject(newProjectPage.getProjectName());
      IPath location = newProjectPage.getLocationPath();
      if (!project.exists()) {
        IProjectDescription desc =
            project.getWorkspace().newProjectDescription(newProjectPage.getProjectName());
        if (ResourcesPlugin.getWorkspace().getRoot().getLocation().equals(location)) {
          location = null;
        }
        desc.setLocation(location);
        project.create(desc, monitor);
        project.open(monitor);

        boolean shouldGenerateModules =
            !(getContainer().getCurrentPage() instanceof WizardNewProjectCreationPage);
        convert(
            project,
            newProjectPage.getSelectedJVM(),
            newAcceleoModulesCreationPage.getAllModules(),
            shouldGenerateModules,
            monitor);

        IWorkingSet[] workingSets = newProjectPage.getSelectedWorkingSets();
        getWorkbench().getWorkingSetManager().addToWorkingSets(project, workingSets);

        project.build(
            IncrementalProjectBuilder.FULL_BUILD,
            AcceleoBuilder.BUILDER_ID,
            new HashMap<String, String>(),
            monitor);
      }
    } catch (CoreException e) {
      AcceleoUIActivator.log(e, true);
    }
  }
  @Override
  protected IStatus run(IProgressMonitor monitor) {
    try {
      repairErroneousBuilderEntry(project);
      reorderBuilderEntries(project);

      final ImmutableList<String> newIDs =
          project.hasNature(ViatraQueryNature.NATURE_ID)
              ? ImmutableList.<String>of()
              : ImmutableList.of(ViatraQueryNature.NATURE_ID);
      Builder<String> builder = ImmutableList.<String>builder();
      for (String ID : MigratorConstants.INCORRECT_NATURE_IDS) {
        if (project.hasNature(ID)) {
          builder.add(ID);
        }
      }

      final ImmutableList<String> oldIDs = builder.build();

      if (newIDs.size() + oldIDs.size() > 0) {
        ProjectGenerationHelper.updateNatures(project, newIDs, oldIDs, monitor);
      }
      removeGlobalEiq(project);
      renamePatternDefinitionFiles(project);

      if (PDE.hasPluginNature(project)) {
        removeExpressionExtensions(project);
        ProjectGenerationHelper.ensurePackageImports(
            project, ImmutableList.<String>of("org.apache.log4j"));
      }
      project.build(IncrementalProjectBuilder.CLEAN_BUILD, monitor);
    } catch (CoreException e) {
      return new Status(
          IStatus.ERROR, ViatraQueryGUIPlugin.PLUGIN_ID, "Error updating project natures", e);
    }
    return Status.OK_STATUS;
  }
  // As above, but test that when root folder is out folder
  public void testCopyDerivedInRoot() throws Exception {
    IProject proj = createPredefinedProject("CopyDerived2");
    getWorkspace().build(IncrementalProjectBuilder.FULL_BUILD, null);

    checkFileIsNotDerived(proj, "file.txt");
    checkFileIsDerived(proj, "Nothing.class");
    checkFileIsDerived(proj, "Nothing2.class");
    checkFolderIsNotDerived(proj, "package1");
    checkFileIsNotDerived(proj, "package1/file.txt");
    checkFileIsDerived(proj, "package1/Nothing.class");
    checkFileIsDerived(proj, "package1/Nothing2.class");

    // should delete all binaries but leave all resources
    proj.build(IncrementalProjectBuilder.CLEAN_BUILD, null);

    checkProjectIsNotDerived(proj, "");
    checkFileIsNotDerived(proj, "file.txt");
    checkFileNoExist(proj, "Nothing1.class");
    checkFileNoExist(proj, "Nothing2.class");
    checkFolderIsNotDerived(proj, "package1");
    checkFileIsNotDerived(proj, "package1/file.txt");
    checkFileNoExist(proj, "package1/Nothing1.class");
    checkFileNoExist(proj, "package1/Nothing2.class");
  }
  // 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));
  }
  public void testCopyDerived() throws Exception {
    IProject proj = createPredefinedProject("CopyDerived1");
    getWorkspace().build(IncrementalProjectBuilder.FULL_BUILD, null);

    // all out folders were empty.
    // project was built when created
    // check all build artifacts to make sure that
    // they exist and are marked derived

    IFolder out = proj.getFolder("bin");
    checkFolderIsNotDerived(out, "");
    checkFileIsDerived(out, "file.txt");
    checkFileIsDerived(out, "Nothing.class");
    checkFileIsDerived(out, "Nothing2.class");
    checkFolderIsDerived(out, "package1");
    checkFileIsDerived(out, "package1/file.txt");
    checkFileIsDerived(out, "package1/Nothing.class");
    checkFileIsDerived(out, "package1/Nothing2.class");

    // deep out folder
    out = proj.getFolder("folder/bin2");
    checkFolderIsNotDerived(out, "");
    checkFileIsDerived(out, "file.txt");
    checkFileIsDerived(out, "Nothing3.class");
    checkFileIsDerived(out, "Nothing4.class");
    checkFolderIsDerived(out, "package1");
    checkFileIsDerived(out, "package1/file.txt");
    checkFileIsDerived(out, "package1/Nothing3.class");
    checkFileIsDerived(out, "package1/Nothing4.class");

    // binary folder == out folder
    out = proj.getFolder("src3");
    checkFolderIsNotDerived(out, "");
    checkFileIsNotDerived(out, "file.txt");
    checkFileIsDerived(out, "Nothing5.class");
    checkFileIsDerived(out, "Nothing6.class");
    checkFolderIsNotDerived(out, "package1");
    checkFileIsNotDerived(out, "package1/file.txt");
    checkFileIsDerived(out, "package1/Nothing5.class");
    checkFileIsDerived(out, "package1/Nothing6.class");

    // should delete all binaries and all resources
    // except for resources in source folder
    proj.build(IncrementalProjectBuilder.CLEAN_BUILD, null);

    out = proj.getFolder("bin");
    checkFolderIsNotDerived(out, "");
    checkFileNoExist(out, "file.txt");
    checkFileNoExist(out, "Nothing.class");
    checkFileNoExist(out, "Nothing2.class");
    checkFolderNoExist(out, "package1");
    checkFileNoExist(out, "package1/file.txt");
    checkFileNoExist(out, "package1/Nothing.class");
    checkFileNoExist(out, "package1/Nothing2.class");

    // deep out folder
    out = proj.getFolder("folder/bin2");
    checkFolderIsNotDerived(out, "");
    checkFileNoExist(out, "file.txt");
    checkFileNoExist(out, "Nothing3.class");
    checkFileNoExist(out, "Nothing4.class");
    checkFolderNoExist(out, "package1");
    checkFileNoExist(out, "package1/file.txt");
    checkFileNoExist(out, "package1/Nothing3.class");
    checkFileNoExist(out, "package1/Nothing4.class");

    // binary folder == out folder
    out = proj.getFolder("src3");
    checkFolderIsNotDerived(out, "");
    checkFileIsNotDerived(out, "file.txt");
    checkFileNoExist(out, "Nothing5.class");
    checkFileNoExist(out, "Nothing6.class");
    checkFolderIsNotDerived(out, "package1");
    checkFileIsNotDerived(out, "package1/file.txt");
    checkFileNoExist(out, "package1/Nothing5.class");
    checkFileNoExist(out, "package1/Nothing6.class");
  }
Example #29
0
 public static void invokeBuilderOn(final IErlProject erlProject) throws CoreException {
   final IProject project = erlProject.getWorkspaceProject();
   project.build(IncrementalProjectBuilder.FULL_BUILD, null);
 }
  public List<IResource> exportArtifact(IProject project) throws Exception {
    List<IResource> exportResources = new ArrayList<IResource>();
    List<String> exportedPackageList = new ArrayList<String>();
    List<String> importededPackageList = new ArrayList<String>();

    ArchiveManipulator archiveManipulator = new ArchiveManipulator();
    NullProgressMonitor nullProgressMonitor = new NullProgressMonitor();
    BundlesDataInfo bundleData = new BundlesDataInfo();
    IFile bundleDataFile = project.getFile("bundles-data.xml");
    File tempProject = createTempProject();
    File libResources = createTempDir(tempProject, "lib_resources");
    MavenProject mavenProject =
        MavenUtils.getMavenProject(project.getFile("pom.xml").getLocation().toFile());

    if (bundleDataFile.exists()) {
      bundleData.deserialize(bundleDataFile);

      for (String lib : bundleData.getExportedPackageListsFromJar().keySet()) {
        IFile JarFile = project.getFile(lib);
        if (JarFile.exists()) {
          archiveManipulator.extract(JarFile.getLocation().toFile(), libResources);
          exportedPackageList.addAll(bundleData.getExportedPackageListsFromJar().get(lib));
        }
      }
      for (IProject lib : bundleData.getExportedPackageListsFromProject().keySet()) {
        if (lib.isOpen()) {
          lib.build(IncrementalProjectBuilder.FULL_BUILD, nullProgressMonitor);
          IJavaProject javaLibProject = JavaCore.create(lib);
          for (IPackageFragment pkg : javaLibProject.getPackageFragments()) {
            if (pkg.getKind() == IPackageFragmentRoot.K_SOURCE) {
              if (pkg.hasChildren()) {
                exportedPackageList.add(pkg.getElementName());
              }
            }
          }

          IPath outPutPath = getOutputPath(javaLibProject);
          // get resource location
          IPath resources = getResourcePath(lib);

          FileUtils.copyDirectoryContents(outPutPath.toFile(), libResources);
          if (resources.toFile().exists()) {
            FileUtils.copyDirectoryContents(resources.toFile(), libResources);
          }
        }
      }
      getPackages(exportedPackageList, mavenProject, "Export-Package");
      getPackages(importededPackageList, mavenProject, "Import-Package");
      BundleManifest manifest = new BundleManifest();
      manifest.setBundleName(project.getName());
      manifest.setBundleSymbolicName(project.getName());
      if (null != mavenProject.getModel().getDescription()
          && !"".equals(mavenProject.getModel().getDescription())) {
        manifest.setBundleDescription(mavenProject.getModel().getDescription());
      } else {
        manifest.setBundleDescription(project.getName());
      }
      if (null != mavenProject.getModel().getVersion()
          && !"".equals(mavenProject.getDescription())) {
        manifest.setBundleVersion(mavenProject.getModel().getVersion());
      } else {
        manifest.setBundleVersion("1.0.0");
      }
      if (null != bundleData.getFragmentHost() && !"".equals(bundleData.getFragmentHost())) {
        manifest.setFragmentHost(bundleData.getFragmentHost());
      }
      manifest.setExportPackagesList(exportedPackageList);
      if (importededPackageList.size() > 0) {
        manifest.setImportPackagesList(importededPackageList);
        manifest.setDynamicImports(false);
      }
      File metaInfDir = new File(libResources, "META-INF");
      if (!metaInfDir.exists()) metaInfDir.mkdir();
      File manifestFile = new File(metaInfDir, "MANIFEST.MF");
      FileUtils.createFile(manifestFile, manifest.toString());

      File tmpArchive = new File(tempProject, project.getName().concat(".jar"));
      archiveManipulator.archiveDir(tmpArchive.toString(), libResources.toString());

      IFile libArchive = getTargetArchive(project, "jar");
      FileUtils.copy(tmpArchive, libArchive.getLocation().toFile());
      exportResources.add((IResource) libArchive);

      // cleaning temp project
      // if(!org.apache.commons.io.FileUtils.deleteQuietly(tempProject.getLocation().toFile())){
      // tempProject.delete(true, getProgressMonitor());
    }

    TempFileUtils.cleanUp();
    return exportResources;
  }