Example usage for org.eclipse.jdt.core.dom StringLiteral getStartPosition

List of usage examples for org.eclipse.jdt.core.dom StringLiteral getStartPosition

Introduction

In this page you can find the example usage for org.eclipse.jdt.core.dom StringLiteral getStartPosition.

Prototype

public final int getStartPosition() 

Source Link

Document

Returns the character index into the original source file indicating where the source fragment corresponding to this node begins.

Usage

From source file:org.eclipse.babel.tapiji.tools.java.ui.MessageCompletionProposalComputer.java

License:Open Source License

@Override
public List<ICompletionProposal> computeCompletionProposals(ContentAssistInvocationContext context,
        IProgressMonitor monitor) {//from ww  w.j  a v  a  2 s. c om

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

    if (!InternationalizationNature.hasNature(
            ((JavaContentAssistInvocationContext) context).getCompilationUnit().getResource().getProject())) {
        return completions;
    }

    try {
        JavaContentAssistInvocationContext javaContext = ((JavaContentAssistInvocationContext) context);
        CompletionContext coreContext = javaContext.getCoreContext();

        int tokenStart = coreContext.getTokenStart();
        int tokenEnd = coreContext.getTokenEnd();
        int tokenOffset = coreContext.getOffset();
        boolean isStringLiteral = coreContext.getTokenKind() == CompletionContext.TOKEN_KIND_STRING_LITERAL;

        if (cu == null) {
            manager = ResourceBundleManager
                    .getManager(javaContext.getCompilationUnit().getResource().getProject());

            resource = javaContext.getCompilationUnit().getResource();

            csav = new ResourceAuditVisitor(null, manager.getProject().getName());

            cu = ASTutilsUI.getAstRoot(ASTutilsUI.getCompilationUnit(resource));

            cu.accept(csav);
        }

        if (coreContext.getTokenKind() == CompletionContext.TOKEN_KIND_NAME
                && (tokenEnd + 1) - tokenStart > 0) {

            // Cal10n extension
            String[] metaData = ASTutils.getCal10nEnumLiteralDataAtPos(manager.getProject().getName(), cu,
                    tokenOffset - 1);

            if (metaData != null) {
                completions.add(new KeyRefactoringProposal(tokenOffset, metaData[1],
                        manager.getProject().getName(), metaData[0], metaData[2]));
            }

            return completions;
        }

        if (tokenStart < 0) {
            // is string literal in front of cursor?
            StringLiteral strLit = ASTutils.getStringLiteralAtPos(cu, tokenOffset - 1);
            if (strLit != null) {
                tokenStart = strLit.getStartPosition();
                tokenEnd = tokenStart + strLit.getLength() - 1;
                tokenOffset = tokenOffset - 1;
                isStringLiteral = true;
            } else {
                tokenStart = tokenOffset;
                tokenEnd = tokenOffset;
            }
        }

        if (isStringLiteral) {
            tokenStart++;
        }

        tokenEnd = Math.max(tokenEnd, tokenStart);

        String fullToken = "";

        if (tokenStart < tokenEnd) {
            fullToken = context.getDocument().get(tokenStart, tokenEnd - tokenStart);
        }

        // Check if the string literal is up to be written within the
        // context of a resource-bundle accessor method
        if (csav.getKeyAt(new Long(tokenOffset)) != null && isStringLiteral) {
            completions.addAll(getResourceBundleCompletionProposals(tokenStart, tokenEnd, tokenOffset,
                    isStringLiteral, fullToken, manager, csav, resource));
        } else if (csav.getRBReferenceAt(new Long(tokenOffset)) != null && isStringLiteral) {
            completions.addAll(getRBReferenceCompletionProposals(tokenStart, tokenEnd, fullToken,
                    isStringLiteral, manager, resource));
        } else {
            completions.addAll(getBasicJavaCompletionProposals(tokenStart, tokenEnd, tokenOffset, fullToken,
                    isStringLiteral, manager, csav, resource));
        }
        if (completions.size() == 1) {
            completions.add(new NoActionProposal());
        }

    } catch (Exception e) {
        Logger.logError(e);
    }
    return completions;
}

From source file:org.eclipse.babel.tapiji.tools.java.util.ASTutils.java

