Example usage for org.eclipse.jdt.core.compiler BuildContext getFile

List of usage examples for org.eclipse.jdt.core.compiler BuildContext getFile

Introduction

In this page you can find the example usage for org.eclipse.jdt.core.compiler BuildContext getFile.

Prototype

public IFile getFile() 

Source Link

Document

Returns the IFile representing the compilation unit.

Usage

From source file:at.bestsolution.efxclipse.tooling.fxml.compile.FxmlAnnotationCompilationParticipant.java

License:Open Source License

@Override
public void buildStarting(BuildContext[] files, boolean isBatch) {
    super.buildStarting(files, isBatch);
    for (BuildContext context : files) {
        List<CategorizedProblem> problems = null;
        try {/*w w  w .java 2 s.  co m*/
            ICompilationUnit unit = JavaCore.createCompilationUnitFrom(context.getFile());
            problems = checkCU(unit, null);
            context.recordNewProblems(problems.toArray(new CategorizedProblem[problems.size()]));
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            if (problems != null) {
                problems.clear();
            }
        }
    }
}

From source file:ca.ecliptical.pde.internal.ds.DSAnnotationCompilationParticipant.java

License:Open Source License

@Override
public void processAnnotations(BuildContext[] files) {
    // we need to process CUs in context of a project; separate them by project
    HashMap<IJavaProject, Map<ICompilationUnit, BuildContext>> filesByProject = new HashMap<IJavaProject, Map<ICompilationUnit, BuildContext>>();
    for (BuildContext file : files) {
        ICompilationUnit cu = JavaCore.createCompilationUnitFrom(file.getFile());
        if (cu == null)
            continue;

        Map<ICompilationUnit, BuildContext> map = filesByProject.get(cu.getJavaProject());
        if (map == null) {
            map = new HashMap<ICompilationUnit, BuildContext>();
            filesByProject.put(cu.getJavaProject(), map);
        }/*from   w w  w .  j a  va2  s . c  o m*/

        map.put(cu, file);
    }

    // process all CUs in each project
    for (Map.Entry<IJavaProject, Map<ICompilationUnit, BuildContext>> entry : filesByProject.entrySet()) {
        processAnnotations(entry.getKey(), entry.getValue());
    }
}

From source file:com.google.appengine.eclipse.core.validators.java.JavaCompilationParticipant.java

License:Open Source License

private void handleBuildStarting(BuildContext[] files, IProgressMonitor monitor) {
    for (BuildContext context : files) {
        IFile file = context.getFile();

        if (monitor != null) {
            // Return early if this is a canceled job. Note that the AST is
            // still being built as there is no way to signal an abort.
            if (monitor.isCanceled()) {
                return;
            }//from   w  ww .  j  a va  2 s .  co  m

            // Update the progress monitor.
            monitor.subTask(file.getName());
            monitor.worked(1);
        }

        try {
            ICompilationUnit cu = JavaCore.createCompilationUnitFrom(file);

            ASTNode ast = null;

            try {
                /*
                 * Generally, the compilation unit will be consistent (the Java Model
                 * matches the .java file on disk). However, in certain cases, such as
                 * when the user undos a member rename refactoring, the two are out of
                 * sync when the build starts. In these cases, we have to explicitly
                 * reconcile the compilation unit with its underlying resource and use
                 * the AST we get back for validation.
                 */
                if (!cu.isConsistent()) {
                    ast = cu.reconcile(AST.JLS3, true, null, null);
                    assert (cu.isConsistent());
                } else {
                    // Have JDT parse the compilation unit
                    ASTParser parser = ASTParser.newParser(AST.JLS3);

                    // TODO: Note I will resolve type bindings for now, but I might
                    // be able to simply convert SimpleNames and QualifiedNames to
                    // fully qualified names, thereby avoiding full binding resolution.
                    parser.setResolveBindings(true);

                    parser.setSource(cu);
                    ast = parser.createAST(null);
                }
            } catch (JavaModelException e) {
                AppEngineCorePluginLog.logError(e);
                continue;
            }

            // Validate the Java AST and record any problems we find
            List<? extends CategorizedProblem> problems = validateCompilationUnit(ast);
            context.recordNewProblems(problems.toArray(EMPTY_PROBLEMS));
        } catch (OperationCanceledException e) {
            // Thrown by Eclipse to abort long-running processes
            throw e;
        } catch (Exception e) {
            // Don't want to allow any unexpected exceptions to escape
            AppEngineCorePluginLog.logError(e, "Unexpected error while validating {0}", file.getName());
        }
    }
}

