Java 类org.eclipse.jdt.core.ISourceRange 实例源码

项目:che    文件:JavaNavigation.java   
private OpenDeclarationDescriptor classFileNavigation(IClassFile classFile, IJavaElement element)
    throws JavaModelException {
  OpenDeclarationDescriptor dto =
      DtoFactory.getInstance().createDto(OpenDeclarationDescriptor.class);
  dto.setPath(classFile.getType().getFullyQualifiedName());
  dto.setLibId(classFile.getAncestor(IPackageFragmentRoot.PACKAGE_FRAGMENT_ROOT).hashCode());
  dto.setBinary(true);
  if (classFile.getSourceRange() != null) {
    if (element instanceof ISourceReference) {
      ISourceRange nameRange = ((ISourceReference) element).getNameRange();
      dto.setOffset(nameRange.getOffset());
      dto.setLength(nameRange.getLength());
    }
  }
  return dto;
}
项目:vertigo-chroma-kspplugin    文件:ServiceManager.java   
private void handleType(IType type, IFile file, List<ServiceImplementation> serviceImplementations) throws JavaModelException {
    /* Parcourt les méthodes. */
    for (IMethod method : type.getMethods()) {
        /* Filtre pour ne garder que les méthodes publiques d'instance */
        if (method.isConstructor() || Flags.isStatic(method.getFlags()) || Flags.isPrivate(method.getFlags())) {
            continue;
        }

        /* Créé le ServiceImplementation. */
        String javaName = method.getElementName();
        ISourceRange nameRange = method.getNameRange();
        FileRegion fileRegion = new FileRegion(file, nameRange.getOffset(), nameRange.getLength());
        ServiceImplementation serviceImplementation = new ServiceImplementation(fileRegion, javaName);
        serviceImplementations.add(serviceImplementation);
    }
}
项目:vertigo-chroma-kspplugin    文件:DaoManager.java   
private void handleType(IType type, IFile file, List<DaoImplementation> daoImplementations) throws JavaModelException {
    /* Parcourt les méthodes. */
    for (IMethod method : type.getMethods()) {
        /* Filtre pour ne garder que les méthodes publiques d'instance */
        if (method.isConstructor() || Flags.isStatic(method.getFlags()) || Flags.isPrivate(method.getFlags())) {
            continue;
        }

        /* Créé le DaoImplementation. */
        String javaName = method.getElementName();
        ISourceRange nameRange = method.getNameRange();
        FileRegion fileRegion = new FileRegion(file, nameRange.getOffset(), nameRange.getLength());
        DaoImplementation daoImplementation = new DaoImplementation(fileRegion, javaName);
        daoImplementations.add(daoImplementation);
    }
}
项目:eclipse.jdt.ls    文件:JDTUtils.java   
/**
 * Creates a location for a given java element.
 * Element can be a {@link ICompilationUnit} or {@link IClassFile}
 *
 * @param element
 * @return location or null
 * @throws JavaModelException
 */
public static Location toLocation(IJavaElement element) throws JavaModelException{
    ICompilationUnit unit = (ICompilationUnit) element.getAncestor(IJavaElement.COMPILATION_UNIT);
    IClassFile cf = (IClassFile) element.getAncestor(IJavaElement.CLASS_FILE);
    if (unit == null && cf == null) {
        return null;
    }
    if (element instanceof ISourceReference) {
        ISourceRange nameRange = getNameRange(element);
        if (SourceRange.isAvailable(nameRange)) {
            if (cf == null) {
                return toLocation(unit, nameRange.getOffset(), nameRange.getLength());
            } else {
                return toLocation(cf, nameRange.getOffset(), nameRange.getLength());
            }
        }
    }
    return null;
}
项目:eclipse.jdt.ls    文件:JDTUtils.java   
private static ISourceRange getNameRange(IJavaElement element) throws JavaModelException {
    ISourceRange nameRange = null;
    if (element instanceof IMember) {
        IMember member = (IMember) element;
        nameRange = member.getNameRange();
        if ( (!SourceRange.isAvailable(nameRange))) {
            nameRange = member.getSourceRange();
        }
    } else if (element instanceof ITypeParameter || element instanceof ILocalVariable) {
        nameRange = ((ISourceReference) element).getNameRange();
    } else if (element instanceof ISourceReference) {
        nameRange = ((ISourceReference) element).getSourceRange();
    }
    if (!SourceRange.isAvailable(nameRange) && element.getParent() != null) {
        nameRange = getNameRange(element.getParent());
    }
    return nameRange;
}
项目:eclipse.jdt.ls    文件:MethodsSourcePositionComparator.java   
private int compareInTheSameType(IMethodBinding firstMethodBinding, IMethodBinding secondMethodBinding) {
    try {
        IMethod firstMethod= (IMethod)firstMethodBinding.getJavaElement();
        IMethod secondMethod= (IMethod)secondMethodBinding.getJavaElement();
        if (firstMethod == null || secondMethod == null) {
            return 0;
        }
        ISourceRange firstSourceRange= firstMethod.getSourceRange();
        ISourceRange secondSourceRange= secondMethod.getSourceRange();

        if (!SourceRange.isAvailable(firstSourceRange) || !SourceRange.isAvailable(secondSourceRange)) {
            return firstMethod.getElementName().compareTo(secondMethod.getElementName());
        } else {
            return firstSourceRange.getOffset() - secondSourceRange.getOffset();
        }
    } catch (JavaModelException e) {
        return 0;
    }
}
项目:eclipse.jdt.ls    文件:StubUtility2.java   
/**
 * Evaluates the insertion position of a new node.
 *
 * @param listRewrite The list rewriter to which the new node will be added
 * @param sibling The Java element before which the new element should be added.
 * @return the AST node of the list to insert before or null to insert as last.
 * @throws JavaModelException thrown if accessing the Java element failed
 */

