private boolean init(IValidationContext helper, IReporter reporter, boolean test) {
   if (!test && disabled) {
     return false;
   }
   if (context == null) {
     synchronized (reporters) {
       reporters.add(document);
     }
     String[] uris = helper.getURIs();
     if (uris.length == 0) {
       return false;
     }
     IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
     file = root.getFile(new Path(uris[0]));
     if (!file.isAccessible()) {
       return false;
     }
     context = new EditorValidationContext(file.getProject(), document);
     if (context.getValidators().isEmpty()) {
       return false;
     }
     rootProjects = new HashMap<IValidator, IProject>();
     for (IValidator validator : context.getValidators()) {
       Map<IProject, IValidatingProjectSet> projectTree =
           context.getValidatingProjectTree(validator).getBrunches();
       if (!projectTree.isEmpty()) {
         IProject rootProject = projectTree.keySet().iterator().next();
         rootProjects.put(validator, rootProject);
       }
     }
   }
   return true;
 }
 private String readHeader() {
   // TODO: use IRunnableWithProgress
   StringBuilder sb = new StringBuilder();
   IFile file = getHeaderFile();
   if (file.exists() && file.isAccessible()) {
     InputStream stream = null;
     try {
       stream = file.getContents();
       BufferedReader reader = new BufferedReader(new InputStreamReader(stream));
       String line;
       while ((line = reader.readLine()) != null) {
         sb.append(line).append(System.lineSeparator());
       }
     } catch (Exception ex) {
       ex.printStackTrace();
     } finally {
       try {
         if (stream != null) stream.close();
       } catch (IOException ioe) {
         ioe.printStackTrace();
       }
     }
   }
   return sb.toString();
 }
  /**
   * This method will ensure that the Acceleo project has a dependency with all the project
   * containing a dynamic metamodels used in the module.
   *
   * @param module The Acceleo module
   * @param inputFile The file in the Acceleo editor
   */
  private void checkDependenciesWithDynamicMetamodels(Module module, IFile inputFile) {
    List<TypedModel> input = module.getInput();
    for (TypedModel typedModel : input) {
      List<EPackage> takesTypesFrom = typedModel.getTakesTypesFrom();
      for (EPackage ePackage : takesTypesFrom) {
        Map<String, String> dynamicEcorePackagePaths =
            AcceleoPackageRegistry.INSTANCE.getDynamicEcorePackagePaths();
        String packagePath = dynamicEcorePackagePaths.get(ePackage.getNsURI());
        if (packagePath == null) {
          return;
        }
        IPath path = new Path(packagePath);
        IFile metamodelFile = ResourcesPlugin.getWorkspace().getRoot().getFile(path);
        if (metamodelFile != null && metamodelFile.isAccessible()) {
          // We have found the "ecore" file for the dynamic metamodel
          IProject metamodelProject = metamodelFile.getProject();
          IProject inputProject = inputFile.getProject();
          if (!inputProject.equals(metamodelProject)) {
            // The dynamic metamodel is not in the project of the generator, let's find if
            // this dynamic metamodel is in a dependency of the project of the generator.
            boolean foundProject = false;

            AcceleoProject acceleoProject = new AcceleoProject(inputProject);
            List<IProject> recursivelyAccessibleProjects =
                acceleoProject.getRecursivelyAccessibleProjects();
            for (IProject iProject : recursivelyAccessibleProjects) {
              if (iProject.equals(metamodelProject)) {
                foundProject = true;
              }
            }

            if (!foundProject) {
              // The dynamic metamodel is not in a dependency of the current project, log a
              // warning.
              try {
                AcceleoMarkerUtils.createMarkerOnFile(
                    AcceleoMarkerUtils.WARNING_MARKER_ID,
                    inputFile,
                    0,
                    typedModel.getStartPosition(),
                    typedModel.getEndPosition(),
                    AcceleoUIMessages.getString(
                        "AcceleoCompileOperation.NoDependencyWithDynamicMetamodelProject", //$NON-NLS-1$
                        metamodelProject.getName(),
                        inputProject.getName()));
              } catch (CoreException e) {
                AcceleoUIActivator.log(e, true);
              }
            }
          }
        }
      }
    }
  }
 /**
  * Checks if the given <code>file</code> is accessible and its file extension is in the list of
  * allowed file extensions.
  */
 public final boolean isBeansConfig(IFile file) {
   if (file.isAccessible() && getAllowedFileExtensions().contains(file.getFileExtension())) {
     Set<IPath> rootPaths = getRootDirectories(file.getProject());
     for (IPath path : rootPaths) {
       if (path.isPrefixOf(file.getFullPath())) {
         return locateBeansConfigs(file.getProject(), null).contains(file);
       }
     }
   }
   return false;
 }
 /**
  * @param testProject
  * @param string
  * @param string2
  * @return
  * @throws CoreException
  * @throws IOException
  */
 public static IFile createTestSourceFile(IProject testProject, String fileName, String content)
     throws CoreException, IOException {
   IFile sourceFile = testProject.getFile(fileName);
   InputStream is = new ByteArrayInputStream(content.getBytes("UTF-8"));
   if (sourceFile.exists() && sourceFile.isAccessible()) {
     sourceFile.setContents(is, true, false, null);
   } else {
     sourceFile.create(is, true, null);
   }
   is.close();
   return sourceFile;
 }
  public IProjectFacetVersion getWebFacetVersion(IProject project) {
    IFile webXml;
    String customWebXml = getCustomWebXml(project);
    if (customWebXml == null) {
      webXml = project.getFolder(getWarSourceDirectory()).getFile(WEB_XML);
    } else {
      webXml = project.getFile(customWebXml);
    }

    if (webXml.isAccessible()) {
      try {
        InputStream is = webXml.getContents();
        try {
          JavaEEQuickPeek jqp = new JavaEEQuickPeek(is);
          switch (jqp.getVersion()) {
            case J2EEVersionConstants.WEB_2_2_ID:
              return WebFacetUtils.WEB_22;
            case J2EEVersionConstants.WEB_2_3_ID:
              return WebFacetUtils.WEB_23;
            case J2EEVersionConstants.WEB_2_4_ID:
              return WebFacetUtils.WEB_24;
            case J2EEVersionConstants.WEB_2_5_ID:
              return WebFacetUtils.WEB_FACET.getVersion("2.5");
              // MNGECLIPSE-1978
            case WEB_3_0_ID: // JavaEEQuickPeek will return this value only if WTP version >= 3.2
              return WebFacetUtils.WEB_FACET.getVersion("3.0"); // only exists in WTP version >= 3.2
          }
        } finally {
          is.close();
        }
      } catch (IOException ex) {
        // expected
      } catch (CoreException ex) {
        // expected
      }
    }

    // MNGECLIPSE-1978 If no web.xml found and the project depends on some java EE 6 jar and WTP >=
    // 3.2, then set web facet to 3.0
    if (WTPProjectsUtil.isJavaEE6Available()
        && WTPProjectsUtil.hasInClassPath(project, "javax.servlet.annotation.WebServlet")) {
      return WebFacetUtils.WEB_FACET.getVersion("3.0");
    }

    // MNGECLIPSE-984 web.xml is optional for 2.5 Web Projects
    return WTPProjectsUtil.DEFAULT_WEB_FACET;
    // We don't want to prevent the project creation when the java compiler level is < 5, we coud
    // try that instead :
    // IProjectFacetVersion javaFv =
    // JavaFacetUtils.compilerLevelToFacet(JavaFacetUtils.getCompilerLevel(project));
    // return (JavaFacetUtils.JAVA_50.compareTo(javaFv) >
    // 0)?WebFacetUtils.WEB_24:WebFacetUtils.WEB_25;
  }
 protected static String getAsString(IFile file) throws IOException, CoreException {
   assert file != null;
   assert file.isAccessible();
   InputStream ins = null;
   String content = null;
   try {
     ins = file.getContents();
     content = IOUtil.toString(ins, 1024);
   } finally {
     IOUtil.close(ins);
   }
   return content;
 }