From source file:com.google.gdt.eclipse.appengine.rpc.validators.JavaCompilationParticipant.java

License:Open Source License

@Override
public void buildStarting(final BuildContext[] files, boolean isBatch) {

    for (BuildContext context : files) {
        IFile file = context.getFile();

        try {//  w w w .  j a v a2 s.  c o  m
            ICompilationUnit cu = JavaCore.createCompilationUnitFrom(file);
            ASTNode ast = null;
            IType requestContext = null;

            // find the requestfactory classes, once per project
            if (javaProject == null || javaProject.getProject() != cu.getJavaProject().getProject()) {

                javaProject = cu.getJavaProject();
                projectEntities.clear();
                proxies.clear();
                requestMap.clear();
                RequestFactoryUtils.findAllTypes(javaProject, projectEntities, proxies, requestMap);
            }

            // if there is no requestfactory implementation, no need to validate
            String name = cu.findPrimaryType().getFullyQualifiedName();
            if (requestMap.containsKey(name)) {
                requestContext = requestMap.get(name);
            }

            if (requestContext != null) {
                try {
                    /*
                     * Generally, the compilation unit will be consistent (the Java
                     * Model matches the .java file on disk). However, in certain cases,
                     * such as when the user undos a member rename refactoring, the two
                     * are out of sync when the build starts. In these cases, we have to
                     * explicitly reconcile the compilation unit with its underlying
                     * resource and use the AST we get back for validation.
                     */
                    if (!cu.isConsistent()) {
                        ast = cu.reconcile(AST.JLS3, true, null, null);
                        assert (cu.isConsistent());
                    } else {
                        // Have JDT parse the compilation unit
                        ASTParser parser = ASTParser.newParser(AST.JLS3);
                        parser.setResolveBindings(true);

                        parser.setSource(cu);
                        ast = parser.createAST(null);
                    }
                } catch (JavaModelException e) {
                    AppEngineRPCPlugin.log(e);
                    continue;
                }
                // Validate the Java AST and record any problems we find
                RequestFactoryValidator validator = new RequestFactoryValidator(requestContext, projectEntities,
                        proxies);
                List<? extends CategorizedProblem> problems = validator.validate(ast);
                context.recordNewProblems(problems.toArray(EMPTY_PROBLEMS));
            }
        } catch (OperationCanceledException e) {
            // Thrown by Eclipse to abort long-running processes
            throw e;
        } catch (Exception e) {
            AppEngineRPCPlugin.getLogger().logError(e, "Unexpected error while validating {0}", file.getName());
        }
    }
}

From source file:com.google.gdt.eclipse.designer.builders.participant.AbstractCompilationParticipant.java

License:Open Source License

/**
 * Implementation of {@link #processAnnotations(BuildContext[])} that can throw any
 * {@link Exception}./*from   w  ww .  j  a v a  2s  .  com*/
 */