License:Open Source License

public static SLLocation resolveResourceBundleLocation(MethodInvocation methodInvocation,
        MethodParameterDescriptor rbDefinition,
        Map<IVariableBinding, VariableDeclarationFragment> variableBindingManagers) {
    SLLocation bundleDesc = null;/*from  w  w  w  .j a  v a 2  s .  c o  m*/

    if (methodInvocation.getExpression() instanceof SimpleName) {
        SimpleName vName = (SimpleName) methodInvocation.getExpression();
        IVariableBinding vBinding = (IVariableBinding) vName.resolveBinding();
        VariableDeclarationFragment dec = variableBindingManagers.get(vBinding);

        if (dec.getInitializer() instanceof MethodInvocation) {
            MethodInvocation init = (MethodInvocation) dec.getInitializer();

            // Check declaring class
            boolean isValidClass = false;
            ITypeBinding type = init.resolveMethodBinding().getDeclaringClass();
            while (type != null) {
                if (type.getQualifiedName().equals(rbDefinition.getDeclaringClass())) {
                    isValidClass = true;
                    break;
                } else {
                    if (rbDefinition.isConsiderSuperclass()) {
                        type = type.getSuperclass();
                    } else {
                        type = null;
                    }
                }

            }
            if (!isValidClass) {
                return null;
            }

            boolean isValidMethod = false;
            for (String mn : rbDefinition.getMethodName()) {
                if (init.getName().getFullyQualifiedName().equals(mn)) {
                    isValidMethod = true;
                    break;
                }
            }
            if (!isValidMethod) {
                return null;
            }

            // retrieve bundlename
            if (init.arguments().size() < rbDefinition.getPosition() + 1) {
                return null;
            }

            StringLiteral bundleLiteral = ((StringLiteral) init.arguments().get(rbDefinition.getPosition()));
            bundleDesc = new SLLocation(null, bundleLiteral.getStartPosition(),
                    bundleLiteral.getLength() + bundleLiteral.getStartPosition(),
                    bundleLiteral.getLiteralValue());
        }
    }

    return bundleDesc;
}

From source file:org.eclipse.babel.tapiji.tools.java.util.ASTutils.java

License:Open Source License

public static boolean existsNonInternationalisationComment(StringLiteral literal) throws BadLocationException {
    CompilationUnit cu = (CompilationUnit) literal.getRoot();
    ICompilationUnit icu = (ICompilationUnit) cu.getJavaElement();

    IDocument doc = null;/*from  w ww.jav  a  2s.co  m*/
    try {
        doc = new Document(icu.getSource());
    } catch (JavaModelException e) {
        Logger.logError(e);
    }

    // get whole line in which string literal
    int lineNo = doc.getLineOfOffset(literal.getStartPosition());
    int lineOffset = doc.getLineOffset(lineNo);
    int lineLength = doc.getLineLength(lineNo);
    String lineOfString = doc.get(lineOffset, lineLength);

    // search for a line comment in this line
    int indexComment = lineOfString.indexOf("//");

    if (indexComment == -1) {
        return false;
    }

    String comment = lineOfString.substring(indexComment);

    // remove first "//" of line comment
    comment = comment.substring(2).toLowerCase();

    // split line comments, necessary if more NON-NLS comments exist in one line, eg.: $NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3
    String[] comments = comment.split("//");

    for (String commentFrag : comments) {
        commentFrag = commentFrag.trim();

        // if comment match format: "$non-nls$" then ignore whole line
        if (commentFrag.matches("^\\$non-nls\\$$")) {
            return true;

            // if comment match format: "$non-nls-{number}$" then only
            // ignore string which is on given position
        } else if (commentFrag.matches("^\\$non-nls-\\d+\\$$")) {
            int iString = findNonInternationalisationPosition(cu, doc, literal.getStartPosition()) + 1;
            int iComment = new Integer(commentFrag.substring(9, 10));
            if (iString == iComment) {
                return true;
            }
        }
    }
    return false;
}

From source file:org.eclipse.babel.tapiji.tools.java.visitor.ResourceAuditVisitor.java

License:Open Source License