public static ASTNode getNodeToInsertBefore(ListRewrite listRewrite, IJavaElement sibling) throws JavaModelException {
    if (sibling instanceof IMember) {
        ISourceRange sourceRange= ((IMember) sibling).getSourceRange();
        if (sourceRange == null) {
            return null;
        }
        int insertPos= sourceRange.getOffset();

        List<? extends ASTNode> members= listRewrite.getOriginalList();
        for (int i= 0; i < members.size(); i++) {
            ASTNode curr= members.get(i);
            if (curr.getStartPosition() >= insertPos) {
                return curr;
            }
        }
    }
    return null;
}
项目:eclipse.jdt.ls    文件:JavadocContentAccess.java   
/**
 * Gets a reader for an IMember's Javadoc comment content from the source attachment.
 * The content does contain only the text from the comment without the Javadoc leading star characters.
 * Returns <code>null</code> if the member does not contain a Javadoc comment or if no source is available.
 * @param member The member to get the Javadoc of.
 * @return Returns a reader for the Javadoc comment content or <code>null</code> if the member
 * does not contain a Javadoc comment or if no source is available
 * @throws JavaModelException is thrown when the elements javadoc can not be accessed
 * @since 3.4
 */
private static Reader internalGetContentReader(IMember member) throws JavaModelException {
    IBuffer buf= member.getOpenable().getBuffer();
    if (buf == null) {
        return null; // no source attachment found
    }

    ISourceRange javadocRange= member.getJavadocRange();
    if (javadocRange != null) {
        JavaDocCommentReader reader= new JavaDocCommentReader(buf, javadocRange.getOffset(), javadocRange.getOffset() + javadocRange.getLength() - 1);
        if (!containsOnlyInheritDoc(reader, javadocRange.getLength())) {
            reader.reset();
            return reader;
        }
    }

    return null;
}
项目:eclipse.jdt.ls    文件:CorrectPackageDeclarationProposal.java   
@Override
protected void addEdits(IDocument doc, TextEdit root) throws CoreException {
    super.addEdits(doc, root);

    ICompilationUnit cu= getCompilationUnit();

    IPackageFragment parentPack= (IPackageFragment) cu.getParent();
    IPackageDeclaration[] decls= cu.getPackageDeclarations();

    if (parentPack.isDefaultPackage() && decls.length > 0) {
        for (int i= 0; i < decls.length; i++) {
            ISourceRange range= decls[i].getSourceRange();
            root.addChild(new DeleteEdit(range.getOffset(), range.getLength()));
        }
        return;
    }
    if (!parentPack.isDefaultPackage() && decls.length == 0) {
        String lineDelim = "\n";
        String str= "package " + parentPack.getElementName() + ';' + lineDelim + lineDelim; //$NON-NLS-1$
        root.addChild(new InsertEdit(0, str));
        return;
    }

    root.addChild(new ReplaceEdit(fLocation.getOffset(), fLocation.getLength(), parentPack.getElementName()));
}
项目:che    文件:AssociativeInfixExpressionFragment.java   
public static IExpressionFragment createSubPartFragmentBySourceRange(
    InfixExpression node, ISourceRange range, ICompilationUnit cu) throws JavaModelException {
  Assert.isNotNull(node);
  Assert.isNotNull(range);
  Assert.isTrue(!Util.covers(range, node));
  Assert.isTrue(Util.covers(SourceRangeFactory.create(node), range));

  if (!isAssociativeInfix(node)) return null;

  InfixExpression groupRoot = findGroupRoot(node);
  Assert.isTrue(isAGroupRoot(groupRoot));

  List<Expression> groupMembers =
      AssociativeInfixExpressionFragment.findGroupMembersInOrderFor(groupRoot);
  List<Expression> subGroup = findSubGroupForSourceRange(groupMembers, range);
  if (subGroup.isEmpty() || rangeIncludesExtraNonWhitespace(range, subGroup, cu)) return null;

  return new AssociativeInfixExpressionFragment(groupRoot, subGroup);
}
项目:che    文件:MethodsSourcePositionComparator.java   
private int compareInTheSameType(
    IMethodBinding firstMethodBinding, IMethodBinding secondMethodBinding) {
  try {
    IMethod firstMethod = (IMethod) firstMethodBinding.getJavaElement();
    IMethod secondMethod = (IMethod) secondMethodBinding.getJavaElement();
    if (firstMethod == null || secondMethod == null) {
      return 0;
    }
    ISourceRange firstSourceRange = firstMethod.getSourceRange();
    ISourceRange secondSourceRange = secondMethod.getSourceRange();

    if (!SourceRange.isAvailable(firstSourceRange)
        || !SourceRange.isAvailable(secondSourceRange)) {
      return firstMethod.getElementName().compareTo(secondMethod.getElementName());
    } else {
      return firstSourceRange.getOffset() - secondSourceRange.getOffset();
    }
  } catch (JavaModelException e) {
    return 0;
  }
}
项目:che    文件:StubUtility2.java   
/**
 * Evaluates the insertion position of a new node.
 *
 * @param listRewrite The list rewriter to which the new node will be added
 * @param sibling The Java element before which the new element should be added.
 * @return the AST node of the list to insert before or null to insert as last.
 * @throws JavaModelException thrown if accessing the Java element failed
 */