private void processAnnotationsEx(BuildContext[] contexts) throws Exception {
    // prepare resources and markers
    final List<IFile> resources = Lists.newArrayList();
    final List<MarkerInfo> newMarkers = Lists.newArrayList();
    for (BuildContext context : contexts) {
        IFile file = context.getFile();
        // prepare AST unit for this file
        ICompilationUnit modelUnit = JavaCore.createCompilationUnitFrom(file);
        CompilationUnit astUnit = Utils.parseUnit(modelUnit);
        // add resources and markers
        resources.add(file);
        addMarkers(newMarkers, file, modelUnit, astUnit);
    }
    // delete markers from resources and add new markers
    {
        IWorkspaceRunnable runnable = new IWorkspaceRunnable() {
            public void run(IProgressMonitor monitor) throws CoreException {
                // delete markers
                for (IFile resource : resources) {
                    resource.deleteMarkers(m_markerID, false, IResource.DEPTH_INFINITE);
                }
                // add markers
                for (MarkerInfo markerInfo : newMarkers) {
                    markerInfo.createMarker(m_markerID);
                }
            }
        };
        ResourcesPlugin.getWorkspace().run(runnable, null);
    }
}

From source file:com.google.gwt.eclipse.core.validators.java.JavaCompilationParticipant.java

License:Open Source License

private void handleBuildStarting(BuildContext[] files, final IProgressMonitor monitor) {
    UiBinderSubtypeToOwnerIndex prebuildOwnerIndex = new UiBinderSubtypeToOwnerIndex(
            UiBinderReferenceManager.INSTANCE.getSubtypeToOwnerIndex());
    final LinkedHashMap<ICompilationUnit, BuildContext> compilationUnitToBuildContext = new LinkedHashMap<ICompilationUnit, BuildContext>();

    for (BuildContext buildContext : files) {
        ICompilationUnit cu = JavaCore.createCompilationUnitFrom(buildContext.getFile());
        compilationUnitToBuildContext.put(cu, buildContext);
    }//from  ww  w .  j  av a2s.  co  m

    final Set<ICompilationUnit> validatedCompilationUnits = new HashSet<ICompilationUnit>();

    /*
     * ASTBatchParser processes the ICompilationUnits in batches based on the
     * available memory in the system. Note that we never cache the ASTs they
     * are only live for the duration of the callback below. Empirically, trying
     * to cache all ASTs for gwt-user project results in an OOM.
     */
    new ASTBatchParser().createASTs(compilationUnitToBuildContext.keySet().toArray(NO_UNITS), NO_STRINGS,
            new ASTRequestor() {
                @Override
                public void acceptAST(ICompilationUnit source, CompilationUnit ast) {
                    BuildContext buildContext = compilationUnitToBuildContext.get(source);
                    IFile file = buildContext.getFile();

                    if (monitor != null) {
                        // Return early if this is a canceled job. Note that the AST is
                        // still being built as there is no way to signal an abort.
                        if (monitor.isCanceled()) {
                            return;
                        }

                        // Update the progress monitor.
                        monitor.subTask(source.getElementName());
                        monitor.worked(1);
                    }

                    try {
                        ICompilationUnit cu = source;

                        validatedCompilationUnits.add(cu);

                        try {
                            /*
                             * Generally, the compilation unit will be consistent (the Java
                             * Model matches the .java file on disk). However, in certain
                             * cases, such as when the user undos a member rename
                             * refactoring, the two are out of sync when the build starts.
                             * In these cases, we have to explicitly reconcile the
                             * compilation unit with its underlying resource and use the AST
                             * we get back for validation.
                             */
                            if (!cu.isConsistent()) {
                                ast = cu.reconcile(AST.JLS4, true, null, null);
                                assert (cu.isConsistent());
                            }
                        } catch (JavaModelException e) {
                            GWTPluginLog.logError(e);
                            return;
                        }

                        // TODO: Merge this code with that of reconcile

                        // Validate the Java AST and record any GWT problems we find
                        JavaValidationResult result = validateCompilationUnit(ast);
                        List<CategorizedProblem> problems = new ArrayList<CategorizedProblem>(
                                result.getProblems());

                        RemoteServiceValidator rsv = new RemoteServiceValidator();
                        ValidationResult validationResult = rsv.validate(ast);
                        problems.addAll(validationResult.getProblems());

                        ClientBundleValidator cbv = new ClientBundleValidator();
                        ValidationResult cbvResult = cbv.validate(ast);
                        problems.addAll(cbvResult.getProblems());

                        ValidationResult uivResult;
                        if (UiBinderConstants.UI_BINDER_ENABLED) {
                            UiBinderJavaValidator uiv = new UiBinderJavaValidator(ast,
                                    UiBinderReferenceManager.INSTANCE.getSubtypeToOwnerIndex(),
                                    UiBinderReferenceManager.INSTANCE.getSubtypeToUiXmlIndex(),
                                    UiBinderReferenceManager.INSTANCE.getUiXmlReferencedFieldIndex(),
                                    UiBinderReferenceManager.INSTANCE.getReferenceManager());
                            uivResult = uiv.validate();
                            problems.addAll(uivResult.getProblems());
                        }

                        // Record the problems
                        buildContext.recordNewProblems(problems.toArray(EMPTY_PROBLEMS));

                        // Get all Java types references from JSNI blocks in this file
                        List<String> typeDependencies = new ArrayList<String>();
                        for (JsniJavaRef javaRef : result.getJavaRefs()) {
                            if (!typeDependencies.contains(javaRef.dottedClassName())) {
                                typeDependencies.add(javaRef.dottedClassName());
                            }
                        }

                        // Add the RPC dependencies
                        typeDependencies.addAll(validationResult.getTypeDependencies());

                        if (UiBinderConstants.UI_BINDER_ENABLED) {
                            // Add the UiBinder dependencies
                            typeDependencies.addAll(uivResult.getTypeDependencies());
                        }

                        // Record the JSNI dependencies so that changing any referenced
                        // types
                        // will automatically trigger a rebuild of this file
                        buildContext.recordDependencies(typeDependencies.toArray(Empty.STRINGS));
                    } catch (OperationCanceledException e) {
                        // Thrown by Eclipse to abort long-running processes
                        throw e;
                    } catch (Exception e) {
                        // Don't want to allow any unexpected exceptions to escape
                        GWTPluginLog.logError(e, "Unexpected error while validating {0}", file.getName());
                    }
                }
            }, null);

    if (UiBinderConstants.UI_BINDER_ENABLED) {
        revalidateOwnerTypes(prebuildOwnerIndex, validatedCompilationUnits);
    }
}