@Override
public boolean visit(StringLiteral stringLiteral) {
    try {/* w  w w  . jav  a2  s. co  m*/
        ASTNode parent = stringLiteral.getParent();
        ResourceBundleManager manager = ResourceBundleManager.getManager(projectName);

        if (manager == null) {
            return false;
        }

        if (parent instanceof MethodInvocation) {
            MethodInvocation methodInvocation = (MethodInvocation) parent;

            IRegion region = new Region(stringLiteral.getStartPosition(), stringLiteral.getLength());

            // Check if this method invokes the getString-Method on a
            // ResourceBundle Implementation
            if (ASTutils.isMatchingMethodParamDesc(methodInvocation, stringLiteral,
                    ASTutils.getRBAccessorDesc())) {
                // Check if the given Resource-Bundle reference is broken
                SLLocation rbName = ASTutils.resolveResourceBundleLocation(methodInvocation,
                        ASTutils.getRBDefinitionDesc(), variableBindingManagers);
                if (rbName == null
                        || manager.isKeyBroken(rbName.getLiteral(), stringLiteral.getLiteralValue())) {
                    // report new problem
                    SLLocation desc = new SLLocation(file, stringLiteral.getStartPosition(),
                            stringLiteral.getStartPosition() + stringLiteral.getLength(),
                            stringLiteral.getLiteralValue());
                    desc.setData(rbName);
                    brokenStrings.add(desc);
                }

                // store position of resource-bundle access
                keyPositions.put(Long.valueOf(stringLiteral.getStartPosition()), region);
                bundleKeys.put(region, stringLiteral.getLiteralValue());
                bundleReferences.put(region, rbName.getLiteral());
                return false;
            } else if (ASTutils.isMatchingMethodParamDesc(methodInvocation, stringLiteral,
                    ASTutils.getRBDefinitionDesc())) {
                rbDefReferences.put(Long.valueOf(stringLiteral.getStartPosition()), region);
                boolean referenceBroken = true;
                for (String bundle : manager.getResourceBundleIdentifiers()) {
                    if (bundle.trim().equals(stringLiteral.getLiteralValue())) {
                        referenceBroken = false;
                    }
                }
                if (referenceBroken) {
                    this.brokenRBReferences.add(new SLLocation(file, stringLiteral.getStartPosition(),
                            stringLiteral.getStartPosition() + stringLiteral.getLength(),
                            stringLiteral.getLiteralValue()));
                }

                return false;
            }
        }

        // check if string is followed by a "$NON-NLS$" line comment
        if (ASTutils.existsNonInternationalisationComment(stringLiteral)) {
            return false;
        }

        // constant string literal found
        constants.add(new SLLocation(file, stringLiteral.getStartPosition(),
                stringLiteral.getStartPosition() + stringLiteral.getLength(), stringLiteral.getLiteralValue()));
    } catch (Exception e) {
        e.printStackTrace();
    }
    return false;
}

From source file:org.eclipse.wb.internal.core.nls.bundle.AbstractBundleSource.java

License:Open Source License

/**
 * Remove "//$NON-NLS-xxx" comment for given {@link StringLiteral}.
 *//*  w  ww  .  j a  v  a  2 s  .co  m*/
protected final void removeNonNLSComment(StringLiteral literal) throws Exception {
    AstEditor editor = m_root.getEditor();
    if (literal != null) {
        int index = editor.getStringLiteralNumberOnLine(literal);
        if (index != -1) {
            String comment = "//$NON-NLS-" + (1 + index) + "$";
            editor.removeEndOfLineComment(literal.getStartPosition(), comment);
        }
    }
}

From source file:org.eclipse.wb.internal.core.utils.ast.AstEditor.java

License:Open Source License

/**
 * @return the index of passed {@link StringLiteral} on same line.
 *//*  ww  w.j a v  a  2 s.  c  o  m*/
public int getStringLiteralNumberOnLine(StringLiteral stringLiteral) {
    final int slLine = getLineNumber(stringLiteral.getStartPosition());
    // find shortest node that fills full line
    ASTNode lineNode = stringLiteral;
    while (getLineNumber(lineNode.getStartPosition()) == slLine
            && getLineNumber(lineNode.getStartPosition() + lineNode.getLength()) == slLine) {
        lineNode = lineNode.getParent();
    }
    // find all literals on this line
    final List<StringLiteral> literals = Lists.newArrayList();
    lineNode.accept(new ASTVisitor() {
        @Override
        public void endVisit(StringLiteral literal) {
            if (getLineNumber(literal.getStartPosition()) == slLine) {
                literals.add(literal);
            }
        }
    });
    // find index of given literal
    return literals.indexOf(stringLiteral);
}