Пример #8
0
 static boolean isInSourceFolder(final IFile file) {
   if (file == null || !file.isAccessible()) {
     // throw new IllegalArgumentException();
     return false;
   }
   boolean result = false;
   IHaskellProject hsProject = HaskellProjectManager.get(file.getProject());
   Set<IPath> sourcePaths = hsProject.getSourcePaths();
   for (IPath sourcePath : sourcePaths) {
     IPath src = file.getProject().getFullPath().append(sourcePath);
     result |= src.isPrefixOf(file.getFullPath());
   }
   return result;
 }
 protected CMElementDeclaration checkExternalSchema(Element element) {
   final Document document = element.getOwnerDocument();
   if (document instanceof IDOMDocument) {
     final String baseLocation = ((IDOMDocument) document).getModel().getBaseLocation();
     if (baseLocation != null) {
       final IPath basePath = new Path(baseLocation);
       IFile file = null;
       if (basePath.segmentCount() > 1) {
         file = ResourcesPlugin.getWorkspace().getRoot().getFile(basePath);
       }
       final URI uri =
           (file == null || !file.isAccessible())
               ? new File(baseLocation).toURI()
               : file.getLocationURI();
       if (uri != null) {
         IExternalSchemaLocationProvider[] providers =
             ExternalSchemaLocationProviderRegistry.getInstance().getProviders();
         for (int i = 0; i < providers.length; i++) {
           long time = _trace ? System.currentTimeMillis() : 0;
           final Map locations = providers[i].getExternalSchemaLocation(uri);
           if (_trace) {
             long diff = System.currentTimeMillis() - time;
             if (diff > 250)
               Logger.log(
                   Logger.INFO,
                   "Schema location provider took ["
                       + diff
                       + "ms] for URI ["
                       + uri
                       + "]"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
           }
           if (locations != null && !locations.isEmpty()) {
             Object location =
                 locations.get(IExternalSchemaLocationProvider.NO_NAMESPACE_SCHEMA_LOCATION);
             if (location != null)
               return getCMElementDeclaration(
                   element,
                   NamespaceTable.getElementLineage(element),
                   uri.toString(),
                   location.toString());
           }
         }
       }
     }
   }
   return null;
 }
Пример #10
0
  /**
   * Create a test source file
   *
   * @param project a project where to create that file; this project is expected to be empty
   */
  public static IFile createTestSourceFile(final IProject project)
      throws JavaModelException, CoreException, IOException {

    // 1. Locate the test java source template
    final InputStream is = EclipseUtils.class.getResourceAsStream("/test.template");

    // 2. Copy the template inside the source directory
    final IFile sourceFile = project.getFile("/src/Test.java");
    if (sourceFile.exists() && sourceFile.isAccessible()) {
      sourceFile.setContents(is, true, false, null);
    } else {
      sourceFile.create(is, true, null);
    }
    is.close();
    project.refreshLocal(IResource.DEPTH_INFINITE, null);

    return sourceFile;
  }
Пример #11
0
 /**
  * Check the '.emtl' file and report in the '.mtl' file some syntax errors when we use the
  * non-standard library.
  *
  * @param iFile is the '.mtl' file
  * @param oURI is the URI of the '.emtl' file
  */
 private void checkFullOMGCompliance(File iFile, URI oURI) {
   try {
     AcceleoSourceBuffer buffer = new AcceleoSourceBuffer(iFile);
     ResourceSet oResourceSet = new ResourceSetImpl();
     EObject oRoot = ModelUtils.load(oURI, oResourceSet);
     TreeIterator<EObject> oAllContents = oRoot.eAllContents();
     while (oAllContents.hasNext()) {
       EObject oNext = oAllContents.next();
       if (oNext instanceof OperationCallExp) {
         OperationCallExp oOperationCallExp = (OperationCallExp) oNext;
         if (oOperationCallExp.getReferredOperation() != null
             && oOperationCallExp.getReferredOperation().getEAnnotation("MTL non-standard")
                 != null) { //$NON-NLS-1$
           IFile workspaceFile =
               ResourcesPlugin.getWorkspace()
                   .getRoot()
                   .getFileForLocation(new Path(iFile.getAbsolutePath()));
           if (workspaceFile != null
               && workspaceFile.isAccessible()
               && oOperationCallExp.getStartPosition() > -1) {
             int line = buffer.getLineOfOffset(oOperationCallExp.getStartPosition());
             AcceleoMarkerUtils.createMarkerOnFile(
                 AcceleoMarkerUtils.PROBLEM_MARKER_ID,
                 workspaceFile,
                 line,
                 oOperationCallExp.getStartPosition(),
                 oOperationCallExp.getEndPosition(),
                 AcceleoUIMessages.getString(
                     "AcceleoCompileOperation.NotFullyCompliant",
                     oOperationCallExp //$NON-NLS-1$
                         .getReferredOperation()
                         .getName()));
           }
         }
       }
     }
   } catch (IOException e) {
     Status status = new Status(IStatus.WARNING, AcceleoUIActivator.PLUGIN_ID, e.getMessage(), e);
     AcceleoUIActivator.getDefault().getLog().log(status);
   } catch (CoreException e) {
     AcceleoUIActivator.getDefault().getLog().log(e.getStatus());
   }
 }
Пример #12
0
  /**
   * Remove the PMD Nature from a project
   *
   * @param project a project to remove the PMD Nature
   * @param monitor a progress monitor
   * @return success true if the nature has been removed; false means the project already had not
   *     the PMD Nature.
   * @throws CoreException if any error occurs.
   */
  public static boolean removePMDNature(final IProject project) throws CoreException {
    final boolean success = false;

    if (project.hasNature(PMDNature.PMD_NATURE)) {
      final IProjectDescription description = project.getDescription();
      final String[] natureIds = description.getNatureIds();
      final String[] newNatureIds = new String[natureIds.length - 1];
      for (int i = 0, j = 0; i < natureIds.length; i++) {
        if (!natureIds[i].equals(PMDNature.PMD_NATURE)) {
          newNatureIds[j++] = natureIds[i];
        }
      }
      description.setNatureIds(newNatureIds);
      project.setDescription(description, null);
      project.deleteMarkers(PMDRuntimeConstants.PMD_MARKER, true, IResource.DEPTH_INFINITE);

      final IFile file = project.getFile(".pmd");
      if (file.exists() && file.isAccessible()) {
        file.delete(true, false, null);
      }
    }

    return success;
  }
Пример #13
0
  /**
   * Compiles the templates. Creates an AST model from a list of Acceleo files, using a CST step.
   * The dependencies are loaded before link resolution.
   *
   * @param monitor is the monitor
   * @throws CoreException contains a status object describing the cause of the exception
   */
  private void doCompileResources(IProgressMonitor monitor) throws CoreException {
    AcceleoProject acceleoProject = new AcceleoProject(project);
    List<URI> dependenciesURIs = acceleoProject.getAccessibleOutputFiles();
    List<AcceleoFile> iFiles = new ArrayList<AcceleoFile>();
    List<URI> oURIs = new ArrayList<URI>();
    for (int i = 0; i < files.length; i++) {
      checkCanceled(monitor);
      if (acceleoProject.getOutputFilePath(files[i]) != null) {
        IPath outputPath = acceleoProject.getOutputFilePath(files[i]);
        if (outputPath != null) {
          String javaPackageName = acceleoProject.getPackageName(files[i]);
          AcceleoFile acceleoFile =
              new AcceleoFile(
                  files[i].getLocation().toFile(),
                  AcceleoFile.javaPackageToFullModuleName(
                      javaPackageName,
                      new Path(files[i].getName()).removeFileExtension().lastSegment()));
          iFiles.add(acceleoFile);
          URI platformURI = URI.createPlatformResourceURI(outputPath.toString(), false);
          oURIs.add(platformURI);
        }
      }
    }

    AcceleoParser parser = null;
    AcceleoBuilderSettings settings = new AcceleoBuilderSettings(project);
    String resourceKind = settings.getResourceKind();
    if (AcceleoBuilderSettings.BUILD_XMI_RESOURCE.equals(resourceKind)) {
      parser = new AcceleoParser(false, settings.isTrimmedPositions());
    } else {
      parser = new AcceleoParser(true, settings.isTrimmedPositions());
    }
    parser.parse(
        iFiles, oURIs, dependenciesURIs, null, new BasicMonitor.EclipseSubProgress(monitor, 1));
    for (URI uri : oURIs) {
      try {
        AcceleoUIResourceSet.removeResource(uri);
      } catch (IOException e) {
        AcceleoUIActivator.log(e, true);
      }
    }

    for (Iterator<AcceleoFile> iterator = iFiles.iterator(); iterator.hasNext(); ) {
      AcceleoFile iFile = iterator.next();

      AcceleoParserProblems problems = parser.getProblems(iFile);
      AcceleoParserWarnings warnings = parser.getWarnings(iFile);
      AcceleoParserInfos infos = parser.getInfos(iFile);

      IFile workspaceFile =
          ResourcesPlugin.getWorkspace()
              .getRoot()
              .getFileForLocation(new Path(iFile.getMtlFile().getAbsolutePath()));

      if (workspaceFile != null && workspaceFile.isAccessible()) {
        if (problems != null) {
          List<AcceleoParserProblem> list = problems.getList();
          for (Iterator<AcceleoParserProblem> itProblems = list.iterator();
              itProblems.hasNext(); ) {
            AcceleoParserProblem problem = itProblems.next();
            AcceleoMarkerUtils.createMarkerOnFile(
                AcceleoMarkerUtils.PROBLEM_MARKER_ID,
                workspaceFile,
                problem.getLine(),
                problem.getPosBegin(),
                problem.getPosEnd(),
                problem.getMessage());
          }
        }
        if (warnings != null) {
          List<AcceleoParserWarning> list = warnings.getList();
          for (Iterator<AcceleoParserWarning> itWarnings = list.iterator();
              itWarnings.hasNext(); ) {
            AcceleoParserWarning warning = itWarnings.next();
            AcceleoMarkerUtils.createMarkerOnFile(
                AcceleoMarkerUtils.WARNING_MARKER_ID,
                workspaceFile,
                warning.getLine(),
                warning.getPosBegin(),
                warning.getPosEnd(),
                warning.getMessage());
          }
        }
        if (infos != null) {
          List<AcceleoParserInfo> list = infos.getList();
          for (Iterator<AcceleoParserInfo> itInfos = list.iterator(); itInfos.hasNext(); ) {
            AcceleoParserInfo info = itInfos.next();
            AcceleoMarkerUtils.createMarkerOnFile(
                AcceleoMarkerUtils.INFO_MARKER_ID,
                workspaceFile,
                info.getLine(),
                info.getPosBegin(),
                info.getPosEnd(),
                info.getMessage());
          }
        }
      }
    }

    if (iFiles.size() > 0) {
      AcceleoFile acceleoFile = iFiles.get(0);
      IFile workspaceFile =
          ResourcesPlugin.getWorkspace()
              .getRoot()
              .getFileForLocation(new Path(acceleoFile.getMtlFile().getAbsolutePath()));

      // FIXME Performance problem? We will only check for the first file to compile.
      AcceleoSourceBuffer buffer = new AcceleoSourceBuffer(acceleoFile);
      buffer.createCST();
      Module module = buffer.getCST();
      this.checkDependenciesWithDynamicMetamodels(module, workspaceFile);
    }
    checkCanceled(monitor);
    List<IFile> filesWithMainTag = new ArrayList<IFile>();
    for (Iterator<AcceleoFile> iterator = iFiles.iterator(); iterator.hasNext(); ) {
      AcceleoFile iFile = iterator.next();
      IFile workspaceFile =
          ResourcesPlugin.getWorkspace()
              .getRoot()
              .getFileForLocation(new Path(iFile.getMtlFile().getAbsolutePath()));
      if (workspaceFile != null && workspaceFile.isAccessible() && hasMainTag(workspaceFile)) {
        filesWithMainTag.add(workspaceFile);
      }
    }
    CreateRunnableAcceleoOperation createRunnableAcceleoOperation =
        new CreateRunnableAcceleoOperation(acceleoProject, filesWithMainTag);
    createRunnableAcceleoOperation.run(monitor);

    settings = new AcceleoBuilderSettings(project);
    if (AcceleoBuilderSettings.BUILD_STRICT_MTL_COMPLIANCE == settings.getCompliance()) {
      Iterator<AcceleoFile> itFiles = iFiles.iterator();
      for (Iterator<URI> itURIs = oURIs.iterator();
          !monitor.isCanceled() && itURIs.hasNext() && itFiles.hasNext(); ) {
        AcceleoFile iFile = itFiles.next();
        URI oURI = itURIs.next();
        checkFullOMGCompliance(iFile.getMtlFile(), oURI);
      }
    }
  }
Пример #14
0
 /**
  * Gets the qualified path of the given generator file. As an example, the qualified path of the
  * file '/MyProject/src/org/eclipse/acceleo/my.mt' is 'org/eclipse/acceleo'
  *
  * @param file is the '.mt' generator
  * @return the qualified path, it removes the first and the last segments of the project relative
  *     path
  */
 private static IPath getPackagePath(IFile file) {
   if (file != null && file.isAccessible()) {
     return file.getProjectRelativePath().removeLastSegments(1).removeFirstSegments(1);
   }
   return new Path(""); // $NON-NLS-1$
 }
Пример #15
0
 /**
  * Get the content of a project resource.
  *
  * @param project a project reference
  * @param resourceName the name of the resource (@see IProject)
  * @return the resource content as an InputStream or null
  * @throws CoreException
  */
 public static InputStream getResourceStream(final IProject project, final String resourceName)
     throws CoreException {
   final IFile file = project.getFile(resourceName);
   return file != null && file.exists() && file.isAccessible() ? file.getContents(true) : null;
 }
Пример #16
0
  public static void checkRegions(
      IProject project,
      String fileName,
      List<TestRegion> regionList,
      AbstractHyperlinkDetector elDetector)
      throws Exception {
    IFile file = project.getFile(fileName);

    assertNotNull("The file \"" + fileName + "\" is not found", file);
    assertTrue("The file \"" + fileName + "\" is not found", file.isAccessible());

    FileEditorInput editorInput = new FileEditorInput(file);

    IDocumentProvider documentProvider = null;
    try {
      documentProvider = DocumentProviderRegistry.getDefault().getDocumentProvider(editorInput);
    } catch (Exception x) {
      x.printStackTrace();
      fail("An exception caught: " + x.getMessage());
    }

    assertNotNull(
        "The document provider for the file \"" + fileName + "\" is not loaded", documentProvider);

    try {
      documentProvider.connect(editorInput);
    } catch (Exception x) {
      x.printStackTrace();
      fail(
          "The document provider is not able to be initialized with the editor input\nAn exception caught: "
              + x.getMessage());
    }

    IDocument document = documentProvider.getDocument(editorInput);

    assertNotNull("The document for the file \"" + fileName + "\" is not loaded", document);

    if (regionList.get(0).region == null) loadRegions(regionList, document);

    int expected = 0;
    for (TestRegion testRegion : regionList) expected += testRegion.region.getLength() + 1;

    IEditorPart part = openFileInEditor(file);
    ISourceViewer viewer = null;
    if (part instanceof JavaEditor) {
      viewer = ((JavaEditor) part).getViewer();
      elDetector.setContext(new TestContext((ITextEditor) part));
    } else if (part instanceof EditorPartWrapper) {
      if (((EditorPartWrapper) part).getEditor() instanceof WebCompoundEditor) {
        WebCompoundEditor wce = (WebCompoundEditor) ((EditorPartWrapper) part).getEditor();
        viewer = wce.getSourceEditor().getTextViewer();
        elDetector.setContext(new TestContext(wce.getSourceEditor()));
      } else if (((EditorPartWrapper) part).getEditor() instanceof XMLTextEditorStandAlone) {
        XMLTextEditorStandAlone xtesa =
            (XMLTextEditorStandAlone) ((EditorPartWrapper) part).getEditor();
        viewer = xtesa.getTextViewer();
        elDetector.setContext(new TestContext(xtesa));
      } else fail("unsupported editor type - " + ((EditorPartWrapper) part).getEditor().getClass());
    } else if (part instanceof JSPMultiPageEditor) {
      viewer = ((JSPMultiPageEditor) part).getJspEditor().getTextViewer();
      elDetector.setContext(new TestContext(((JSPMultiPageEditor) part).getJspEditor()));
    } else fail("unsupported editor type - " + part.getClass());

    int counter = 0;
    for (int i = 0; i < document.getLength(); i++) {
      int lineNumber = document.getLineOfOffset(i);
      int position = i - document.getLineOffset(lineNumber) + 1;
      lineNumber++;

      TestData testData = new TestData(document, i);
      IHyperlink[] links = elDetector.detectHyperlinks(viewer, testData.getHyperlinkRegion(), true);

      boolean recognized = links != null;

      if (recognized) {
        counter++;
        TestRegion testRegion = findOffsetInRegions(i, regionList);
        if (testRegion == null) {
          String information = findRegionInformation(document, i, regionList);
          fail(
              "Wrong detection for offset - "
                  + i
                  + " (line - "
                  + lineNumber
                  + " position - "
                  + position
                  + ") "
                  + information);
        } else {
          checkTestRegion(links, testRegion);
        }
      } else {
        for (TestRegion testRegion : regionList) {
          if (i >= testRegion.region.getOffset()
              && i <= testRegion.region.getOffset() + testRegion.region.getLength()) {
            fail(
                "Wrong detection for region - "
                    + getRegionInformation(document, testRegion)
                    + " offset - "
                    + i
                    + " (line - "
                    + lineNumber
                    + " position - "
                    + position
                    + ")");
          }
        }
      }
    }

    assertEquals("Wrong recognized region count: ", expected, counter);

    documentProvider.disconnect(editorInput);
  }
  void performValidation(IFile f, IReporter reporter, IStructuredModel model, boolean inBatch) {
    if (model instanceof IDOMModel) {
      IDOMModel domModel = (IDOMModel) model;
      JsTranslationAdapterFactory.setupAdapterFactory(domModel);
      IDOMDocument xmlDoc = domModel.getDocument();
      JsTranslationAdapter translationAdapter =
          (JsTranslationAdapter) xmlDoc.getAdapterFor(IJsTranslation.class);
      // translationAdapter.resourceChanged();
      IJsTranslation translation = translationAdapter.getJsTranslation(false);
      if (!reporter.isCancelled()) {
        translation.setProblemCollectingActive(true);
        translation.reconcileCompilationUnit();
        List problems = translation.getProblems();
        // only update task markers if the model is the same as what's on disk
        boolean updateTasks = !domModel.isDirty() && f != null && f.isAccessible();
        if (updateTasks) {
          // remove old JavaScript task markers
          try {
            IMarker[] foundMarkers =
                f.findMarkers(JAVASCRIPT_TASK_MARKER_TYPE, true, IResource.DEPTH_ONE);
            for (int i = 0; i < foundMarkers.length; i++) {
              foundMarkers[i].delete();
            }
          } catch (CoreException e) {
            Logger.logException(e);
          }
        }

        //				if(!inBatch) reporter.removeAllMessages(this, f);
        // add new messages
        for (int i = 0; i < problems.size() && !reporter.isCancelled(); i++) {
          IProblem problem = (IProblem) problems.get(i);
          IMessage m =
              createMessageFromProblem(problem, f, translation, domModel.getStructuredDocument());
          if (m != null) {
            if (problem.getID() == IProblem.Task) {
              if (updateTasks) {
                // add new JavaScript task marker
                try {
                  IMarker task = f.createMarker(JAVASCRIPT_TASK_MARKER_TYPE);
                  task.setAttribute(IMarker.LINE_NUMBER, new Integer(m.getLineNumber()));
                  task.setAttribute(IMarker.CHAR_START, new Integer(m.getOffset()));
                  task.setAttribute(IMarker.CHAR_END, new Integer(m.getOffset() + m.getLength()));
                  task.setAttribute(IMarker.MESSAGE, m.getText());
                  task.setAttribute(IMarker.USER_EDITABLE, Boolean.FALSE);

                  switch (m.getSeverity()) {
                    case IMessage.HIGH_SEVERITY:
                      {
                        task.setAttribute(IMarker.PRIORITY, new Integer(IMarker.PRIORITY_HIGH));
                        task.setAttribute(IMarker.SEVERITY, new Integer(IMarker.SEVERITY_ERROR));
                      }
                      break;
                    case IMessage.LOW_SEVERITY:
                      {
                        task.setAttribute(IMarker.PRIORITY, new Integer(IMarker.PRIORITY_LOW));
                        task.setAttribute(IMarker.SEVERITY, new Integer(IMarker.SEVERITY_INFO));
                      }
                      break;
                    default:
                      {
                        task.setAttribute(IMarker.PRIORITY, new Integer(IMarker.PRIORITY_NORMAL));
                        task.setAttribute(IMarker.SEVERITY, new Integer(IMarker.SEVERITY_WARNING));
                      }
                  }
                } catch (CoreException e) {
                  Logger.logException(e);
                }
              }
            } else {
              reporter.addMessage(fMessageOriginator, m);
            }
          }
        }
      }
    }
  }
Пример #18
0
  /** @exception JavaModelException if setting the source of the original compilation unit fails */
  protected void executeOperation() throws JavaModelException {
    try {
      beginTask(Messages.workingCopy_commit, 2);
      CompilationUnit workingCopy = getCompilationUnit();

      if (ExternalJavaProject.EXTERNAL_PROJECT_NAME.equals(
          workingCopy.getJavaProject().getElementName())) {
        // case of a working copy without a resource
        workingCopy.getBuffer().save(this.progressMonitor, this.force);
        return;
      }

      ICompilationUnit primary = workingCopy.getPrimary();
      boolean isPrimary = workingCopy.isPrimary();

      JavaElementDeltaBuilder deltaBuilder = null;
      PackageFragmentRoot root =
          (PackageFragmentRoot) workingCopy.getAncestor(IJavaElement.PACKAGE_FRAGMENT_ROOT);
      boolean isIncluded = !Util.isExcluded(workingCopy);
      IFile resource = (IFile) workingCopy.getResource();
      IJavaProject project = root.getJavaProject();
      if (isPrimary
          || (root.validateOnClasspath().isOK()
              && isIncluded
              && resource.isAccessible()
              && Util.isValidCompilationUnitName(
                  workingCopy.getElementName(),
                  project.getOption(JavaCore.COMPILER_SOURCE, true),
                  project.getOption(JavaCore.COMPILER_COMPLIANCE, true)))) {

        // force opening so that the delta builder can get the old info
        if (!isPrimary && !primary.isOpen()) {
          primary.open(null);
        }

        // creates the delta builder (this remembers the content of the cu) if:
        // - it is not excluded
        // - and it is not a primary or it is a non-consistent primary
        if (isIncluded && (!isPrimary || !workingCopy.isConsistent())) {
          deltaBuilder = new JavaElementDeltaBuilder(primary);
        }

        // save the cu
        IBuffer primaryBuffer = primary.getBuffer();
        if (!isPrimary) {
          if (primaryBuffer == null) return;
          char[] primaryContents = primaryBuffer.getCharacters();
          boolean hasSaved = false;
          try {
            IBuffer workingCopyBuffer = workingCopy.getBuffer();
            if (workingCopyBuffer == null) return;
            primaryBuffer.setContents(workingCopyBuffer.getCharacters());
            primaryBuffer.save(this.progressMonitor, this.force);
            primary.makeConsistent(this);
            hasSaved = true;
          } finally {
            if (!hasSaved) {
              // restore original buffer contents since something went wrong
              primaryBuffer.setContents(primaryContents);
            }
          }
        } else {
          // for a primary working copy no need to set the content of the buffer again
          primaryBuffer.save(this.progressMonitor, this.force);
          primary.makeConsistent(this);
        }
      } else {
        // working copy on cu outside classpath OR resource doesn't exist yet
        String encoding = null;
        try {
          encoding = resource.getCharset();
        } catch (CoreException ce) {
          // use no encoding
        }
        String contents = workingCopy.getSource();
        if (contents == null) return;
        try {
          byte[] bytes = encoding == null ? contents.getBytes() : contents.getBytes(encoding);
          ByteArrayInputStream stream = new ByteArrayInputStream(bytes);
          if (resource.exists()) {
            resource.setContents(
                stream,
                this.force ? IResource.FORCE | IResource.KEEP_HISTORY : IResource.KEEP_HISTORY,
                null);
          } else {
            resource.create(stream, this.force, this.progressMonitor);
          }
        } catch (CoreException e) {
          throw new JavaModelException(e);
        } catch (UnsupportedEncodingException e) {
          throw new JavaModelException(e, IJavaModelStatusConstants.IO_EXCEPTION);
        }
      }

      setAttribute(HAS_MODIFIED_RESOURCE_ATTR, TRUE);

      // make sure working copy is in sync
      workingCopy.updateTimeStamp((CompilationUnit) primary);
      workingCopy.makeConsistent(this);
      worked(1);

      // build the deltas
      if (deltaBuilder != null) {
        deltaBuilder.buildDeltas();

        // add the deltas to the list of deltas created during this operation
        if (deltaBuilder.delta != null) {
          addDelta(deltaBuilder.delta);
        }
      }
      worked(1);
    } finally {
      done();
    }
  }