From source file:de.devboost.commenttemplate.builder.CommentTemplateCompilationParticipant.java

License:Open Source License

private void buildUnsafe(BuildContext[] contexts) {

    ResourceSetImpl resourceSet = new ResourceSetImpl();
    // markers are already created by the JDT
    Map<Object, Object> loadOptions = resourceSet.getLoadOptions();
    loadOptions.put(IJavaOptions.DISABLE_CREATING_MARKERS_FOR_PROBLEMS, Boolean.TRUE);

    for (BuildContext context : contexts) {
        IFile srcFile = context.getFile();
        IPath srcFilePath = srcFile.getFullPath();
        URI uri = URI.createPlatformResourceURI(srcFilePath.toString(), true);
        if (!builder.isBuildingNeeded(uri)) {
            continue;
        }// w w w .ja v a 2  s  . c  o  m

        Set<String> brokenVariableReferences = new LinkedHashSet<String>();
        Resource resource = resourceSet.getResource(uri, true);
        URI compiledURI = builder.build(resource, brokenVariableReferences);
        if (compiledURI == null) {
            continue;
        }

        IWorkspace workspace = srcFile.getWorkspace();
        IWorkspaceRoot root = workspace.getRoot();
        Path compiledSrcPath = new Path(compiledURI.toPlatformString(true));
        IFile compiledSrc = root.getFile(compiledSrcPath);
        try {
            srcFile.deleteMarkers(JavaMarkerHelper.MARKER_TYPE, false, IResource.DEPTH_ONE);
        } catch (CoreException e) {
            CommentTemplatePlugin.logError("Can't delete markers from " + srcFile, e);
        }
        if (!brokenVariableReferences.isEmpty()) {
            createWarnings(brokenVariableReferences, srcFile);
        }
        context.recordAddedGeneratedFiles(new IFile[] { compiledSrc });
        createSrcGenFolder(srcFile.getProject());
    }
}