From source file:org.eclipse.wst.xml.search.editor.statics.JavaStringLiteralDocumentVisitor.java

License:Open Source License

public void visit(Object selectedNode, IFile file, final String matching, final boolean startsWith,
        final IStaticValueCollector collector) {
    final IFile javaFile = getFile(selectedNode, file);

    final ASTParser parser = ASTParser.newParser(AST.JLS3);
    parser.setResolveBindings(true);//from ww w  .java  2s  . com
    parser.setSource(JavaCore.createCompilationUnitFrom(javaFile));
    final CompilationUnit cu = (CompilationUnit) parser.createAST(null);

    ASTVisitor visitor = new ASTVisitor() {

        public boolean visit(org.eclipse.jdt.core.dom.StringLiteral node) {

            ASTNode parent = accept(node);
            if (parent != null) {
                String stringValue = node.getLiteralValue();

                boolean match = (startsWith ? stringValue.startsWith(matching) : stringValue.equals(matching));
                if (match) {
                    collector.add(new StaticValueDocument(stringValue, parent.toString(),
                            node.getStartPosition() + 1, stringValue.length(), javaFile));
                }
            }

            return true;
        };

    };
    cu.accept(visitor);
}

From source file:org.hibernate.eclipse.jdt.ui.internal.HQLQuickAssistProcessor.java

License:Open Source License

public IJavaCompletionProposal[] getAssists(final IInvocationContext context, IProblemLocation[] locations)
        throws CoreException {

    IJavaCompletionProposal[] result = new IJavaCompletionProposal[0];
    if (!hasAssists(context))
        return result;

    ASTNode coveringNode = context.getCoveringNode();
    if (!(coveringNode instanceof StringLiteral)) {
        return result;
    }/*  w  ww .j a v a  2 s  . c o  m*/

    final StringLiteral stringLiteral = (StringLiteral) coveringNode;
    String contents = stringLiteral.getLiteralValue();
    result = new IJavaCompletionProposal[1];
    result[0] = new ExternalActionQuickAssistProposal(contents,
            EclipseImages.getImage(ImageConstants.HQL_EDITOR),
            JdtUiMessages.HQLQuickAssistProcessor_copy_to_hql_editor, context) {
        public void apply(IDocument document) {
            IEditorPart editorPart = Activator.getDefault().getWorkbench().getActiveWorkbenchWindow()
                    .getActivePage().getActiveEditor();
            ITextEditor[] textEditors = OpenMappingUtils.getTextEditors(editorPart);
            if (textEditors.length == 0)
                return;
            Point position = new Point(stringLiteral.getStartPosition() + 1, stringLiteral.getLength() - 2);
            new SaveQueryEditorListener(textEditors[0], getName(), getContents(), position,
                    SaveQueryEditorListener.HQLEditor);
        }
    };

    return result;
}

From source file:org.iti.sqlschemacomparerplugin.utils.ParseUtils.java

License:Open Source License

public static Map<String, Integer> getAllJavaStrings(IFile file) {
    Map<String, Integer> javaStringsAndLineNumbers = new HashMap<>();
    JavaStringFinder visitor = new JavaStringFinder();
    ICompilationUnit unit = JavaCore.createCompilationUnitFrom(file);

    CompilationUnit node = (CompilationUnit) parse(unit);

    node.accept(visitor);/* w  w w . j  av  a 2 s  .  c om*/

    for (StringLiteral literal : visitor.javaStringLiterals) {
        javaStringsAndLineNumbers.put(literal.getLiteralValue(),
                node.getLineNumber(literal.getStartPosition()));
    }

    return javaStringsAndLineNumbers;
}

From source file:org.jboss.tools.arquillian.core.internal.builder.ArquillianBuilder.java

License:Open Source License