public static ASTNode getNodeToInsertBefore(ListRewrite listRewrite, IJavaElement sibling)
    throws JavaModelException {
  if (sibling instanceof IMember) {
    ISourceRange sourceRange = ((IMember) sibling).getSourceRange();
    if (sourceRange == null) {
      return null;
    }
    int insertPos = sourceRange.getOffset();

    List<? extends ASTNode> members = listRewrite.getOriginalList();
    for (int i = 0; i < members.size(); i++) {
      ASTNode curr = members.get(i);
      if (curr.getStartPosition() >= insertPos) {
        return curr;
      }
    }
  }
  return null;
}
项目:che    文件:RenameAnalyzeUtil.java   
private static void addReferenceShadowedError(
    ICompilationUnit cu, SearchMatch newMatch, String newElementName, RefactoringStatus result) {
  // Found a new match with no corresponding old match.
  // -> The new match is a reference which was pointing to another element,
  // but that other element has been shadowed

  // TODO: should not have to filter declarations:
  if (newMatch instanceof MethodDeclarationMatch || newMatch instanceof FieldDeclarationMatch)
    return;
  ISourceRange range = getOldSourceRange(newMatch);
  RefactoringStatusContext context = JavaStatusContext.create(cu, range);
  String message =
      Messages.format(
          RefactoringCoreMessages.RenameAnalyzeUtil_reference_shadowed,
          new String[] {
            BasicElementLabels.getFileName(cu),
            BasicElementLabels.getJavaElementName(newElementName)
          });
  result.addError(message, context);
}
项目:che    文件:ReorgPolicyFactory.java   
private ArrayList<IJavaElement> getSortedChildren(IType parent) throws JavaModelException {
  IJavaElement[] children = parent.getChildren();
  ArrayList<IJavaElement> sortedChildren = new ArrayList<IJavaElement>(Arrays.asList(children));
  Collections.sort(
      sortedChildren,
      new Comparator<IJavaElement>() {
        public int compare(IJavaElement e1, IJavaElement e2) {
          if (!(e1 instanceof ISourceReference)) return 0;
          if (!(e2 instanceof ISourceReference)) return 0;

          try {
            ISourceRange sr1 = ((ISourceReference) e1).getSourceRange();
            ISourceRange sr2 = ((ISourceReference) e2).getSourceRange();
            if (sr1 == null || sr2 == null) return 0;

            return sr1.getOffset() - sr2.getOffset();

          } catch (JavaModelException e) {
            return 0;
          }
        }
      });
  return sortedChildren;
}
项目:che    文件:SelfEncapsulateFieldRefactoring.java   
@Override
public RefactoringStatus checkInitialConditions(IProgressMonitor pm) throws CoreException {
  if (fVisibility < 0)
    fVisibility = (fField.getFlags() & (Flags.AccPublic | Flags.AccProtected | Flags.AccPrivate));
  RefactoringStatus result = new RefactoringStatus();
  result.merge(Checks.checkAvailability(fField));
  if (result.hasFatalError()) return result;
  fRoot =
      new RefactoringASTParser(ASTProvider.SHARED_AST_LEVEL)
          .parse(fField.getCompilationUnit(), true, pm);
  ISourceRange sourceRange = fField.getNameRange();
  ASTNode node = NodeFinder.perform(fRoot, sourceRange.getOffset(), sourceRange.getLength());
  if (node == null) {
    return mappingErrorFound(result, node);
  }
  fFieldDeclaration =
      (VariableDeclarationFragment) ASTNodes.getParent(node, VariableDeclarationFragment.class);
  if (fFieldDeclaration == null) {
    return mappingErrorFound(result, node);
  }
  if (fFieldDeclaration.resolveBinding() == null) {
    if (!processCompilerError(result, node))
      result.addFatalError(RefactoringCoreMessages.SelfEncapsulateField_type_not_resolveable);
    return result;
  }
  computeUsedNames();
  return result;
}
项目:che    文件:Util.java   
/** Returns the IInitializer that contains the given local variable in the given type */
public static JavaElement getUnresolvedJavaElement(
    int localSourceStart, int localSourceEnd, JavaElement type) {
  try {
    if (!(type instanceof IType)) return null;
    IInitializer[] initializers = ((IType) type).getInitializers();
    for (int i = 0; i < initializers.length; i++) {
      IInitializer initializer = initializers[i];
      ISourceRange sourceRange = initializer.getSourceRange();
      if (sourceRange != null) {
        int initializerStart = sourceRange.getOffset();
        int initializerEnd = initializerStart + sourceRange.getLength();
        if (initializerStart <= localSourceStart && localSourceEnd <= initializerEnd) {
          return (JavaElement) initializer;
        }
      }
    }
    return null;
  } catch (JavaModelException e) {
    return null;
  }
}
项目:che    文件:JavadocContentAccess.java   
/**
 * Gets a reader for an IMember's Javadoc comment content from the source attachment. The content
 * does contain only the text from the comment without the Javadoc leading star characters.
 * Returns <code>null</code> if the member does not contain a Javadoc comment or if no source is
 * available.
 *
 * @param member The member to get the Javadoc of.
 * @return Returns a reader for the Javadoc comment content or <code>null</code> if the member
 *     does not contain a Javadoc comment or if no source is available
 * @throws org.eclipse.jdt.core.JavaModelException is thrown when the elements javadoc can not be
 *     accessed
 * @since 3.4
 */