From source file:de.devboost.emfcustomize.builder.EMFCustomizeCompilationParticipant.java

License:Open Source License

@Override
public void buildStarting(BuildContext[] files, boolean isBatch) {
    ResourceSetImpl resourceSet = new ResourceSetImpl();
    //markers are already created by the JDT
    resourceSet.getLoadOptions().put(IJavaOptions.DISABLE_CREATING_MARKERS_FOR_PROBLEMS, Boolean.TRUE);
    for (BuildContext context : files) {
        URI uri = URI.createPlatformResourceURI(context.getFile().getFullPath().toString(), true);
        if (builder.isBuildingNeeded(uri)) {
            IWorkspace workspace = context.getFile().getWorkspace();
            List<Resource> createdClasses = builder.build(resourceSet.getResource(uri, true),
                    context.getFile());//from w  ww . j  av a2s.  c  o m
            IFile[] newSrcFiles = new IFile[createdClasses.size()];
            for (int i = 0; i < createdClasses.size(); i++) {
                newSrcFiles[i] = workspace.getRoot()
                        .getFile(new Path(createdClasses.get(i).getURI().toPlatformString(true)));
            }
            context.recordAddedGeneratedFiles(newSrcFiles);
        }
    }
}

From source file:jmockit.assist.JMockitCompilationParticipant.java

License:Open Source License

@Override
public void buildStarting(final BuildContext[] files, final boolean isBatch) {
    CheckScope scope = getCheckScope();//from w  w  w.j av  a2 s  .c  o m

    IResource res = Activator.getActiveResource();
    String activeProj = null;
    if (res != null) {
        activeProj = res.getProject().getName();
    }

    List<BuildContext> filesToParse = new ArrayList<BuildContext>();
    for (BuildContext f : files) {
        IFile file = f.getFile();

        if ((scope == CheckScope.Project || scope == CheckScope.File)
                && !file.getProject().getName().equals(activeProj)) {
            continue;
        }

        if (scope == CheckScope.File && (res == null || !file.equals(res))) {
            continue;
        }

        filesToParse.add(f);
    }

    job.addFiles(filesToParse);

    if (isBatch) {
        job.schedule(JOB_DELAY);
    } else {
        job.schedule();
    }
}

From source file:net.atos.jdt.ast.validation.engine.internal.participant.ASTValidationParticipant.java

License:Open Source License

@Override
public void buildStarting(BuildContext[] files, boolean isBatch) {

    // Only if enabled, we start checking the source...
    if (ASTRulesPreferences.isValidationParticipantEnabled()) {

        // If enabled, we collect all the compilation units raised by the
        // context
        final Collection<ICompilationUnit> compilationUnits = new ArrayList<ICompilationUnit>();
        for (final BuildContext file : files) {
            final IFile iFile = file.getFile();
            if (iFile != null && iFile.exists()) {
                final IJavaElement javaElement = JavaCore.create(iFile);
                if (javaElement instanceof ICompilationUnit) {
                    compilationUnits.add((ICompilationUnit) javaElement);
                }//from  w ww  .  j a v  a 2  s . c  o m
            }
        }
        try {

            // For all collected units, we validate them.
            new ASTValidationEngine(compilationUnits).execute(new NullProgressMonitor());
        } catch (CoreException e) {
            Activator.logException(e);
        }
    }

    // Resume the process...
    super.buildStarting(files, isBatch);
}