private void validateArchiveName(final ICompilationUnit unit, IJavaProject project, final Integer severity)
        throws CoreException {
    final CompilationUnit root = getAST(unit, project);
    final List<MethodDeclaration> deploymentMethods = getDeploymentMethods(root);
    for (MethodDeclaration methodDeclaration : deploymentMethods) {
        methodDeclaration.accept(new ASTVisitor() {

            @Override//from   w w  w  . j  av a2 s  .  co  m
            public boolean visit(MethodInvocation node) {
                boolean isCreateMethod = false;
                StringLiteral archiveName = null;
                if (node.getName() != null && "create".equals(node.getName().getIdentifier())) { //$NON-NLS-1$
                    List arguments = node.arguments();
                    if (arguments.size() == 2) {
                        Object o = arguments.get(1);
                        if (o instanceof StringLiteral) {
                            archiveName = (StringLiteral) o;
                        }
                    }
                    Expression expression = node.getExpression();
                    if (expression instanceof SimpleName) {
                        if ("ShrinkWrap".equals(((SimpleName) expression).getIdentifier())) { //$NON-NLS-1$
                            isCreateMethod = true;
                        }
                    }
                    if (expression instanceof QualifiedName) {
                        if ("org.jboss.shrinkwrap.api.ShrinkWrap" //$NON-NLS-1$
                                .equals(((QualifiedName) expression).getName().getIdentifier())) {
                            isCreateMethod = true;
                        }
                    }
                }
                if (isCreateMethod && archiveName != null) {
                    IMethodBinding binding = node.resolveMethodBinding();
                    ITypeBinding[] types = binding.getParameterTypes();
                    if (types.length == 2) {
                        ITypeBinding archiveType = types[0];
                        if (archiveType.isClass()) {
                            String extension = null;
                            ITypeBinding[] typeArguments = archiveType.getTypeArguments();
                            if (typeArguments.length == 1) {
                                ITypeBinding typeArgument = typeArguments[0];
                                if (ArquillianUtility.ORG_JBOSS_SHRINKWRAP_API_SPEC_WEB_ARCHIVE
                                        .equals(typeArgument.getBinaryName())) {
                                    extension = ".war"; //$NON-NLS-1$
                                }
                                if (ArquillianUtility.ORG_JBOSS_SHRINKWRAP_API_SPEC_JAVA_ARCHIVE
                                        .equals(typeArgument.getBinaryName())) {
                                    extension = ".jar"; //$NON-NLS-1$
                                }
                                if (ArquillianUtility.ORG_JBOSS_SHRINKWRAP_API_SPEC_ENTERPRISE_ARCHIVE
                                        .equals(typeArgument.getBinaryName())) {
                                    extension = ".ear"; //$NON-NLS-1$
                                }
                                if (ArquillianUtility.ORG_JBOSS_SHRINKWRAP_API_SPEC_RESOURCEADAPTER_ARCHIVE
                                        .equals(typeArgument.getBinaryName())) {
                                    extension = ".rar"; //$NON-NLS-1$
                                }
                            }
                            String value = archiveName.getLiteralValue();
                            if (extension != null && value != null
                                    && (!value.endsWith(extension) || value.trim().length() <= 4)) {
                                try {
                                    IMarker marker = storeProblem(unit,
                                            "Archive name is invalid. A name with the " + extension
                                                    + " extension is expected.",
                                            severity, ArquillianConstants.MARKER_INVALID_ARCHIVE_NAME_ID);
                                    if (marker != null) {
                                        int start = archiveName.getStartPosition();
                                        int end = start + archiveName.getLength();
                                        int lineNumber = root.getLineNumber(start);
                                        marker.setAttribute(IMarker.CHAR_START, start + 1);
                                        marker.setAttribute(IMarker.CHAR_END, end - 1);
                                        marker.setAttribute(IMarker.LINE_NUMBER, lineNumber);
                                        marker.setAttribute(ArquillianConstants.OLD_ARCHIVE_NAME, value);
                                        marker.setAttribute(ArquillianConstants.ARCHIVE_EXTENSION, extension);
                                    }
                                } catch (CoreException e) {
                                    ArquillianCoreActivator.log(e);
                                }
                            }
                        }

                    }

                }
                return true;
            }

        });
    }

}