/**
   * Returns the qualified signature corresponding to <code>signature</code>.
   *
   * @param signature the signature to qualify
   * @param context the type inside which an unqualified type will be resolved to find the
   *     qualifier, or <code>null</code> if no context is available
   * @return the qualified signature
   */
  public static String qualifySignature(final String signature, final IType context) {
    if (context == null) return signature;

    String qualifier = Signature.getSignatureQualifier(signature);
    if (qualifier.length() > 0) return signature;

    String elementType = Signature.getElementType(signature);
    String erasure = Signature.getTypeErasure(elementType);
    String simpleName = Signature.getSignatureSimpleName(erasure);
    String genericSimpleName = Signature.getSignatureSimpleName(elementType);

    int dim = Signature.getArrayCount(signature);

    try {
      String[][] strings = context.resolveType(simpleName);
      if (strings != null && strings.length > 0) qualifier = strings[0][0];
    } catch (JavaModelException e) {
      // ignore - not found
    }

    if (qualifier.length() == 0) return signature;

    String qualifiedType = Signature.toQualifiedName(new String[] {qualifier, genericSimpleName});
    String qualifiedSignature = Signature.createTypeSignature(qualifiedType, true);
    String newSignature = Signature.createArraySignature(qualifiedSignature, dim);

    return newSignature;
  }
Beispiel #2
0
 public static String getReturnTypeString(IMethod method, boolean classTypesOnly) {
   try {
     String qualifiedReturnType = Signature.getReturnType(method.getSignature());
     if (!classTypesOnly
         || qualifiedReturnType.startsWith("L")
         || qualifiedReturnType.startsWith("Q")) {
       return Signature.getSignatureSimpleName(qualifiedReturnType.replace('/', '.'));
     }
   } catch (IllegalArgumentException e) {
   } catch (JavaModelException e) {
   }
   return null;
 }
 /**
  * Builds a string of the constructor parameters.
  *
  * @param type The type containing the fields.
  * @param fields The array of fields.
  * @return The parameters string.
  */
 protected String buildParams(IType type, String[] fields) throws Exception {
   StringBuffer params = new StringBuffer();
   for (int ii = 0; ii < fields.length; ii++) {
     if (ii != 0) {
       params.append(", ");
     }
     IField field = type.getField(fields[ii]);
     params
         .append(Signature.getSignatureSimpleName(field.getTypeSignature()))
         .append(' ')
         .append(field.getElementName());
   }
   return params.toString();
 }
