Example usage for org.eclipse.jdt.core ICompilationUnit reconcile

List of usage examples for org.eclipse.jdt.core ICompilationUnit reconcile

Introduction

In this page you can find the example usage for org.eclipse.jdt.core ICompilationUnit reconcile.

Prototype

CompilationUnit reconcile(int astLevel, int reconcileFlags, WorkingCopyOwner owner, IProgressMonitor monitor)
        throws JavaModelException;

Source Link

Document

Reconciles the contents of this working copy, sends out a Java delta notification indicating the nature of the change of the working copy since the last time it was either reconciled or made consistent ( IOpenable#makeConsistent(IProgressMonitor) ), and returns a compilation unit AST if requested.

Usage

From source file:cideplus.ui.astview.ASTView.java

License:Open Source License

private CompilationUnit createAST(ITypeRoot input, int astLevel, int offset)
        throws JavaModelException, CoreException {
    long startTime;
    long endTime;
    CompilationUnit root;/*from w w w .  j  a  v a  2s.  co  m*/

    if ((getCurrentInputKind() == ASTInputKindAction.USE_RECONCILE)) {
        final IProblemRequestor problemRequestor = new IProblemRequestor() { //strange: don't get bindings when supplying null as problemRequestor
            public void acceptProblem(IProblem problem) {
                /*not interested*/}

            public void beginReporting() {
                /*not interested*/}

            public void endReporting() {
                /*not interested*/}

            public boolean isActive() {
                return true;
            }
        };
        WorkingCopyOwner workingCopyOwner = new WorkingCopyOwner() {
            @Override
            public IProblemRequestor getProblemRequestor(ICompilationUnit workingCopy) {
                return problemRequestor;
            }
        };
        ICompilationUnit wc = input.getWorkingCopy(workingCopyOwner, null);
        try {
            int reconcileFlags = ICompilationUnit.FORCE_PROBLEM_DETECTION;
            if (fStatementsRecovery)
                reconcileFlags |= ICompilationUnit.ENABLE_STATEMENTS_RECOVERY;
            if (fBindingsRecovery)
                reconcileFlags |= ICompilationUnit.ENABLE_BINDINGS_RECOVERY;
            if (fIgnoreMethodBodies)
                reconcileFlags |= ICompilationUnit.IGNORE_METHOD_BODIES;
            startTime = System.currentTimeMillis();
            root = wc.reconcile(getCurrentASTLevel(), reconcileFlags, null, null);
            endTime = System.currentTimeMillis();
        } finally {
            wc.discardWorkingCopy();
        }

    } else if (input instanceof ICompilationUnit && (getCurrentInputKind() == ASTInputKindAction.USE_CACHE)) {
        ICompilationUnit cu = (ICompilationUnit) input;
        startTime = System.currentTimeMillis();
        root = SharedASTProvider.getAST(cu, SharedASTProvider.WAIT_NO, null);
        endTime = System.currentTimeMillis();

    } else {
        ASTParser parser = ASTParser.newParser(astLevel);
        parser.setResolveBindings(fCreateBindings);
        if (input instanceof ICompilationUnit) {
            parser.setSource((ICompilationUnit) input);
        } else {
            parser.setSource((IClassFile) input);
        }
        parser.setStatementsRecovery(fStatementsRecovery);
        parser.setBindingsRecovery(fBindingsRecovery);
        parser.setIgnoreMethodBodies(fIgnoreMethodBodies);
        if (getCurrentInputKind() == ASTInputKindAction.USE_FOCAL) {
            parser.setFocalPosition(offset);
        }
        startTime = System.currentTimeMillis();
        root = (CompilationUnit) parser.createAST(null);
        endTime = System.currentTimeMillis();
    }
    if (root != null) {
        updateContentDescription(input, root, endTime - startTime);
    }
    return root;
}

From source file:com.cb.eclipse.folding.java.calculation.ProjectionChangeReconciler.java

License:Open Source License

/**
 * Performs an initialization on the projection annotation model. This is
 * essentially the process of putting the result from the
 * JavaProjectionCalculator on to annotation model.
 * //from ww  w .j  a  va2 s .c om
 * @param model
 * @param input
 */
public void initialize(ProjectionAnnotationModel model, IJavaElement input) {

    try {

        if (input instanceof ICompilationUnit) {
            ICompilationUnit unit = (ICompilationUnit) input;
            synchronized (unit) {
                try {
                    unit.reconcile(ICompilationUnit.NO_AST, false, null, null);
                } catch (JavaModelException x) {
                    x.printStackTrace();
                }

            }
        }

        // enable collapsing so new structures that are created can be 
        // collapsed. Initialize should only be invoked on editor startup.
        calculator.setCollapsing(true);
        if (model != null) {
            Map additions = reconstructAnnotations(input);
            model.removeAllAnnotations();
            model.replaceAnnotations(null, additions);
        }
    } finally {
        // ensure we disable collapsing on the calculator so no further 
        // projections are collapsed at construction.
        calculator.setCollapsing(false);
    }
}

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();/*from www  . j a  va  2  s  . co  m*/

        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(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.markers.quickfixes.CreateRequestFactoryMethodProposal.java

License:Open Source License

/**
 * Add service methods for entities//w  w w  .  j av a  2 s.c om
 */
private boolean addServiceMethods() {

    IMethod method = (IMethod) serviceMethod.resolveBinding().getJavaElement();
    ICompilationUnit cu = method.getCompilationUnit();
    String source = null;
    try {
        source = cu.getSource();
        Document document = new Document(source);
        ASTParser parser = ASTParser.newParser(AST.JLS3);
        parser.setSource(cu);
        CompilationUnit astRoot = (CompilationUnit) parser.createAST(null);
        ASTRewrite rewrite = ASTRewrite.create(astRoot.getAST());
        ListRewrite listRewriter = null;
        AbstractTypeDeclaration declaration = (AbstractTypeDeclaration) astRoot.types().get(0);
        if (declaration != null) {
            listRewriter = rewrite.getListRewrite(declaration, declaration.getBodyDeclarationsProperty());
        }
        StringBuffer buf = new StringBuffer();
        for (IType entity : entityList) {
            buf.append(CodegenUtils.format(RequestFactoryCodegenUtils.constructServiceMethods(entity, method),
                    CodeFormatter.K_CLASS_BODY_DECLARATIONS));
        }
        MethodDeclaration methodDecl = (MethodDeclaration) listRewriter.getASTRewrite()
                .createStringPlaceholder(buf.toString(), ASTNode.METHOD_DECLARATION);
        listRewriter.insertLast(methodDecl, null);

        TextEdit edits = rewrite.rewriteAST(document, cu.getJavaProject().getOptions(true));
        edits.apply(document);
        cu.getBuffer().setContents(document.get());
        cu.reconcile(ICompilationUnit.NO_AST, false, null, null);
    } catch (CoreException e) {
        AppEngineRPCPlugin.log(e);
        return false;
    } catch (MalformedTreeException e) {
        AppEngineRPCPlugin.log(e);
        return false;
    } catch (BadLocationException e) {
        AppEngineRPCPlugin.log(e);
        return false;
    }
    return true;
}

From source file:com.google.gdt.eclipse.appengine.rpc.util.CompilationUnitCreator.java

License:Open Source License

/**
 * /*from  ww w  .  ja  va  2  s  .  c  om*/
 * @param type IType - entity to generate request factory code
 * @param pack IPackageFragment - package for the file
 * @param name String - name of the file
 * @param rpcType int - whether proxy, locator, service, request,
 *          requestfactory
 * @param monitor IProgressMonitor
 * @return IJavaElement - the created element
 * @throws CoreException
 */
public IJavaElement create(IType type, IPackageFragment pack, String name, RpcType rpcType,
        IProgressMonitor monitor) throws CoreException {

    IJavaElement element = null;
    IType createdType = null;
    ImportsManager imports;
    ICompilationUnit connectedCU = null;
    current = type;
    lineDelimiter = System.getProperty("line.separator", "\n"); //$NON-NLS-N$

    try {
        ICompilationUnit parentCU = pack.createCompilationUnit(name + ".java", //$NON-NLS-N$
                "", true, new SubProgressMonitor(monitor, 1));
        parentCU.becomeWorkingCopy(new SubProgressMonitor(monitor, 1));
        connectedCU = parentCU;
        IBuffer buffer = parentCU.getBuffer();
        String simpleTypeStub = constructSimpleTypeStub(name);
        String content = CodeGeneration.getCompilationUnitContent(parentCU, null, null, simpleTypeStub,
                lineDelimiter);
        buffer.setContents(content);

        CompilationUnit astRoot = createASTForImports(parentCU);
        imports = new ImportsManager(astRoot);

        String typeContent;
        String annotation = "";
        List<String> interfaces = new ArrayList<String>();
        boolean isInterface = true;
        switch (rpcType) {
        case SERVICE:
            isInterface = false;
            break;
        case LOCATOR:
            isInterface = false;
            interfaces.add("com.google.web.bindery.requestfactory.shared.Locator"); //$NON-NLS-N$
            if (RequestFactoryUtils.shouldBeProxiedAsAnEntity(type)) {
                for (IMethod method : type.getMethods()) {
                    if (method.getElementName().equals("getId")) { //$NON-NLS-N$
                        entityIdType = Signature.toString(method.getReturnType());
                    }
                }
            } else {
                entityIdType = "Void"; //$NON-NLS-N$
            }
            break;
        case PROXY:
            if (RequestFactoryUtils.shouldBeProxiedAsAnEntity(current)) {
                interfaces.add("com.google.web.bindery.requestfactory.shared.EntityProxy"); //$NON-NLS-N$
            } else {
                interfaces.add("com.google.web.bindery.requestfactory.shared.ValueProxy");//$NON-NLS-N$
            }
            annotation = "@ProxyForName(value=\"" + current.getFullyQualifiedName() //$NON-NLS-N$
                    + "\",\nlocator = \"" + current.getFullyQualifiedName() + "Locator\")";
            break;
        case REQUEST:
            interfaces.add("com.google.web.bindery.requestfactory.shared.RequestContext");//$NON-NLS-N$
            annotation = "@ServiceName(\"" + serviceName //$NON-NLS-N$
                    + "\")";
            break;
        case REQ_FACTORY:
            interfaces.add("com.google.web.bindery.requestfactory.shared.RequestFactory"); //$NON-NLS-N$
            break;
        }

        typeContent = constructTypeStub(parentCU, name, isInterface, interfaces, annotation, imports);
        int index = content.lastIndexOf(simpleTypeStub);
        if (index == -1) {
            AbstractTypeDeclaration typeNode = (AbstractTypeDeclaration) astRoot.types().get(0);
            int start = ((ASTNode) typeNode.modifiers().get(0)).getStartPosition();
            int end = typeNode.getStartPosition() + typeNode.getLength();
            buffer.replace(start, end - start, typeContent);
        } else {
            buffer.replace(index, simpleTypeStub.length(), typeContent);
        }

        createdType = parentCU.getType(name);

        ICompilationUnit cu = createdType.getCompilationUnit();
        imports.create(false, new SubProgressMonitor(monitor, 1));
        cu.reconcile(ICompilationUnit.NO_AST, false, null, null);

        astRoot = createASTForImports(cu);
        imports = new ImportsManager(astRoot);

        switch (rpcType) {
        case SERVICE:
            constructServiceBody(createdType, imports, new SubProgressMonitor(monitor, 1));
            break;
        case LOCATOR:
            constructLocatorBody(createdType, imports, new SubProgressMonitor(monitor, 1));
            break;
        case PROXY:
            constructProxyBody(createdType, imports, new SubProgressMonitor(monitor, 1));
            break;
        case REQUEST:
            requestTypes.add(createdType);
            constructRequestBody(createdType, imports, monitor);
            break;

        case REQ_FACTORY:
            constructReqFactoryBody(createdType, imports, new SubProgressMonitor(monitor, 1));
            break;
        }

        imports.create(false, new SubProgressMonitor(monitor, 1));
        removeUnusedImports(cu, getExistingImports(astRoot), false);
        cu.reconcile(ICompilationUnit.NO_AST, false, null, null);

        ISourceRange range = createdType.getSourceRange();

        IBuffer buf = cu.getBuffer();
        String originalContent = buf.getText(range.getOffset(), range.getLength());

        String formattedContent = CodegenUtils.format(originalContent, CodeFormatter.K_CLASS_BODY_DECLARATIONS);
        buf.replace(range.getOffset(), range.getLength(), formattedContent);

        cu.commitWorkingCopy(true, new SubProgressMonitor(monitor, 1));

        element = cu.getPrimaryElement();

    } finally {
        if (connectedCU != null) {
            connectedCU.discardWorkingCopy();
        }
    }
    monitor.done();
    return element;
}

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();/*  ww  w  . j a v  a2 s  .c  om*/

        try {
            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.appengine.rpc.validators.JavaCompilationParticipant.java

License:Open Source License

@Override
public void reconcile(ReconcileContext context) {

    ICompilationUnit cu = context.getWorkingCopy();

    IType requestContext = null;//w w  w  .j  a v  a  2  s  .  co  m

    try {
        if (!cu.isConsistent()) {
            cu.reconcile(AST.JLS3, true, null, null);
            assert (cu.isConsistent());
        }

        // 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 (cu.findPrimaryType() == null) {
            return;
        }
        if (cuName == null || !cuName.equals(cu.findPrimaryType().getFullyQualifiedName())) {
            cuName = cu.findPrimaryType().getFullyQualifiedName();

            if (requestMap.containsKey(cuName)) {
                requestContext = requestMap.get(cuName);
            } else {
                requestContext = null;
            }
            // if there is no requestfactory implementation, no need to validate
        }
        if (requestContext != null) {
            CompilationUnit ast = context.getAST3();
            ArrayList<CategorizedProblem> finalProblemSet = new ArrayList<CategorizedProblem>();
            CategorizedProblem[] currentProblems = context.getProblems(GWTJavaProblem.MARKER_ID);
            if (currentProblems != null) {
                finalProblemSet.addAll(Arrays.asList(currentProblems));
            }
            RequestFactoryValidator validator = new RequestFactoryValidator(requestContext, projectEntities,
                    proxies);
            List<CategorizedProblem> reqFactoryProblems = validator.validate(ast);
            finalProblemSet.addAll(reqFactoryProblems);
            context.putProblems(GWTJavaProblem.MARKER_ID,
                    (finalProblemSet.size() > 0 ? finalProblemSet.toArray(EMPTY_PROBLEMS) : null));
        }
    } catch (JavaModelException e) {
        AppEngineRPCPlugin.log(e);
    }
}

From source file:com.google.gdt.eclipse.appengine.rpc.wizards.helpers.RpcServiceLayerCreator.java

License:Open Source License

private void addReqFactoryBody(IType type, IProgressMonitor monitor)
        throws MalformedTreeException, BadLocationException, CoreException {
    ICompilationUnit cu = type.getCompilationUnit();
    cu.becomeWorkingCopy(monitor);//  www. j a v a  2s .  c  o  m
    String source = cu.getSource();
    Document document = new Document(source);
    ASTParser parser = ASTParser.newParser(AST.JLS3);
    parser.setSource(cu);
    CompilationUnit astRoot = (CompilationUnit) parser.createAST(null);
    ASTRewrite rewrite = ASTRewrite.create(astRoot.getAST());
    ListRewrite listRewriter = null;
    AbstractTypeDeclaration declaration = (AbstractTypeDeclaration) astRoot.types().get(0);
    if (declaration != null) {
        listRewriter = rewrite.getListRewrite(declaration, declaration.getBodyDeclarationsProperty());
    }
    ImportRewrite importRewrite = CodeStyleConfiguration.createImportRewrite(astRoot, true);

    StringBuffer buf = new StringBuffer();
    for (IType request : requestTypes) {
        importRewrite.addImport(request.getFullyQualifiedName());
        buf.append(request.getElementName());
        buf.append(" "); //$NON-NLS-N$
        String name = request.getElementName();
        buf.append(name.substring(0, 1).toLowerCase() + name.substring(1));
        buf.append("();"); //$NON-NLS-N$
        buf.append(lineDelimiter);
    }

    MethodDeclaration methodDecl = (MethodDeclaration) listRewriter.getASTRewrite()
            .createStringPlaceholder(buf.toString(), ASTNode.METHOD_DECLARATION);
    listRewriter.insertLast(methodDecl, null);
    TextEdit edits = rewrite.rewriteAST(document, cu.getJavaProject().getOptions(true));
    edits.addChild(importRewrite.rewriteImports(monitor));
    edits.apply(document);
    cu.getBuffer().setContents(document.get());
    cu.reconcile(ICompilationUnit.NO_AST, false, null, null);
    ISourceRange range = type.getSourceRange();
    IBuffer buffer = cu.getBuffer();
    String originalContent = buffer.getText(range.getOffset(), range.getLength());
    String formattedContent = format(originalContent, CodeFormatter.K_CLASS_BODY_DECLARATIONS);
    buffer.replace(range.getOffset(), range.getLength(), formattedContent);
    cu.commitWorkingCopy(true, monitor);
    cu.discardWorkingCopy();
}

From source file:com.google.gwt.eclipse.core.editors.java.JsniMethodBodyCompletionProposalComputer.java

License:Open Source License

public List<ICompletionProposal> computeCompletionProposals(ContentAssistInvocationContext context,
        IProgressMonitor monitor) {/*  ww  w .  j  ava  2 s  .co  m*/
    if (!(context instanceof JavaContentAssistInvocationContext)) {
        // Not in a java content assist content.
        return NO_PROPOSALS;
    }

    try {
        JavaContentAssistInvocationContext jcaic = (JavaContentAssistInvocationContext) context;
        ICompilationUnit compilationUnit = jcaic.getCompilationUnit();

        /*
         * Resolves issue 3560,
         * http://code.google.com/p/google-web-toolkit/issues/detail?id=3650. We
         * need to have a reconciled compilation unit if we are to use it, but we
         * don't want to tickle the hierarchy view bug.
         */
        compilationUnit.reconcile(ICompilationUnit.NO_AST, false, null, null);

        int invocationOffset = jcaic.getInvocationOffset();
        IJavaElement elementAt = compilationUnit.getElementAt(invocationOffset);

        if (elementAt == null) {
            // Can't determine the element at the specified offset.
            return NO_PROPOSALS;
        }

        if (IJavaElement.METHOD != elementAt.getElementType()) {
            // Not a method.
            return NO_PROPOSALS;
        }

        IMethod method = (IMethod) elementAt;

        IType thisType = method.getDeclaringType();
        if (thisType.isInterface()) {
            // Don't propose anything for interfaces.
            return NO_PROPOSALS;
        }

        ISourceRange sourceRange = method.getSourceRange();
        if (sourceRange == null) {
            // No source code.
            // TODO: Is this possible?
            return NO_PROPOSALS;
        }

        String methodSource = method.getSource();
        int invocationIdx = invocationOffset - sourceRange.getOffset();

        // Sometimes, if incomplete JSNI method has /* and is followed by any global 
        // comment of format /*..*/, compilation unit separates the code after
        // incomplete JSNI method's /* as a separate block from the incomplete method.
        // So we need to check whether the block before the invocation offset's block
        // is the incomplete JSNI method that we are interested in.

        IJavaElement prevElement = compilationUnit.getElementAt(sourceRange.getOffset() - 1);
        if (prevElement != null && IJavaElement.METHOD == prevElement.getElementType()) {

            IMethod prevMethod = (IMethod) prevElement;

            if ((prevMethod.getDeclaringType().isInterface() == false)
                    && (Flags.isNative(prevMethod.getFlags()) == true)) {

                String prevMethodSource = prevMethod.getSource();
                if (prevMethodSource.trim().endsWith(")") == true) {
                    methodSource = prevMethodSource.concat(methodSource);
                    method = prevMethod;
                    invocationIdx += prevMethodSource.length();
                }
            }
        }

        int flags = method.getFlags();
        if (!Flags.isNative(flags)) {
            // If the method is not native then no proposals.
            return NO_PROPOSALS;
        }

        // Eliminating comments that might precede native method declaration, so that
        // following code can safely assume first ')' found is that of function declaration.
        int idxMultiLineComment = methodSource.trim().indexOf("/*");
        int idxSingleLineComment = methodSource.trim().indexOf("//");
        while ((idxMultiLineComment == 0) || (idxSingleLineComment == 0)) {
            if (idxMultiLineComment == 0) {
                invocationIdx -= methodSource.indexOf("*/") + 2;
                methodSource = methodSource.substring(methodSource.indexOf("*/") + 2);
            } else {
                invocationIdx -= methodSource.indexOf('\n') + 1;
                methodSource = methodSource.substring(methodSource.indexOf('\n') + 1);
            }
            idxMultiLineComment = methodSource.trim().indexOf("/*");
            idxSingleLineComment = methodSource.trim().indexOf("//");
        }

        // Eliminating any JSNI method that might follow the JSNI method in consideration.
        int jsniMethodOpenIdx = methodSource.indexOf(JSNI_METHOD_OPEN_BRACE);
        if (jsniMethodOpenIdx != -1) {
            int jsniMethodCloseBracketIdx = methodSource.indexOf(")");
            String tempString = methodSource.substring(jsniMethodCloseBracketIdx, jsniMethodOpenIdx);
            if (tempString.trim().length() != 1) {
                methodSource = methodSource.substring(0, jsniMethodOpenIdx - 1);
            } else {
                int nextJsniMethodOpenIdx = methodSource.substring(jsniMethodOpenIdx + 4)
                        .indexOf(JSNI_METHOD_OPEN_BRACE);
                if (nextJsniMethodOpenIdx != -1) {
                    nextJsniMethodOpenIdx += jsniMethodOpenIdx + 4;
                    methodSource = methodSource.substring(0, nextJsniMethodOpenIdx - 1);
                }
            }
        }

        // Check if the JSNI method is already complete.
        if (methodSource.indexOf("}-*/;") != -1) {
            // JSNI method is complete.
            return NO_PROPOSALS;
        }

        // Check position of invocation offset.
        int numCharsFilled = 0, numCharsToOverwrite = 0;

        String tempString = "";
        if (methodSource.substring(methodSource.indexOf(")") + 1).trim().indexOf("/") != -1) {
            tempString = methodSource.substring(methodSource.indexOf(")"), methodSource.indexOf("/"));
        }

        if ((methodSource.substring(methodSource.indexOf(")") + 1).trim().indexOf("/") == 0)
                && (tempString.indexOf('\n') == -1)) {

            int jsniMethodOpenSlashIdx = methodSource.indexOf("/");

            if (jsniMethodOpenSlashIdx > invocationIdx) {
                // Invocation index is placed before JSNI open slash.
                return NO_PROPOSALS;
            }

            String jsniCompletedString = methodSource.substring(jsniMethodOpenSlashIdx, invocationIdx);

            if (jsniCompletedString.indexOf(JSNI_METHOD_OPEN_BRACE) != -1) {
                jsniCompletedString = jsniCompletedString.trim();
            }

            if (JSNI_METHOD_OPEN_BRACE.startsWith(jsniCompletedString)) {
                numCharsFilled = jsniCompletedString.length();
            } else {
                // Invocation index placement does not allow auto-completion.
                return NO_PROPOSALS;
            }
        } else {
            int jsniMethodCloseBracketIdx = methodSource.indexOf(")") + 1;

            if (jsniMethodCloseBracketIdx > invocationIdx) {
                // Invocation index is not placed after method's close bracket.
                return NO_PROPOSALS;
            }
            if (methodSource.substring(jsniMethodCloseBracketIdx, invocationIdx).trim().length() != 0) {
                // Do not auto-complete if there is anything other than space between the two indices.
                return NO_PROPOSALS;
            }
        }

        methodSource = methodSource.substring(invocationIdx);
        int endIdx = methodSource.length();
        if (methodSource.indexOf(" ") != -1) {
            endIdx = methodSource.indexOf(" ");
            if (methodSource.indexOf("\n") != -1 && (endIdx > methodSource.indexOf("\n"))) {
                endIdx = methodSource.indexOf("\n");
            }
        } else if (methodSource.indexOf("\n") != -1) {
            endIdx = methodSource.indexOf("\n");
        }

        numCharsToOverwrite = methodSource.substring(0, endIdx).trim().length();

        IDocument document = jcaic.getDocument();
        int lineOfInvocationOffset = document.getLineOfOffset(invocationOffset);
        int lineOffset = document.getLineOffset(lineOfInvocationOffset);

        IJavaProject project = jcaic.getProject();
        int indentationUnits = measureIndentationUnits(document, lineOfInvocationOffset, lineOffset, project);

        List<ICompletionProposal> proposals = new ArrayList<ICompletionProposal>();

        proposeEmptyJsniBlock(project, method, invocationOffset, indentationUnits, proposals, numCharsFilled,
                numCharsToOverwrite);

        boolean isStatic = Flags.isStatic(flags);
        if (method.getReturnType().equals(Signature.SIG_VOID)) {
            proposeSetters(project, method, invocationOffset, indentationUnits, isStatic, proposals,
                    numCharsFilled, numCharsToOverwrite);
        } else {
            proposeGetters(project, method, invocationOffset, indentationUnits, isStatic, proposals,
                    numCharsFilled, numCharsToOverwrite);
        }
        return proposals;
    } catch (JavaModelException e) {
        // Default to no proposals.
    } catch (BadLocationException e) {
        // Default to no proposals.
    }

    return NO_PROPOSALS;
}

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 w  ww.j  a va 2 s  .  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);
    }
}