private static Reader internalGetContentReader(IMember member) throws JavaModelException {
  IBuffer buf = member.getOpenable().getBuffer();
  if (buf == null) {
    return null; // no source attachment found
  }

  ISourceRange javadocRange = member.getJavadocRange();
  if (javadocRange != null) {
    JavaDocCommentReader reader =
        new JavaDocCommentReader(
            buf,
            javadocRange.getOffset(),
            javadocRange.getOffset() + javadocRange.getLength() - 1);
    if (!containsOnlyInheritDoc(reader, javadocRange.getLength())) {
      reader.reset();
      return reader;
    }
  }

  return null;
}
项目:che    文件:JavadocContentAccess2.java   
private static String getHTMLContentFromSource(IMember member, String urlPrefix)
    throws JavaModelException {
  IBuffer buf = member.getOpenable().getBuffer();
  if (buf == null) {
    return null; // no source attachment found
  }

  ISourceRange javadocRange = member.getJavadocRange();
  if (javadocRange == null) {
    if (canInheritJavadoc(member)) {
      // Try to use the inheritDoc algorithm.
      String inheritedJavadoc = javadoc2HTML(member, "/***/", urlPrefix); // $NON-NLS-1$
      if (inheritedJavadoc != null && inheritedJavadoc.length() > 0) {
        return inheritedJavadoc;
      }
    }
    return null; // getJavaFxPropertyDoc(member);
  }

  String rawJavadoc = buf.getText(javadocRange.getOffset(), javadocRange.getLength());
  return javadoc2HTML(member, rawJavadoc, urlPrefix);
}
项目:umlet    文件:ImageRefHyperlinkDetector.java   
private void collectIntersectingJavadocRanges(IJavaElement element, IRegion region, List<ISourceRange> elements) throws JavaModelException {
    if (element instanceof IParent) {
        for (IJavaElement child : ((IParent) element).getChildren()) {
            collectIntersectingJavadocRanges(child, region, elements);
        }
    }

    if (element instanceof IMember) {
        ISourceRange range = ((IMember) element).getJavadocRange();
        if (range != null) {
            if (range.getOffset() <= region.getOffset() + region.getLength() && range.getOffset() + range.getLength() >= region.getOffset()) {
                elements.add(range);
            }
        }
    }

}
项目:Eclipse-Postfix-Code-Completion    文件:MatchLocator.java   
protected void reportBinaryMemberDeclaration(IResource resource, IMember binaryMember, Binding binaryMemberBinding, IBinaryType info, int accuracy) throws CoreException {
    ClassFile classFile = (ClassFile) binaryMember.getClassFile();
    ISourceRange range = classFile.isOpen() ? binaryMember.getNameRange() : SourceMapper.UNKNOWN_RANGE;
    if (range.getOffset() == -1) {
        BinaryType type = (BinaryType) classFile.getType();
        String sourceFileName = type.sourceFileName(info);
        if (sourceFileName != null) {
            SourceMapper mapper = classFile.getSourceMapper();
            if (mapper != null) {
                char[] contents = mapper.findSource(type, sourceFileName);
                if (contents != null)
                    range = mapper.mapSource(type, contents, info, binaryMember);
            }
        }
    }
    if (resource == null) resource =  this.currentPossibleMatch.resource;
    SearchMatch match = newDeclarationMatch(binaryMember, binaryMemberBinding, accuracy, range.getOffset(), range.getLength(), getParticipant(), resource);
    report(match);
}
项目:Eclipse-Postfix-Code-Completion    文件:ReorgPolicyFactory.java   
private ArrayList<IJavaElement> getSortedChildren(IType parent) throws JavaModelException {
    IJavaElement[] children= parent.getChildren();
    ArrayList<IJavaElement> sortedChildren= new ArrayList<IJavaElement>(Arrays.asList(children));
    Collections.sort(sortedChildren, new Comparator<IJavaElement>() {
        public int compare(IJavaElement e1, IJavaElement e2) {
            if (!(e1 instanceof ISourceReference))
                return 0;
            if (!(e2 instanceof ISourceReference))
                return 0;

            try {
                ISourceRange sr1= ((ISourceReference)e1).getSourceRange();
                ISourceRange sr2= ((ISourceReference)e2).getSourceRange();
                if (sr1 == null || sr2 == null)
                    return 0;

                return sr1.getOffset() - sr2.getOffset();

            } catch (JavaModelException e) {
                return 0;
            }
        }
    });
    return sortedChildren;
}
项目:Eclipse-Postfix-Code-Completion    文件:SelfEncapsulateFieldRefactoring.java   
@Override
public RefactoringStatus checkInitialConditions(IProgressMonitor pm) throws CoreException {
    if (fVisibility < 0)
        fVisibility= (fField.getFlags() & (Flags.AccPublic | Flags.AccProtected | Flags.AccPrivate));
    RefactoringStatus result=  new RefactoringStatus();
    result.merge(Checks.checkAvailability(fField));
    if (result.hasFatalError())
        return result;
    fRoot= new RefactoringASTParser(ASTProvider.SHARED_AST_LEVEL).parse(fField.getCompilationUnit(), true, pm);
    ISourceRange sourceRange= fField.getNameRange();
    ASTNode node= NodeFinder.perform(fRoot, sourceRange.getOffset(), sourceRange.getLength());
    if (node == null) {
        return mappingErrorFound(result, node);
    }
    fFieldDeclaration= (VariableDeclarationFragment)ASTNodes.getParent(node, VariableDeclarationFragment.class);
    if (fFieldDeclaration == null) {
        return mappingErrorFound(result, node);
    }
    if (fFieldDeclaration.resolveBinding() == null) {
        if (!processCompilerError(result, node))
            result.addFatalError(RefactoringCoreMessages.SelfEncapsulateField_type_not_resolveable);
        return result;
    }
    computeUsedNames();
    return result;
}
项目:Eclipse-Postfix-Code-Completion    文件:CorrectPackageDeclarationProposal.java   
@Override
protected void addEdits(IDocument doc, TextEdit root) throws CoreException {
    super.addEdits(doc, root);

    ICompilationUnit cu= getCompilationUnit();

    IPackageFragment parentPack= (IPackageFragment) cu.getParent();
    IPackageDeclaration[] decls= cu.getPackageDeclarations();

    if (parentPack.isDefaultPackage() && decls.length > 0) {
        for (int i= 0; i < decls.length; i++) {
            ISourceRange range= decls[i].getSourceRange();
            root.addChild(new DeleteEdit(range.getOffset(), range.getLength()));
        }
        return;
    }
    if (!parentPack.isDefaultPackage() && decls.length == 0) {
        String lineDelim= StubUtility.getLineDelimiterUsed(cu);
        String str= "package " + parentPack.getElementName() + ';' + lineDelim + lineDelim; //$NON-NLS-1$
        root.addChild(new InsertEdit(0, str));
        return;
    }

    root.addChild(new ReplaceEdit(fLocation.getOffset(), fLocation.getLength(), parentPack.getElementName()));
}
项目:Eclipse-Postfix-Code-Completion-Juno38    文件:ReorgPolicyFactory.java   
private ArrayList<IJavaElement> getSortedChildren(IType parent) throws JavaModelException {
    IJavaElement[] children= parent.getChildren();
    ArrayList<IJavaElement> sortedChildren= new ArrayList<IJavaElement>(Arrays.asList(children));
    Collections.sort(sortedChildren, new Comparator<IJavaElement>() {
        public int compare(IJavaElement e1, IJavaElement e2) {
            if (!(e1 instanceof ISourceReference))
                return 0;
            if (!(e2 instanceof ISourceReference))
                return 0;

            try {
                ISourceRange sr1= ((ISourceReference)e1).getSourceRange();
                ISourceRange sr2= ((ISourceReference)e2).getSourceRange();
                if (sr1 == null || sr2 == null)
                    return 0;

                return sr1.getOffset() - sr2.getOffset();

            } catch (JavaModelException e) {
                return 0;
            }
        }
    });
    return sortedChildren;
}
项目:Eclipse-Postfix-Code-Completion-Juno38    文件:MethodsSourcePositionComparator.java   
private int compareInTheSameType(IMethodBinding firstMethodBinding, IMethodBinding secondMethodBinding) {
    try {
        IMethod firstMethod= (IMethod)firstMethodBinding.getJavaElement();
        IMethod secondMethod= (IMethod)secondMethodBinding.getJavaElement();
        if (firstMethod == null || secondMethod == null) {
            return 0;
        }
        ISourceRange firstSourceRange= firstMethod.getSourceRange();
        ISourceRange secondSourceRange= secondMethod.getSourceRange();

        if (!SourceRange.isAvailable(firstSourceRange) || !SourceRange.isAvailable(secondSourceRange)) {
            return firstMethod.getElementName().compareTo(secondMethod.getElementName());
        } else {
            return firstSourceRange.getOffset() - secondSourceRange.getOffset();
        }
    } catch (JavaModelException e) {
        return 0;
    }
}
项目:Eclipse-Postfix-Code-Completion-Juno38    文件:MatchLocator.java   
protected void reportBinaryMemberDeclaration(IResource resource, IMember binaryMember, Binding binaryMemberBinding, IBinaryType info, int accuracy) throws CoreException {
    ClassFile classFile = (ClassFile) binaryMember.getClassFile();
    ISourceRange range = classFile.isOpen() ? binaryMember.getNameRange() : SourceMapper.UNKNOWN_RANGE;
    if (range.getOffset() == -1) {
        BinaryType type = (BinaryType) classFile.getType();
        String sourceFileName = type.sourceFileName(info);
        if (sourceFileName != null) {
            SourceMapper mapper = classFile.getSourceMapper();
            if (mapper != null) {
                char[] contents = mapper.findSource(type, sourceFileName);
                if (contents != null)
                    range = mapper.mapSource(type, contents, info, binaryMember);
            }
        }
    }
    if (resource == null) resource =  this.currentPossibleMatch.resource;
    SearchMatch match = newDeclarationMatch(binaryMember, binaryMemberBinding, accuracy, range.getOffset(), range.getLength(), getParticipant(), resource);
    report(match);
}
项目:Eclipse-Postfix-Code-Completion    文件:StructureSelectNextAction.java   
@Override
ISourceRange internalGetNewSelectionRange(ISourceRange oldSourceRange, ISourceReference sr, SelectionAnalyzer selAnalyzer) throws JavaModelException{
    if (oldSourceRange.getLength() == 0 && selAnalyzer.getLastCoveringNode() != null) {
        ASTNode previousNode= NextNodeAnalyzer.perform(oldSourceRange.getOffset(), selAnalyzer.getLastCoveringNode());
        if (previousNode != null)
            return getSelectedNodeSourceRange(sr, previousNode);
    }
    ASTNode first= selAnalyzer.getFirstSelectedNode();
    if (first == null)
        return getLastCoveringNodeRange(oldSourceRange, sr, selAnalyzer);

    ASTNode parent= first.getParent();
    if (parent == null)
        return getLastCoveringNodeRange(oldSourceRange, sr, selAnalyzer);

    ASTNode lastSelectedNode= selAnalyzer.getSelectedNodes()[selAnalyzer.getSelectedNodes().length - 1];
    ASTNode nextNode= getNextNode(parent, lastSelectedNode);
    if (nextNode == parent)
        return getSelectedNodeSourceRange(sr, first.getParent());
    int offset= oldSourceRange.getOffset();
    int end= Math.min(sr.getSourceRange().getLength(), nextNode.getStartPosition() + nextNode.getLength() - 1);
    return StructureSelectionAction.createSourceRange(offset, end);
}
项目:codelens-eclipse    文件:JavaCodeLensProvider.java   
private ICodeLens getCodeLens(String type, IJavaElement element, ITypeRoot unit) throws JavaModelException {
    ISourceRange r = ((ISourceReference) element).getNameRange();
    final Range range = JDTUtils.toRange(unit, r.getOffset(), r.getLength());

    ICodeLens lens = new JavaCodeLens(range, type);

    // String uri = ResourceUtils.toClientUri(JDTUtils.getFileURI(unit));
    // lens.setData(Arrays.asList(uri, range.getStart(), type));
    return lens;
}
项目:gw4e.project    文件:JDTManager.java   
/**
 * Format a Unit Source Code
 * 
 * @param testInterface
 * @param monitor
 * @throws CoreException 
 */
