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

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

Introduction

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

Prototype

public final int getLength() 

Source Link

Document

Returns the length in characters of the original source file indicating where the source fragment corresponding to this node ends.

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) {// w ww. jav  a 2 s.  c o m

    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 ww.ja  v a  2  s .c om

    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.visitor.ResourceAuditVisitor.java

License:Open Source License

@Override
public boolean visit(StringLiteral stringLiteral) {
    try {/* w w  w .j  av  a  2s .  c  o 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.jpt.jpa.ui.internal.jpql.JpaJpqlJavaCompletionProposalComputer.java

License:Open Source License

@SuppressWarnings("unchecked")
private String retrieveQuery(NormalAnnotation annotation, int[] tokenStart, int[] tokenEnd, int[] position) {

    for (MemberValuePair pair : (List<MemberValuePair>) annotation.values()) {
        org.eclipse.jdt.core.dom.Expression expression = pair.getValue();

        if (isInsideNode(expression, tokenStart[0], tokenEnd[0])) {
            Expression child = pair.getValue();

            // Single string
            if (child.getNodeType() == ASTNode.STRING_LITERAL) {
                StringLiteral literal = (StringLiteral) pair.getValue();
                return unquotedString(literal.getEscapedValue());
            }//from  w w w  .j a v  a  2s  .  c o  m

            // Build the JPQL query from the concatenated strings
            if (child.getNodeType() == ASTNode.INFIX_EXPRESSION) {

                StringBuilder sb = new StringBuilder();
                boolean adjustPosition = true;

                for (Expression childNode : children((InfixExpression) child)) {

                    StringLiteral literal = (StringLiteral) childNode;
                    sb.append(unquotedString(literal.getEscapedValue()));

                    if (adjustPosition && !isInsideNode(literal, tokenEnd[0], tokenEnd[0])) {
                        position[0] += (literal.getLength() - 2);
                    } else {
                        adjustPosition = false;
                    }
                }

                // Now adjust the start and end offsets so it includes the entire InfixExpression
                // because content assist will only replace one string literal and right now we
                // only support replacing the entire string
                tokenStart[0] = child.getStartPosition();
                tokenEnd[0] = child.getStartPosition() + child.getLength() - 1;

                return sb.toString();
            }
        }
    }

    return StringTools.EMPTY_STRING;
}

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;
    }/*from  w w  w .  java  2s  .c om*/

    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.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  a  2 s .c  om
            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;
            }

        });
    }

}

From source file:org.springframework.ide.vscode.boot.java.livehover.ActiveProfilesProvider.java

License:Open Source License

private static Optional<Range> rangeOf(TextDocument doc, StringLiteral node) {
    try {/* ww w. ja  v a 2  s. c  o  m*/
        int start = node.getStartPosition();
        int end = start + node.getLength();
        if (doc.getSafeChar(start) == '"') {
            start++;
        }
        if (doc.getSafeChar(end - 1) == '"') {
            end--;
        }
        return Optional.of(doc.toRange(start, end - start));
    } catch (Exception e) {
        log.error("", e);
        return Optional.empty();
    }
}

From source file:org.springframework.ide.vscode.boot.java.requestmapping.WebfluxPathFinder.java

License:Open Source License

@Override
public boolean visit(MethodInvocation node) {
    boolean visitChildren = true;

    if (node != this.root) {
        IMethodBinding methodBinding = node.resolveMethodBinding();

        try {//from  w  ww.ja  v  a 2  s .  c o  m
            if (methodBinding != null && methodBinding.getDeclaringClass() != null
                    && WebfluxUtils.REQUEST_PREDICATES_TYPE
                            .equals(methodBinding.getDeclaringClass().getBinaryName())) {

                String name = methodBinding.getName();
                if (name != null && WebfluxUtils.REQUEST_PREDICATE_ALL_PATH_METHODS.contains(name)) {
                    StringLiteral stringLiteral = WebfluxUtils.extractStringLiteralArgument(node);
                    if (stringLiteral != null) {
                        Range range = doc.toRange(stringLiteral.getStartPosition(), stringLiteral.getLength());
                        path.add(new WebfluxRouteElement(stringLiteral.getLiteralValue(), range));
                    }
                }
            }
        } catch (BadLocationException e) {
            // ignore
        }

        if (WebfluxUtils.isRouteMethodInvocation(methodBinding)) {
            visitChildren = false;
        }

    }
    return visitChildren;
}

From source file:org.springframework.ide.vscode.boot.java.requestmapping.WebfluxRouterSymbolProvider.java

License:Open Source License

private WebfluxRouteElement[] extractPath(MethodInvocation routerInvocation, TextDocument doc) {
    WebfluxPathFinder pathFinder = new WebfluxPathFinder(routerInvocation, doc);
    List<?> arguments = routerInvocation.arguments();
    for (Object argument : arguments) {
        if (argument != null && argument instanceof ASTNode) {
            ((ASTNode) argument).accept(pathFinder);
        }//from   www.j  av a  2s .co m
    }

    List<WebfluxRouteElement> path = pathFinder.getPath();

    extractNestedValue(routerInvocation, path, (methodInvocation) -> {
        IMethodBinding methodBinding = methodInvocation.resolveMethodBinding();
        String methodName = methodBinding.getName();

        try {
            if (WebfluxUtils.REQUEST_PREDICATE_PATH_METHOD.equals(methodName)) {
                StringLiteral stringLiteral = WebfluxUtils.extractStringLiteralArgument(methodInvocation);
                if (stringLiteral != null) {
                    Range range = doc.toRange(stringLiteral.getStartPosition(), stringLiteral.getLength());
                    return new WebfluxRouteElement(stringLiteral.getLiteralValue(), range);
                }
            }
        } catch (BadLocationException e) {
            // ignore
        }
        return null;
    });

    return (WebfluxRouteElement[]) path.toArray(new WebfluxRouteElement[path.size()]);
}