Beispiel #4
0
 public static String[] getParameterTypesString(IMethod method) {
   try {
     String[] parameterQualifiedTypes = Signature.getParameterTypes(method.getSignature());
     int length = parameterQualifiedTypes == null ? 0 : parameterQualifiedTypes.length;
     String[] parameterPackages = new String[length];
     for (int i = 0; i < length; i++) {
       parameterQualifiedTypes[i] = parameterQualifiedTypes[i].replace('/', '.');
       parameterPackages[i] = Signature.getSignatureSimpleName(parameterQualifiedTypes[i]);
     }
     return parameterPackages;
   } catch (IllegalArgumentException e) {
   } catch (JavaModelException e) {
   }
   return null;
 }
  @Override
  public List<ICompletionProposal> computeCompletionProposals(
      final ContentAssistInvocationContext context, final IProgressMonitor monitor) {
    final List<ICompletionProposal> list = new ArrayList<ICompletionProposal>();
    boolean extendContext = false;
    try {
      if (context instanceof JavaContentAssistInvocationContext) {
        final ITextViewer viewer = context.getViewer();
        final List<ScriptVariable> scriptVariables = getScriptVariables(viewer);
        if (scriptVariables.isEmpty()) {
          return list;
        }
        final CompletionContext coreContext =
            ((JavaContentAssistInvocationContext) context).getCoreContext();
        if (coreContext != null && !coreContext.isExtended()) {
          // must use reflection to set the fields
          ReflectionUtils.setPrivateField(
              InternalCompletionContext.class, "isExtended", coreContext, true);
          extendContext = true;
        }
        final ICompilationUnit unit =
            ((JavaContentAssistInvocationContext) context).getCompilationUnit();
        if (unit instanceof GroovyCompilationUnit) {
          if (((GroovyCompilationUnit) unit).getModuleNode() == null) {
            return Collections.emptyList();
          }
          final ContentAssistContext assistContext =
              new GroovyCompletionProposalComputer()
                  .createContentAssistContext(
                      (GroovyCompilationUnit) unit,
                      context.getInvocationOffset(),
                      context.getDocument());
          CharSequence prefix = null;
          try {
            prefix = context.computeIdentifierPrefix();
          } catch (final BadLocationException e) {
            BonitaStudioLog.error(e);
          }

          if (assistContext != null && assistContext.completionNode instanceof VariableExpression) {
            try {
              final VariableExpression expr = (VariableExpression) assistContext.completionNode;
              if (scriptVariables != null) {
                for (final ScriptVariable f : scriptVariables) {
                  if (expr.getName().equals(f.getName())) {
                    final IType type = javaProject.findType(f.getType());
                    if (type == null) {
                      return list;
                    }
                    for (final IMethod m : type.getMethods()) {
                      if (m.getElementName().startsWith(prefix.toString())) {
                        final GroovyCompletionProposal proposal =
                            new GroovyCompletionProposal(
                                CompletionProposal.METHOD_REF, context.getInvocationOffset());
                        proposal.setName(m.getElementName().toCharArray());
                        proposal.setCompletion(
                            m.getElementName().substring(prefix.length()).toCharArray());
                        proposal.setFlags(m.getFlags());

                        if (prefix.length() == m.getElementName().length()) {
                          proposal.setReplaceRange(
                              context.getInvocationOffset(), context.getInvocationOffset());
                          proposal.setReceiverRange(0, 0);
                        } else {
                          proposal.setReplaceRange(
                              context.getInvocationOffset() - prefix.length(),
                              context.getInvocationOffset());
                          proposal.setReceiverRange(prefix.length(), prefix.length());
                        }

                        final char[][] parametersArray =
                            new char[m.getParameterNames().length][256];
                        final List<Parameter> parameters = new ArrayList<Parameter>();
                        for (int i = 0; i < m.getParameterNames().length; i++) {
                          parametersArray[i] = m.getParameterNames()[i].toCharArray();
                          parameters.add(
                              new Parameter(
                                  ClassHelper.make(
                                      Signature.getSignatureSimpleName(m.getParameterTypes()[i])),
                                  m.getParameterNames()[i]));
                        }

                        final ClassNode classNode =
                            ClassHelper.make(m.getDeclaringType().getFullyQualifiedName());
                        proposal.setDeclarationSignature(
                            ProposalUtils.createTypeSignature(classNode));
                        proposal.setParameterNames(parametersArray);
                        if (m.getDeclaringType().getFullyQualifiedName().equals(f.getType())) {
                          proposal.setRelevance(100);
                        }

                        final MethodNode methodNode =
                            new MethodNode(
                                m.getElementName(),
                                m.getFlags(),
                                ClassHelper.make(
                                    Signature.getSignatureSimpleName(m.getReturnType())),
                                parameters.toArray(new Parameter[parameters.size()]),
                                new ClassNode[0],
                                null);
                        final char[] methodSignature =
                            ProposalUtils.createMethodSignature(methodNode);
                        proposal.setSignature(methodSignature);

                        final GroovyJavaGuessingCompletionProposal groovyProposal =
                            GroovyJavaGuessingCompletionProposal.createProposal(
                                proposal,
                                (JavaContentAssistInvocationContext) context,
                                true,
                                "Groovy",
                                ProposalFormattingOptions.newFromOptions());
                        if (groovyProposal != null) {
                          list.add(groovyProposal);
                        }
                      }
                    }
                  }
                }
              }
            } catch (final JavaModelException e) {
              BonitaStudioLog.error(e);
            }
          }
        }

        return list;
      }
    } finally {
      final CompletionContext coreContext =
          ((JavaContentAssistInvocationContext) context).getCoreContext();
      if (extendContext && coreContext != null && coreContext.isExtended()) {
        // must use reflection to set the fields
        ReflectionUtils.setPrivateField(
            InternalCompletionContext.class, "isExtended", coreContext, false);
      }
    }

    return Collections.emptyList();
  }
 private static String typeSignatureToFqn(String signature) {
   try {
     switch (Signature.getTypeSignatureKind(signature)) {
       case Signature.ARRAY_TYPE_SIGNATURE:
         return typeSignatureToFqn(Signature.getElementType(signature))
             + brackets.substring(0, 2 * Signature.getArrayCount(signature));
       case Signature.CLASS_TYPE_SIGNATURE:
         String args[] = Signature.getTypeArguments(signature);
         if (args.length == 0) {
           int firstDollar = signature.indexOf('$');
           if (firstDollar == -1) {
             return Signature.getSignatureQualifier(signature)
                 + "."
                 + Signature.getSignatureSimpleName(signature);
           } else {
             String shortSig = signature.substring(0, firstDollar) + ";";
             return Signature.getSignatureQualifier(shortSig)
                 + "."
                 + Signature.getSignatureSimpleName(shortSig)
                 + signature.substring(firstDollar, signature.length() - 1);
           }
         } else {
           StringBuilder fqnBuilder =
               new StringBuilder(typeSignatureToFqn(Signature.getTypeErasure(signature)));
           fqnBuilder.append('<');
           boolean first = true;
           for (String arg : args) {
             if (first) {
               first = false;
             } else {
               fqnBuilder.append(',');
             }
             fqnBuilder.append(typeSignatureToFqn(arg));
           }
           fqnBuilder.append('>');
           return fqnBuilder.toString();
         }
       case Signature.BASE_TYPE_SIGNATURE:
         return Signature.getSignatureSimpleName(signature);
       case Signature.TYPE_VARIABLE_SIGNATURE:
         return "<" + Signature.getSignatureSimpleName(signature) + ">";
       case Signature.WILDCARD_TYPE_SIGNATURE:
         if (signature.startsWith("+")) {
           return "<?+" + typeSignatureToFqn(signature.substring(1)) + ">";
         } else if (signature.startsWith("-")) {
           return "<?-" + typeSignatureToFqn(signature.substring(1)) + ">";
         } else {
           return "<?>";
         }
       case Signature.CAPTURE_TYPE_SIGNATURE:
         System.out.println("eek");
         return "";
       default:
         throw new IllegalArgumentException("Not a valid type signature");
     }
   } catch (Exception e) {
     e.printStackTrace();
     System.out.println("bad");
     return null;
   }
 }
  /**
   * Finds the key defined by the given match. The assumption is that the key is the only argument
   * and it is a string literal i.e. quoted ("...") or a string constant i.e. 'static final String'
   * defined in the same class.
   *
   * @param keyPositionResult reference parameter: will be filled with the position of the found key
   * @param enclosingElement enclosing java element
   * @return a string denoting the key, {@link #NO_KEY} if no key can be found and <code>null</code>
   *     otherwise
   * @throws CoreException if a problem occurs while accessing the <code>enclosingElement</code>
   */
  private String findKey(Position keyPositionResult, IJavaElement enclosingElement)
      throws CoreException {
    ICompilationUnit unit =
        (ICompilationUnit) enclosingElement.getAncestor(IJavaElement.COMPILATION_UNIT);
    if (unit == null) return null;

    String source = unit.getSource();
    if (source == null) return null;

    IJavaProject javaProject = unit.getJavaProject();
    IScanner scanner = null;
    if (javaProject != null) {
      String complianceLevel = javaProject.getOption(JavaCore.COMPILER_COMPLIANCE, true);
      String sourceLevel = javaProject.getOption(JavaCore.COMPILER_SOURCE, true);
      scanner = ToolFactory.createScanner(false, false, false, sourceLevel, complianceLevel);
    } else {
      scanner = ToolFactory.createScanner(false, false, false, false);
    }
    scanner.setSource(source.toCharArray());
    scanner.resetTo(keyPositionResult.getOffset() + keyPositionResult.getLength(), source.length());

    try {
      if (scanner.getNextToken() != ITerminalSymbols.TokenNameDOT) return null;

      if (scanner.getNextToken() != ITerminalSymbols.TokenNameIdentifier) return null;

      String src = new String(scanner.getCurrentTokenSource());
      int tokenStart = scanner.getCurrentTokenStartPosition();
      int tokenEnd = scanner.getCurrentTokenEndPosition();

      if (scanner.getNextToken() == ITerminalSymbols.TokenNameLPAREN) {
        // Old school
        // next must be key string. Ignore methods which do not take a single String parameter (Bug
        // 295040).
        int nextToken = scanner.getNextToken();
        if (nextToken != ITerminalSymbols.TokenNameStringLiteral
            && nextToken != ITerminalSymbols.TokenNameIdentifier) return null;

        tokenStart = scanner.getCurrentTokenStartPosition();
        tokenEnd = scanner.getCurrentTokenEndPosition();
        int token;
        while ((token = scanner.getNextToken()) == ITerminalSymbols.TokenNameDOT) {
          if ((nextToken = scanner.getNextToken()) != ITerminalSymbols.TokenNameIdentifier) {
            return null;
          }
          tokenStart = scanner.getCurrentTokenStartPosition();
          tokenEnd = scanner.getCurrentTokenEndPosition();
        }
        if (token != ITerminalSymbols.TokenNameRPAREN) return null;

        if (nextToken == ITerminalSymbols.TokenNameStringLiteral) {
          keyPositionResult.setOffset(tokenStart + 1);
          keyPositionResult.setLength(tokenEnd - tokenStart - 1);
          return source.substring(tokenStart + 1, tokenEnd);
        } else if (nextToken == ITerminalSymbols.TokenNameIdentifier) {
          keyPositionResult.setOffset(tokenStart);
          keyPositionResult.setLength(tokenEnd - tokenStart + 1);
          IType parentClass = (IType) enclosingElement.getAncestor(IJavaElement.TYPE);
          IField[] fields = parentClass.getFields();
          String identifier = source.substring(tokenStart, tokenEnd + 1);
          for (int i = 0; i < fields.length; i++) {
            if (fields[i].getElementName().equals(identifier)) {
              if (!Signature.getSignatureSimpleName(fields[i].getTypeSignature())
                  .equals("String")) // $NON-NLS-1$
              return null;
              Object obj = fields[i].getConstant();
              return obj instanceof String
                  ? ((String) obj).substring(1, ((String) obj).length() - 1)
                  : NO_KEY;
            }
          }
        }
        return NO_KEY;
      } else {
        keyPositionResult.setOffset(tokenStart);
        keyPositionResult.setLength(tokenEnd - tokenStart + 1);
        return src;
      }
    } catch (InvalidInputException e) {
      throw new CoreException(JavaUIStatus.createError(IStatus.ERROR, e));
    }
  }