@SuppressWarnings("unchecked")
public static void formatUnitSourceCode(IFile file, IProgressMonitor monitor) throws CoreException {
    @SuppressWarnings("rawtypes")
    SubMonitor subMonitor = SubMonitor.convert(monitor, 100);
    ICompilationUnit unit = JavaCore.createCompilationUnitFrom(file);
    subMonitor.split(50);
    ICompilationUnit workingCopy = unit.getWorkingCopy(monitor);

    Map options = DefaultCodeFormatterConstants.getEclipseDefaultSettings();

    options.put(JavaCore.COMPILER_COMPLIANCE, JavaCore.VERSION_1_7);
    options.put(JavaCore.COMPILER_CODEGEN_TARGET_PLATFORM, JavaCore.VERSION_1_7);
    options.put(JavaCore.COMPILER_SOURCE, JavaCore.VERSION_1_7);

    options.put(DefaultCodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_ENUM_CONSTANTS,
            DefaultCodeFormatterConstants.createAlignmentValue(true,
                    DefaultCodeFormatterConstants.WRAP_ONE_PER_LINE,
                    DefaultCodeFormatterConstants.INDENT_ON_COLUMN));

    final CodeFormatter codeFormatter = ToolFactory.createCodeFormatter(options);
    ISourceRange range = unit.getSourceRange();
    TextEdit formatEdit = codeFormatter.format(CodeFormatter.K_COMPILATION_UNIT, unit.getSource(),
            range.getOffset(), range.getLength(), 0, null);
    subMonitor.split(30);
    if (formatEdit != null /* && formatEdit.hasChildren()*/) {
        workingCopy.applyTextEdit(formatEdit, monitor);
        workingCopy.reconcile(ICompilationUnit.NO_AST, false, null, null);
        workingCopy.commitWorkingCopy(true, null);
        workingCopy.discardWorkingCopy();
    }
    file.refreshLocal(IResource.DEPTH_INFINITE, subMonitor);
    subMonitor.split(20);
}
项目:vertigo-chroma-kspplugin    文件:DtoManager.java   
/**
 * Parse un fichier candidat de DTO.
 * 
 * @param file Fichier.
 * @param javaProject Projet Java du fichier.
 * @return Le DTO, <code>null</code> sinon.
 */
private DtoFile createDtoFile(IFile file, IJavaProject javaProject) {

    /* Charge l'AST du fichier Java. */
    ICompilationUnit compilationUnit = JdtUtils.getCompilationUnit(file, javaProject);
    if (compilationUnit == null) {
        return null;
    }
    List<String> dtoParentClassesList = LegacyManager.getInstance().getDtoParentsClasseList(javaProject.getProject());
    try {
        LegacyStrategy strategy = LegacyManager.getInstance().getStrategy(file);
        /* Parcourt les types du fichier Java. */
        for (IType type : compilationUnit.getAllTypes()) {

            /* Vérifie que c'est un Dto */
            boolean isDtoType = strategy.isDtoType(type) || JdtUtils.isSubclass(type, dtoParentClassesList);

            if (!isDtoType) {
                continue;
            }

            /* Parse les champs. */
            List<DtoField> fields = strategy.parseDtoFields(type);

            /* Créé le DtoFile. */
            String javaName = type.getElementName();
            String packageName = type.getPackageFragment().getElementName();
            ISourceRange nameRange = type.getNameRange();
            FileRegion fileRegion = new FileRegion(file, nameRange.getOffset(), nameRange.getLength());
            return new DtoFile(fileRegion, javaName, packageName, fields);
        }
    } catch (JavaModelException e) {
        ErrorUtils.handle(e);
    }

    return null;
}
项目:vertigo-chroma-kspplugin    文件:WsRouteManager.java   
private void handleMethod(IMethod method, String pathPrefix, IFile file, List<WsRoute> wsRoutes) throws JavaModelException {
    /* Filtre pour ne garder que les méthodes publiques d'instance */
    if (method.isConstructor() || Flags.isStatic(method.getFlags()) || Flags.isPrivate(method.getFlags())) {
        return;
    }

    /* Parcourt les verbes HTTP */
    for (String verb : HTTP_VERBS) {

        /* Extrait l'annotation du verbe. */
        IAnnotation verbAnnotation = JdtUtils.getAnnotation(method, verb);
        if (verbAnnotation == null) {
            continue;
        }

        /* Extrait la route partielle. */
        String routePatternSuffix = JdtUtils.getMemberValue(verbAnnotation);

        /* Calcule la route complète. */
        String routePattern = pathPrefix + routePatternSuffix;

        /* Créé la WsRoute. */
        String javaName = method.getElementName();
        ISourceRange nameRange = method.getNameRange();
        FileRegion fileRegion = new FileRegion(file, nameRange.getOffset(), nameRange.getLength());
        WsRoute wsRoute = new WsRoute(fileRegion, javaName, routePattern, verb);
        wsRoutes.add(wsRoute);
    }
}
项目:vertigo-chroma-kspplugin    文件:JavaClassManager.java   
/**
 * Parse un fichier de classe Java.
 * 
 * @param file Fichier.
 * @param javaProject Projet Java du fichier.
 * @return Le fichier de classe Java, <code>null</code> sinon.
 */
private JavaClassFile createJavaClassFile(IFile file, IJavaProject javaProject) {

    /* Charge l'AST du fichier Java. */
    ICompilationUnit compilationUnit = JdtUtils.getCompilationUnit(file, javaProject);
    if (compilationUnit == null) {
        return null;
    }
    try {
        /* Parcourt les types du fichier Java. */
        for (IType type : compilationUnit.getAllTypes()) {

            if (!type.isClass()) {
                continue;
            }

            /* Créé le JavaClassFile. */
            String javaName = type.getElementName();
            String packageName = type.getPackageFragment().getElementName();
            ISourceRange nameRange = type.getNameRange();
            FileRegion fileRegion = new FileRegion(file, nameRange.getOffset(), nameRange.getLength());
            return new JavaClassFile(fileRegion, javaName, packageName);
        }
    } catch (JavaModelException e) {
        ErrorUtils.handle(e);
    }

    return null;
}
项目:eclipse.jdt.ls    文件:JavaStatusContext.java   
@Override
public ISourceRange getSourceRange() {
    try {
        return fMember.getSourceRange();
    } catch (JavaModelException e) {
        return new SourceRange(0, 0);
    }
}
项目:eclipse.jdt.ls    文件:JavaStatusContext.java   
@Override
public ISourceRange getSourceRange() {
    try {
        return fImportDeclartion.getSourceRange();
    } catch (JavaModelException e) {
        return new SourceRange(0, 0);
    }
}
项目:eclipse.jdt.ls    文件:CodeLensHandler.java   
private CodeLens getCodeLens(String type, IJavaElement element, ITypeRoot typeRoot) throws JavaModelException {
    CodeLens lens = new CodeLens();
    ISourceRange r = ((ISourceReference) element).getNameRange();
    final Range range = JDTUtils.toRange(typeRoot, r.getOffset(), r.getLength());
    lens.setRange(range);
    String uri = ResourceUtils.toClientUri(JDTUtils.toUri(typeRoot));
    lens.setData(Arrays.asList(uri, range.getStart(), type));
    return lens;
}
项目:Sparrow    文件:ModelVisitor.java   
private String getComments(ICompilationUnit unit, IMember member) {
    try {
        ISourceRange range = member.getJavadocRange();
        if (range != null)
            return unit.getSource().substring(range.getOffset(), range.getOffset() + range.getLength());
    } catch (JavaModelException e1) {
        e1.printStackTrace();
    }
    return null;
}
项目:che    文件:JavaNavigation.java   
private OpenDeclarationDescriptor compilationUnitNavigation(
    ICompilationUnit unit, IJavaElement element) throws JavaModelException {
  OpenDeclarationDescriptor dto =
      DtoFactory.getInstance().createDto(OpenDeclarationDescriptor.class);
  String absolutePath = unit.getPath().toOSString();
  dto.setPath(absolutePath);
  dto.setBinary(false);
  if (element instanceof ISourceReference) {
    ISourceRange nameRange = ((ISourceReference) element).getNameRange();
    dto.setOffset(nameRange.getOffset());
    dto.setLength(nameRange.getLength());
  }

  return dto;
}
项目:che    文件:JavaTypeHierarchy.java   
private void setRange(Member member, IMember iMember) throws JavaModelException {
  ISourceRange nameRange = iMember.getNameRange();
  if (iMember.isBinary()) {
    nameRange = iMember.getSourceRange();
  }

  if (nameRange == null) {
    return;
  }

  member.setFileRegion(convertToRegionDTO(iMember.getSourceRange()));
}
项目:che    文件:ImportOrganizeTest.java   
protected IChooseImportQuery createQuery(
    final String name, final String[] choices, final int[] nEntries) {
  return new IChooseImportQuery() {
    public TypeNameMatch[] chooseImports(TypeNameMatch[][] openChoices, ISourceRange[] ranges) {
      assertTrue(name + "-query-nchoices1", choices.length == openChoices.length);
      assertTrue(name + "-query-nchoices2", nEntries.length == openChoices.length);
      for (int i = 0; i < nEntries.length; i++) {
        assertTrue(name + "-query-cnt" + i, openChoices[i].length == nEntries[i]);
      }
      TypeNameMatch[] res = new TypeNameMatch[openChoices.length];
      for (int i = 0; i < openChoices.length; i++) {
        TypeNameMatch[] selection = openChoices[i];
        assertNotNull(name + "-query-setset" + i, selection);
        assertTrue(name + "-query-setlen" + i, selection.length > 0);
        TypeNameMatch found = null;
        for (int k = 0; k < selection.length; k++) {
          if (selection[k].getFullyQualifiedName().equals(choices[i])) {
            found = selection[k];
          }
        }
        assertNotNull(name + "-query-notfound" + i, found);
        res[i] = found;
      }
      return res;
    }
  };
}
项目:che    文件:Rename18Test.java   
private ISourceRange getSelection(ICompilationUnit cu) throws Exception {
  String source = cu.getSource();
  // Warning: this *includes* the SQUARE_BRACKET_OPEN!
  int offset = source.indexOf(SQUARE_BRACKET_OPEN);
  int end = source.indexOf(SQUARE_BRACKET_CLOSE);
  return new SourceRange(offset + SQUARE_BRACKET_OPEN.length(), end - offset);
}