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

项目:junit-tools    文件:JDTUtils.java   
private static String getFullQualifiedName(IImportDeclaration[] imports,
        String paramType) {
    if (imports == null) {
        return null;
    }

    String importFullQualifiedName;
    String importType;

    for (IImportDeclaration importDeclaration : imports) {
        importFullQualifiedName = importDeclaration.getElementName();
        importType = importFullQualifiedName
                .substring(importFullQualifiedName.lastIndexOf(".") + 1);
        if (paramType.equals(importType)) {
            return importFullQualifiedName;
        }
    }

    return null;
}
项目:che    文件:ASTNodeSearchUtil.java   
public static ASTNode[] getDeclarationNodes(IJavaElement element, CompilationUnit cuNode)
    throws JavaModelException {
  switch (element.getElementType()) {
    case IJavaElement.FIELD:
      return new ASTNode[] {getFieldOrEnumConstantDeclaration((IField) element, cuNode)};
    case IJavaElement.IMPORT_CONTAINER:
      return getImportNodes((IImportContainer) element, cuNode);
    case IJavaElement.IMPORT_DECLARATION:
      return new ASTNode[] {getImportDeclarationNode((IImportDeclaration) element, cuNode)};
    case IJavaElement.INITIALIZER:
      return new ASTNode[] {getInitializerNode((IInitializer) element, cuNode)};
    case IJavaElement.METHOD:
      return new ASTNode[] {
        getMethodOrAnnotationTypeMemberDeclarationNode((IMethod) element, cuNode)
      };
    case IJavaElement.PACKAGE_DECLARATION:
      return new ASTNode[] {getPackageDeclarationNode((IPackageDeclaration) element, cuNode)};
    case IJavaElement.TYPE:
      return new ASTNode[] {getAbstractTypeDeclarationNode((IType) element, cuNode)};
    default:
      Assert.isTrue(false, String.valueOf(element.getElementType()));
      return null;
  }
}
项目:che    文件:RenameTypeProcessor.java   
private RefactoringStatus checkTypesImportedInCu() throws CoreException {
  IImportDeclaration imp = getImportedType(fType.getCompilationUnit(), getNewElementName());

  if (imp == null) return null;

  String msg =
      Messages.format(
          RefactoringCoreMessages.RenameTypeRefactoring_imported,
          new Object[] {
            getNewElementLabel(),
            BasicElementLabels.getPathLabel(
                fType.getCompilationUnit().getResource().getFullPath(), false)
          });
  IJavaElement grandParent = imp.getParent().getParent();
  if (grandParent instanceof ICompilationUnit)
    return RefactoringStatus.createErrorStatus(msg, JavaStatusContext.create(imp));

  return null;
}
项目:che    文件:RenameTypeProcessor.java   
private void analyzeImportedTypes(IType[] types, RefactoringStatus result, IImportDeclaration imp)
    throws CoreException {
  for (int i = 0; i < types.length; i++) {
    // could this be a problem (same package imports)?
    if (JdtFlags.isPublic(types[i]) && types[i].getElementName().equals(getNewElementName())) {
      String msg =
          Messages.format(
              RefactoringCoreMessages.RenameTypeRefactoring_name_conflict1,
              new Object[] {
                JavaElementLabels.getElementLabel(
                    types[i], JavaElementLabels.ALL_FULLY_QUALIFIED),
                BasicElementLabels.getPathLabel(getCompilationUnit(imp).getPath(), false)
              });
      result.addError(msg, JavaStatusContext.create(imp));
    }
  }
}
项目:che    文件:RenameTypeProcessor.java   
private void analyzeImportDeclaration(IImportDeclaration imp, RefactoringStatus result)
    throws CoreException {
  if (!imp.isOnDemand()) return; // analyzed earlier

  IJavaElement imported = convertFromImportDeclaration(imp);
  if (imported == null) return;

  if (imported instanceof IPackageFragment) {
    ICompilationUnit[] cus = ((IPackageFragment) imported).getCompilationUnits();
    for (int i = 0; i < cus.length; i++) {
      analyzeImportedTypes(cus[i].getTypes(), result, imp);
    }
  } else {
    // cast safe: see JavaModelUtility.convertFromImportDeclaration
    analyzeImportedTypes(((IType) imported).getTypes(), result, imp);
  }
}
项目:che    文件:RenamePackageProcessor.java   
/**
 * Add new imports to types in <code>typeReferences</code> with package <code>fPackage</code>.
 *
 * @param typeReferences type references
 * @throws CoreException should not happen
 */
private void addTypeImports(SearchResultGroup typeReferences) throws CoreException {
  SearchMatch[] searchResults = typeReferences.getSearchResults();
  for (int i = 0; i < searchResults.length; i++) {
    SearchMatch result = searchResults[i];
    IJavaElement enclosingElement = SearchUtils.getEnclosingJavaElement(result);
    if (!(enclosingElement instanceof IImportDeclaration)) {
      String reference = getNormalizedTypeReference(result);
      if (!reference.startsWith(fPackage.getElementName())) {
        // is unqualified
        reference = cutOffInnerTypes(reference);
        ImportChange importChange =
            fImportsManager.getImportChange(typeReferences.getCompilationUnit());
        importChange.addImport(fPackage.getElementName() + '.' + reference);
      }
    }
  }
}
项目:che    文件:RenamePackageProcessor.java   
/**
 * Add new imports to types in <code>typeReferences</code> with package <code>fNewElementName
 * </code> and remove old import with <code>fPackage</code>.
 *
 * @param typeReferences type references
 * @throws CoreException should not happen
 */
private void updateTypeImports(SearchResultGroup typeReferences) throws CoreException {
  SearchMatch[] searchResults = typeReferences.getSearchResults();
  for (int i = 0; i < searchResults.length; i++) {
    SearchMatch result = searchResults[i];
    IJavaElement enclosingElement = SearchUtils.getEnclosingJavaElement(result);
    if (enclosingElement instanceof IImportDeclaration) {
      IImportDeclaration importDeclaration = (IImportDeclaration) enclosingElement;
      updateImport(
          typeReferences.getCompilationUnit(),
          importDeclaration,
          getUpdatedImport(importDeclaration));
    } else {
      String reference = getNormalizedTypeReference(result);
      if (!reference.startsWith(fPackage.getElementName())) {
        reference = cutOffInnerTypes(reference);
        ImportChange importChange =
            fImportsManager.getImportChange(typeReferences.getCompilationUnit());
        importChange.removeImport(fPackage.getElementName() + '.' + reference);
        importChange.addImport(getNewPackageName() + '.' + reference);
      } // else: already found & updated with package reference search
    }
  }
}
项目:che    文件:ReorgPolicyFactory.java   
private void copyImportsToDestination(
    IImportContainer container,
    ASTRewrite rewrite,
    CompilationUnit sourceCuNode,
    CompilationUnit destinationCuNode)
    throws JavaModelException {
  ListRewrite listRewrite =
      rewrite.getListRewrite(destinationCuNode, CompilationUnit.IMPORTS_PROPERTY);

  IJavaElement[] importDeclarations = container.getChildren();
  for (int i = 0; i < importDeclarations.length; i++) {
    IImportDeclaration declaration = (IImportDeclaration) importDeclarations[i];

    ImportDeclaration sourceNode =
        ASTNodeSearchUtil.getImportDeclarationNode(declaration, sourceCuNode);
    ImportDeclaration copiedNode =
        (ImportDeclaration) ASTNode.copySubtree(rewrite.getAST(), sourceNode);

    if (getLocation() == IReorgDestination.LOCATION_BEFORE) {
      listRewrite.insertFirst(copiedNode, null);
    } else {
      listRewrite.insertLast(copiedNode, null);
    }
  }
}
项目:che    文件:ReorgPolicyFactory.java   
private void copyImportToDestination(
    IImportDeclaration declaration,
    ASTRewrite targetRewrite,
    CompilationUnit sourceCuNode,
    CompilationUnit destinationCuNode)
    throws JavaModelException {
  ImportDeclaration sourceNode =
      ASTNodeSearchUtil.getImportDeclarationNode(declaration, sourceCuNode);
  ImportDeclaration copiedNode =
      (ImportDeclaration) ASTNode.copySubtree(targetRewrite.getAST(), sourceNode);
  ListRewrite listRewrite =
      targetRewrite.getListRewrite(destinationCuNode, CompilationUnit.IMPORTS_PROPERTY);

  if (getJavaElementDestination() instanceof IImportDeclaration) {
    ImportDeclaration destinationNode =
        ASTNodeSearchUtil.getImportDeclarationNode(
            (IImportDeclaration) getJavaElementDestination(), destinationCuNode);
    insertRelative(copiedNode, destinationNode, listRewrite);
  } else {
    // dropped on container, we could be better here
    listRewrite.insertLast(copiedNode, null);
  }
}
项目:che    文件:MoveCuUpdateCreator.java   
private void addStaticImport(
    ICompilationUnit movedUnit, IImportDeclaration importDecl, ImportRewrite rewrite) {
  String old = importDecl.getElementName();
  int oldPackLength = movedUnit.getParent().getElementName().length();

  StringBuffer result = new StringBuffer(fDestination.getElementName());
  if (oldPackLength == 0) // move FROM default package
  result.append('.').append(old);
  else if (result.length() == 0) // move TO default package
  result.append(old.substring(oldPackLength + 1)); // cut "."
  else result.append(old.substring(oldPackLength));
  int index = result.lastIndexOf("."); // $NON-NLS-1$
  if (index > 0 && index < result.length() - 1)
    rewrite.addStaticImport(
        result.substring(0, index), result.substring(index + 1, result.length()), true);
}
项目:che    文件:JavaTestFinder.java   
private boolean isImportOfTestAnnotationExist(
    ICompilationUnit compilationUnit, String testAnnotation) {
  try {
    IImportDeclaration[] imports = compilationUnit.getImports();
    for (IImportDeclaration importDeclaration : imports) {
      String elementName = importDeclaration.getElementName();
      if (testAnnotation.equals(elementName)) {
        return true;
      }
      if (importDeclaration.isOnDemand()
          && testAnnotation.startsWith(
              elementName.substring(0, elementName.length() - 3))) { // remove .*
        return true;
      }
    }
  } catch (JavaModelException e) {
    LOG.info("Can't read class imports.", e);
    return false;
  }
  return false;
}
项目:Eclipse-Postfix-Code-Completion    文件:ASTNodeSearchUtil.java   
public static ASTNode[] getDeclarationNodes(IJavaElement element, CompilationUnit cuNode) throws JavaModelException {
    switch(element.getElementType()){
        case IJavaElement.FIELD:
            return new ASTNode[]{getFieldOrEnumConstantDeclaration((IField) element, cuNode)};
        case IJavaElement.IMPORT_CONTAINER:
            return getImportNodes((IImportContainer)element, cuNode);
        case IJavaElement.IMPORT_DECLARATION:
            return new ASTNode[]{getImportDeclarationNode((IImportDeclaration)element, cuNode)};
        case IJavaElement.INITIALIZER:
            return new ASTNode[]{getInitializerNode((IInitializer)element, cuNode)};
        case IJavaElement.METHOD:
            return new ASTNode[]{getMethodOrAnnotationTypeMemberDeclarationNode((IMethod) element, cuNode)};
        case IJavaElement.PACKAGE_DECLARATION:
            return new ASTNode[]{getPackageDeclarationNode((IPackageDeclaration)element, cuNode)};
        case IJavaElement.TYPE:
            return new ASTNode[]{getAbstractTypeDeclarationNode((IType) element, cuNode)};
        default:
            Assert.isTrue(false, String.valueOf(element.getElementType()));
            return null;
    }
}
项目:Eclipse-Postfix-Code-Completion    文件:RenameTypeProcessor.java   
private void analyzeImportDeclaration(IImportDeclaration imp, RefactoringStatus result) throws CoreException{
    if (!imp.isOnDemand())
        return; //analyzed earlier

    IJavaElement imported= convertFromImportDeclaration(imp);
    if (imported == null)
        return;

    if (imported instanceof IPackageFragment){
        ICompilationUnit[] cus= ((IPackageFragment)imported).getCompilationUnits();
        for (int i= 0; i < cus.length; i++) {
            analyzeImportedTypes(cus[i].getTypes(), result, imp);
        }
    } else {
        //cast safe: see JavaModelUtility.convertFromImportDeclaration
        analyzeImportedTypes(((IType)imported).getTypes(), result, imp);
    }
}
项目:Eclipse-Postfix-Code-Completion    文件:RenamePackageProcessor.java   
/**
 * Add new imports to types in <code>typeReferences</code> with package <code>fPackage</code>.
 * @param typeReferences type references
 * @throws CoreException should not happen
 */
private void addTypeImports(SearchResultGroup typeReferences) throws CoreException {
    SearchMatch[] searchResults= typeReferences.getSearchResults();
    for (int i= 0; i < searchResults.length; i++) {
        SearchMatch result= searchResults[i];
        IJavaElement enclosingElement= SearchUtils.getEnclosingJavaElement(result);
        if (! (enclosingElement instanceof IImportDeclaration)) {
            String reference= getNormalizedTypeReference(result);
            if (! reference.startsWith(fPackage.getElementName())) {
                // is unqualified
                reference= cutOffInnerTypes(reference);
                ImportChange importChange= fImportsManager.getImportChange(typeReferences.getCompilationUnit());
                importChange.addImport(fPackage.getElementName() + '.' + reference);
            }
        }
    }
}
项目:Eclipse-Postfix-Code-Completion    文件:RenamePackageProcessor.java   
/**
 * Add new imports to types in <code>typeReferences</code> with package <code>fNewElementName</code>
 * and remove old import with <code>fPackage</code>.
 * @param typeReferences type references
 * @throws CoreException should not happen
 */
private void updateTypeImports(SearchResultGroup typeReferences) throws CoreException {
    SearchMatch[] searchResults= typeReferences.getSearchResults();
    for (int i= 0; i < searchResults.length; i++) {
        SearchMatch result= searchResults[i];
        IJavaElement enclosingElement= SearchUtils.getEnclosingJavaElement(result);
        if (enclosingElement instanceof IImportDeclaration) {
            IImportDeclaration importDeclaration= (IImportDeclaration) enclosingElement;
            updateImport(typeReferences.getCompilationUnit(), importDeclaration, getUpdatedImport(importDeclaration));
        } else {
            String reference= getNormalizedTypeReference(result);
            if (! reference.startsWith(fPackage.getElementName())) {
                reference= cutOffInnerTypes(reference);
                ImportChange importChange= fImportsManager.getImportChange(typeReferences.getCompilationUnit());
                importChange.removeImport(fPackage.getElementName() + '.' + reference);
                importChange.addImport(getNewPackageName() + '.' + reference);
            } // else: already found & updated with package reference search
        }
    }
}
项目:Eclipse-Postfix-Code-Completion    文件:ReorgPolicyFactory.java   
private void copyImportsToDestination(IImportContainer container, ASTRewrite rewrite, CompilationUnit sourceCuNode, CompilationUnit destinationCuNode) throws JavaModelException {
    ListRewrite listRewrite= rewrite.getListRewrite(destinationCuNode, CompilationUnit.IMPORTS_PROPERTY);

    IJavaElement[] importDeclarations= container.getChildren();
    for (int i= 0; i < importDeclarations.length; i++) {
        IImportDeclaration declaration= (IImportDeclaration) importDeclarations[i];

        ImportDeclaration sourceNode= ASTNodeSearchUtil.getImportDeclarationNode(declaration, sourceCuNode);
        ImportDeclaration copiedNode= (ImportDeclaration) ASTNode.copySubtree(rewrite.getAST(), sourceNode);

        if (getLocation() == IReorgDestination.LOCATION_BEFORE) {
            listRewrite.insertFirst(copiedNode, null);
        } else {
            listRewrite.insertLast(copiedNode, null);
        }
    }
}
项目:Eclipse-Postfix-Code-Completion    文件:JavaEditorBreadcrumb.java   
/**
 * Returns the input for the given element. The Java breadcrumb does not show some elements of
 * the model:
 * <ul>
 *      <li><code>ITypeRoots</li>
 *      <li><code>IPackageDeclaration</li>
 *      <li><code>IImportContainer</li>
 *      <li><code>IImportDeclaration</li>
 * </ul>
 *
 * @param element the potential input element
 * @return the element to use as input
 */
private IJavaElement getInput(IJavaElement element) {
    try {
        if (element instanceof IImportDeclaration)
            element= element.getParent();

        if (element instanceof IImportContainer)
            element= element.getParent();

        if (element instanceof IPackageDeclaration)
            element= element.getParent();

        if (element instanceof ICompilationUnit) {
            IType[] types= ((ICompilationUnit) element).getTypes();
            if (types.length > 0)
                element= types[0];
        }

        if (element instanceof IClassFile)
            element= ((IClassFile) element).getType();

        return element;
    } catch (JavaModelException e) {
        return null;
    }
}
项目:Eclipse-Postfix-Code-Completion    文件:MembersView.java   
/**
 * Answers if the given <code>element</code> is a valid
 * element for this part.
 *
 * @param   element the object to test
 * @return  <true> if the given element is a valid element
 */
@Override
protected boolean isValidElement(Object element) {
    if (element instanceof IMember)
        return super.isValidElement(((IMember)element).getDeclaringType());
    else if (element instanceof IImportDeclaration)
        return isValidElement(((IJavaElement)element).getParent());
    else if (element instanceof IImportContainer) {
        Object input= getViewer().getInput();
        if (input instanceof IJavaElement) {
            ICompilationUnit cu= (ICompilationUnit)((IJavaElement)input).getAncestor(IJavaElement.COMPILATION_UNIT);
            if (cu != null) {
                ICompilationUnit importContainerCu= (ICompilationUnit)((IJavaElement)element).getAncestor(IJavaElement.COMPILATION_UNIT);
                return cu.equals(importContainerCu);
            } else {
                IClassFile cf= (IClassFile)((IJavaElement)input).getAncestor(IJavaElement.CLASS_FILE);
                IClassFile importContainerCf= (IClassFile)((IJavaElement)element).getAncestor(IJavaElement.CLASS_FILE);
                return cf != null && cf.equals(importContainerCf);
            }
        }
    }
    return false;
}
项目:Eclipse-Postfix-Code-Completion    文件:CreatePackageDeclarationOperation.java   
/**
 * Sets the correct position for new package declaration:<ul>
 * <li> before the first import
 * <li> if no imports, before the first type
 * <li> if no type - first thing in the CU
 * <li>
 */
protected void initializeDefaultPosition() {
    try {
        ICompilationUnit cu = getCompilationUnit();
        IImportDeclaration[] imports = cu.getImports();
        if (imports.length > 0) {
            createBefore(imports[0]);
            return;
        }
        IType[] types = cu.getTypes();
        if (types.length > 0) {
            createBefore(types[0]);
            return;
        }
    } catch (JavaModelException e) {
        // cu doesn't exist: ignore
    }
}
项目:Eclipse-Postfix-Code-Completion    文件:CreateImportOperation.java   
/**
 * Sets the correct position for the new import:<ul>
 * <li> after the last import
 * <li> if no imports, before the first type
 * <li> if no type, after the package statement
 * <li> and if no package statement - first thing in the CU
 */
protected void initializeDefaultPosition() {
    try {
        ICompilationUnit cu = getCompilationUnit();
        IImportDeclaration[] imports = cu.getImports();
        if (imports.length > 0) {
            createAfter(imports[imports.length - 1]);
            return;
        }
        IType[] types = cu.getTypes();
        if (types.length > 0) {
            createBefore(types[0]);
            return;
        }
        IJavaElement[] children = cu.getChildren();
        //look for the package declaration
        for (int i = 0; i < children.length; i++) {
            if (children[i].getElementType() == IJavaElement.PACKAGE_DECLARATION) {
                createAfter(children[i]);
                return;
            }
        }
    } catch (JavaModelException e) {
        // cu doesn't exit: ignore
    }
}
项目:Eclipse-Postfix-Code-Completion    文件:ImportRewrite.java   
/**
 * Creates an {@link ImportRewrite} from an {@link ICompilationUnit}. If <code>restoreExistingImports</code>
 * is <code>true</code>, all existing imports are kept, and new imports will be inserted at best matching locations. If
 * <code>restoreExistingImports</code> is <code>false</code>, the existing imports will be removed and only the
 * newly added imports will be created.
 * <p>
 * Note that {@link #create(CompilationUnit, boolean)} is more efficient than this method if an AST for
 * the compilation unit is already available.
 * </p>
 * @param cu the compilation unit to create the imports for
 * @param restoreExistingImports specifies if the existing imports should be kept or removed.
 * @return the created import rewriter.
 * @throws JavaModelException thrown when the compilation unit could not be accessed.
 */
public static ImportRewrite create(ICompilationUnit cu, boolean restoreExistingImports) throws JavaModelException {
    if (cu == null) {
        throw new IllegalArgumentException("Compilation unit must not be null"); //$NON-NLS-1$
    }
    List existingImport= null;
    if (restoreExistingImports) {
        existingImport= new ArrayList();
        IImportDeclaration[] imports= cu.getImports();
        for (int i= 0; i < imports.length; i++) {
            IImportDeclaration curr= imports[i];
            char prefix= Flags.isStatic(curr.getFlags()) ? STATIC_PREFIX : NORMAL_PREFIX;
            existingImport.add(prefix + curr.getElementName());
        }
    }
    return new ImportRewrite(cu, null, existingImport);
}
项目:Eclipse-Postfix-Code-Completion-Juno38    文件:ASTNodeSearchUtil.java   
public static ASTNode[] getDeclarationNodes(IJavaElement element, CompilationUnit cuNode) throws JavaModelException {
    switch(element.getElementType()){
        case IJavaElement.FIELD:
            return new ASTNode[]{getFieldOrEnumConstantDeclaration((IField) element, cuNode)};
        case IJavaElement.IMPORT_CONTAINER:
            return getImportNodes((IImportContainer)element, cuNode);
        case IJavaElement.IMPORT_DECLARATION:
            return new ASTNode[]{getImportDeclarationNode((IImportDeclaration)element, cuNode)};
        case IJavaElement.INITIALIZER:
            return new ASTNode[]{getInitializerNode((IInitializer)element, cuNode)};
        case IJavaElement.METHOD:
            return new ASTNode[]{getMethodOrAnnotationTypeMemberDeclarationNode((IMethod) element, cuNode)};
        case IJavaElement.PACKAGE_DECLARATION:
            return new ASTNode[]{getPackageDeclarationNode((IPackageDeclaration)element, cuNode)};
        case IJavaElement.TYPE:
            return new ASTNode[]{getAbstractTypeDeclarationNode((IType) element, cuNode)};
        default:
            Assert.isTrue(false, String.valueOf(element.getElementType()));
            return null;
    }
}
项目:Eclipse-Postfix-Code-Completion-Juno38    文件:RenameTypeProcessor.java   
private void analyzeImportDeclaration(IImportDeclaration imp, RefactoringStatus result) throws CoreException{
    if (!imp.isOnDemand())
        return; //analyzed earlier

    IJavaElement imported= convertFromImportDeclaration(imp);
    if (imported == null)
        return;

    if (imported instanceof IPackageFragment){
        ICompilationUnit[] cus= ((IPackageFragment)imported).getCompilationUnits();
        for (int i= 0; i < cus.length; i++) {
            analyzeImportedTypes(cus[i].getTypes(), result, imp);
        }
    } else {
        //cast safe: see JavaModelUtility.convertFromImportDeclaration
        analyzeImportedTypes(((IType)imported).getTypes(), result, imp);
    }
}
项目:Eclipse-Postfix-Code-Completion-Juno38    文件:RenamePackageProcessor.java   
/**
 * Add new imports to types in <code>typeReferences</code> with package <code>fPackage</code>.
 * @param typeReferences type references
 * @throws CoreException should not happen
 */
private void addTypeImports(SearchResultGroup typeReferences) throws CoreException {
    SearchMatch[] searchResults= typeReferences.getSearchResults();
    for (int i= 0; i < searchResults.length; i++) {
        SearchMatch result= searchResults[i];
        IJavaElement enclosingElement= SearchUtils.getEnclosingJavaElement(result);
        if (! (enclosingElement instanceof IImportDeclaration)) {
            String reference= getNormalizedTypeReference(result);
            if (! reference.startsWith(fPackage.getElementName())) {
                // is unqualified
                reference= cutOffInnerTypes(reference);
                ImportChange importChange= fImportsManager.getImportChange(typeReferences.getCompilationUnit());
                importChange.addImport(fPackage.getElementName() + '.' + reference);
            }
        }
    }
}
项目:Eclipse-Postfix-Code-Completion-Juno38    文件:RenamePackageProcessor.java   
/**
 * Add new imports to types in <code>typeReferences</code> with package <code>fNewElementName</code>
 * and remove old import with <code>fPackage</code>.
 * @param typeReferences type references
 * @throws CoreException should not happen
 */
private void updateTypeImports(SearchResultGroup typeReferences) throws CoreException {
    SearchMatch[] searchResults= typeReferences.getSearchResults();
    for (int i= 0; i < searchResults.length; i++) {
        SearchMatch result= searchResults[i];
        IJavaElement enclosingElement= SearchUtils.getEnclosingJavaElement(result);
        if (enclosingElement instanceof IImportDeclaration) {
            IImportDeclaration importDeclaration= (IImportDeclaration) enclosingElement;
            updateImport(typeReferences.getCompilationUnit(), importDeclaration, getUpdatedImport(importDeclaration));
        } else {
            String reference= getNormalizedTypeReference(result);
            if (! reference.startsWith(fPackage.getElementName())) {
                reference= cutOffInnerTypes(reference);
                ImportChange importChange= fImportsManager.getImportChange(typeReferences.getCompilationUnit());
                importChange.removeImport(fPackage.getElementName() + '.' + reference);
                importChange.addImport(getNewPackageName() + '.' + reference);
            } // else: already found & updated with package reference search
        }
    }
}
项目:Eclipse-Postfix-Code-Completion-Juno38    文件:ReorgPolicyFactory.java   
private void copyImportsToDestination(IImportContainer container, ASTRewrite rewrite, CompilationUnit sourceCuNode, CompilationUnit destinationCuNode) throws JavaModelException {
    ListRewrite listRewrite= rewrite.getListRewrite(destinationCuNode, CompilationUnit.IMPORTS_PROPERTY);

    IJavaElement[] importDeclarations= container.getChildren();
    for (int i= 0; i < importDeclarations.length; i++) {
        IImportDeclaration declaration= (IImportDeclaration) importDeclarations[i];

        ImportDeclaration sourceNode= ASTNodeSearchUtil.getImportDeclarationNode(declaration, sourceCuNode);
        ImportDeclaration copiedNode= (ImportDeclaration) ASTNode.copySubtree(rewrite.getAST(), sourceNode);

        if (getLocation() == IReorgDestination.LOCATION_BEFORE) {
            listRewrite.insertFirst(copiedNode, null);
        } else {
            listRewrite.insertLast(copiedNode, null);
        }
    }
}
项目:Eclipse-Postfix-Code-Completion-Juno38    文件:JavaEditorBreadcrumb.java   
/**
 * Returns the input for the given element. The Java breadcrumb does not show some elements of
 * the model:
 * <ul>
 *      <li><code>ITypeRoots</li>
 *      <li><code>IPackageDeclaration</li>
 *      <li><code>IImportContainer</li>
 *      <li><code>IImportDeclaration</li>
 * </ul>
 *
 * @param element the potential input element
 * @return the element to use as input
 */
private IJavaElement getInput(IJavaElement element) {
    try {
        if (element instanceof IImportDeclaration)
            element= element.getParent();

        if (element instanceof IImportContainer)
            element= element.getParent();

        if (element instanceof IPackageDeclaration)
            element= element.getParent();

        if (element instanceof ICompilationUnit) {
            IType[] types= ((ICompilationUnit) element).getTypes();
            if (types.length > 0)
                element= types[0];
        }

        if (element instanceof IClassFile)
            element= ((IClassFile) element).getType();

        return element;
    } catch (JavaModelException e) {
        return null;
    }
}
项目:Eclipse-Postfix-Code-Completion-Juno38    文件:MembersView.java   
/**
 * Answers if the given <code>element</code> is a valid
 * element for this part.
 *
 * @param   element the object to test
 * @return  <true> if the given element is a valid element
 */
@Override
protected boolean isValidElement(Object element) {
    if (element instanceof IMember)
        return super.isValidElement(((IMember)element).getDeclaringType());
    else if (element instanceof IImportDeclaration)
        return isValidElement(((IJavaElement)element).getParent());
    else if (element instanceof IImportContainer) {
        Object input= getViewer().getInput();
        if (input instanceof IJavaElement) {
            ICompilationUnit cu= (ICompilationUnit)((IJavaElement)input).getAncestor(IJavaElement.COMPILATION_UNIT);
            if (cu != null) {
                ICompilationUnit importContainerCu= (ICompilationUnit)((IJavaElement)element).getAncestor(IJavaElement.COMPILATION_UNIT);
                return cu.equals(importContainerCu);
            } else {
                IClassFile cf= (IClassFile)((IJavaElement)input).getAncestor(IJavaElement.CLASS_FILE);
                IClassFile importContainerCf= (IClassFile)((IJavaElement)element).getAncestor(IJavaElement.CLASS_FILE);
                return cf != null && cf.equals(importContainerCf);
            }
        }
    }
    return false;
}
项目:Eclipse-Postfix-Code-Completion-Juno38    文件:CreatePackageDeclarationOperation.java   
/**
 * Sets the correct position for new package declaration:<ul>
 * <li> before the first import
 * <li> if no imports, before the first type
 * <li> if no type - first thing in the CU
 * <li>
 */
protected void initializeDefaultPosition() {
    try {
        ICompilationUnit cu = getCompilationUnit();
        IImportDeclaration[] imports = cu.getImports();
        if (imports.length > 0) {
            createBefore(imports[0]);
            return;
        }
        IType[] types = cu.getTypes();
        if (types.length > 0) {
            createBefore(types[0]);
            return;
        }
    } catch (JavaModelException e) {
        // cu doesn't exist: ignore
    }
}
项目:Eclipse-Postfix-Code-Completion-Juno38    文件:CreateImportOperation.java   
/**
 * Sets the correct position for the new import:<ul>
 * <li> after the last import
 * <li> if no imports, before the first type
 * <li> if no type, after the package statement
 * <li> and if no package statement - first thing in the CU
 */
protected void initializeDefaultPosition() {
    try {
        ICompilationUnit cu = getCompilationUnit();
        IImportDeclaration[] imports = cu.getImports();
        if (imports.length > 0) {
            createAfter(imports[imports.length - 1]);
            return;
        }
        IType[] types = cu.getTypes();
        if (types.length > 0) {
            createBefore(types[0]);
            return;
        }
        IJavaElement[] children = cu.getChildren();
        //look for the package declaration
        for (int i = 0; i < children.length; i++) {
            if (children[i].getElementType() == IJavaElement.PACKAGE_DECLARATION) {
                createAfter(children[i]);
                return;
            }
        }
    } catch (JavaModelException e) {
        // cu doesn't exit: ignore
    }
}
项目:Eclipse-Postfix-Code-Completion-Juno38    文件:ImportRewrite.java   
/**
 * Creates a {@link ImportRewrite} from a {@link ICompilationUnit}. If <code>restoreExistingImports</code>
 * is <code>true</code>, all existing imports are kept, and new imports will be inserted at best matching locations. If
 * <code>restoreExistingImports</code> is <code>false</code>, the existing imports will be removed and only the
 * newly added imports will be created.
 * <p>
 * Note that {@link #create(ICompilationUnit, boolean)} is more efficient than this method if an AST for
 * the compilation unit is already available.
 * </p>
 * @param cu the compilation unit to create the imports for
 * @param restoreExistingImports specifies if the existing imports should be kept or removed.
 * @return the created import rewriter.
 * @throws JavaModelException thrown when the compilation unit could not be accessed.
 */
public static ImportRewrite create(ICompilationUnit cu, boolean restoreExistingImports) throws JavaModelException {
    if (cu == null) {
        throw new IllegalArgumentException("Compilation unit must not be null"); //$NON-NLS-1$
    }
    List existingImport= null;
    if (restoreExistingImports) {
        existingImport= new ArrayList();
        IImportDeclaration[] imports= cu.getImports();
        for (int i= 0; i < imports.length; i++) {
            IImportDeclaration curr= imports[i];
            char prefix= Flags.isStatic(curr.getFlags()) ? STATIC_PREFIX : NORMAL_PREFIX;
            existingImport.add(prefix + curr.getElementName());
        }
    }
    return new ImportRewrite(cu, null, existingImport);
}
项目:get-set-generator    文件:ProjectUtil.java   
public static String getImportDeclaration(IFile file, String className)
        throws JavaModelException {
    String fullyQualifiedName = null;
    ICompilationUnit currentFile = JavaCore.createCompilationUnitFrom(file);
    IImportDeclaration[] imports = currentFile.getImports();
    for (IImportDeclaration iImportDeclaration : imports) {
        if (iImportDeclaration.getElementName().endsWith(
                MethodUtil.PACKAGE_DOT + className)) {
            fullyQualifiedName = iImportDeclaration.getElementName();
            break;
        }
    }
    if (fullyQualifiedName == null || fullyQualifiedName.length() <= 0) {
        IPackageDeclaration packageDeclaration = currentFile
                .getPackageDeclarations()[0];
        fullyQualifiedName = packageDeclaration.getElementName()
                + MethodUtil.PACKAGE_DOT + className;
    }
    return fullyQualifiedName;
}
项目:querybuilder_plugin    文件:ParserHelper.java   
public static String getMatchedPackage(String className, ICompilationUnit cUnit) throws JavaModelException {
    int higherAccuracy = 0;
    String matchedPackage = cUnit.getPackageDeclarations()[0].getElementName();
    IImportDeclaration[] imports = cUnit.getImports();
    for (IImportDeclaration impDec : imports) {
        String fullName = impDec.getElementName();
        int dotIndex = fullName.lastIndexOf('.');

        String lastNameOfImport = fullName.substring(dotIndex + 1);
        if (lastNameOfImport.equals(className) && higherAccuracy < 2) {
            matchedPackage = fullName.substring(0, dotIndex);
            higherAccuracy = 2;
        } else if (lastNameOfImport.equals("*") && higherAccuracy < 1) {
            matchedPackage = fullName.substring(0, dotIndex);
            higherAccuracy = 1;
        }
    }

    if (higherAccuracy > 0) return matchedPackage;

    if (cUnit.getType(className) != null) return cUnit.getPackageDeclarations()[0].getElementName();

    return "java.lang";
}
项目:codehint    文件:StochasticExpressionGenerator.java   
/**
 * Adds locals, constants, and imports to seed the search.
 * @param typeConstraint The type constraint.
 * @throws DebugException
 * @throws JavaModelException
 */
private void addSeeds(TypeConstraint typeConstraint) throws DebugException, JavaModelException {
    for (IJavaVariable l : stack.getLocalVariables())
        candidates.addWeighted(expressionMaker.makeVar(l.getName(), (IJavaValue)l.getValue(), EclipseUtils.getTypeOfVariableAndLoadIfNeeded(l, stack), thread));
    if (!stack.isStatic())
        objects.addWeighted(expressionMaker.makeThis(stack.getThis(), thisType, thread));
    if (!(typeConstraint instanceof MethodConstraint) && !(typeConstraint instanceof FieldConstraint))  // If we have a method or field constraint, we can't have null.)
        nulls.addWeighted(expressionMaker.makeNull(thread));
    if (stack.isStatic() || stack.isConstructor())
        names.addWeighted(expressionMaker.makeStaticName(stack.getReceivingTypeName(), thisType, thread));
    for (IImportDeclaration imp : imports) {
        // TODO: Handle static imports.
        // TODO: Decomp with deterministic version?
        if (!imp.isOnDemand()) {
            String fullName = imp.getElementName();
            String shortName = EclipseUtils.getUnqualifiedName(fullName);  // Use the unqualified typename for brevity.
            if (!Flags.isStatic(imp.getFlags())) {
                IJavaReferenceType importedType = (IJavaReferenceType)EclipseUtils.getTypeAndLoadIfNeeded(fullName, stack, target, typeCache);
                if (importedType != null) {
                    if (hasPublicStaticFieldOrMethod(importedType))
                        names.addWeighted(expressionMaker.makeStaticName(shortName, importedType, thread));
                }
            }
        }
    }
}
项目:reflectify    文件:AbstractJavaModelTests.java   
protected ICompilationUnit getCompilationUnitFor(IJavaElement element) {

        if (element instanceof ICompilationUnit) {
            return (ICompilationUnit)element;
        }

        if (element instanceof IMember) {
            return ((IMember)element).getCompilationUnit();
        }

        if (element instanceof IPackageDeclaration ||
            element instanceof IImportDeclaration) {
                return (ICompilationUnit)element.getParent();
            }

        return null;

    }
项目:libraries    文件:WorkspaceDependenciesInvestigator.java   
private List<IImport> getImportedTypes(final IImportDeclaration[] importDeclarations) {
  final List<IImport> importedTypes = new ArrayList<>();
  for (final IImportDeclaration importDeclaration : importDeclarations) {
    final String importName = importDeclaration.getElementName();
    final Path importPath = create(null, importName);
    importedTypes.add(new Import(importName, importName.endsWith("*") //$NON-NLS-1$
        ? importPath.getParent()
        : importPath));
  }
  return importedTypes;
}
项目:junit-tools    文件:JDTUtils.java   
public static String getFullQualifiedName(IType type,
        String variableTypeName) throws JavaModelException {

    IImportDeclaration[] imports = null;
    List<?> importsFromBinary = null;
    ICompilationUnit cu = type.getCompilationUnit();

    if (cu != null) {
        imports = cu.getImports();
    } else {
        ASTParser parser = ASTParser.newParser(AST.JLS8);
        parser.setSource(type.getClassFile().getBuffer().getCharacters());
        CompilationUnit cuParsed = (CompilationUnit) parser.createAST(null);

        if (cuParsed != null) {
            importsFromBinary = cuParsed.imports();
        }
    }

    String fullQualifiedName = null;

    if (imports != null) {
        // from source
        fullQualifiedName = getFullQualifiedName(imports, variableTypeName);
    } else if (importsFromBinary != null) {
        // from binary
        fullQualifiedName = getFullQualifiedName(importsFromBinary,
                variableTypeName);
    }

    if (fullQualifiedName == null) {
        // if no import available, then try to find in same package
        fullQualifiedName = type.getPackageFragment().getElementName()
                + "." + variableTypeName;
    }

    return fullQualifiedName;
}
项目:junit-tools    文件:TestClassGenerator.java   
protected void createStandardStaticImports(ICompilationUnit compilationUnit) throws JavaModelException {
IJavaElement importAbove = null;
IImportDeclaration[] imports = compilationUnit.getImports();
if (imports.length > 0) {
    importAbove = imports[0];
    compilationUnit.createImport("org.junit.Assert.*", importAbove, Flags.AccStatic, null);
}
   }
项目:che    文件:JavaElementToDtoConverter.java   
private void addImport(List<ImportDeclaration> result, Set<Object> imports)
    throws JavaModelException {
  for (Object im : imports) {
    if (im instanceof IImportDeclaration) {
      IImportDeclaration dec = (IImportDeclaration) im;
      ImportDeclaration importDeclaration = DtoFactory.newDto(ImportDeclaration.class);
      importDeclaration.setFlags(dec.getFlags());
      importDeclaration.setHandleIdentifier(dec.getHandleIdentifier());
      importDeclaration.setElementName(dec.getElementName());
      result.add(importDeclaration);
    }
  }
}
项目:che    文件:ImportOrganizeTest.java   
private void assertImports(ICompilationUnit cu, String[] imports) throws Exception {
  IImportDeclaration[] desc = cu.getImports();
  assertEquals(cu.getElementName() + "-count", imports.length, desc.length);
  for (int i = 0; i < imports.length; i++) {
    assertEquals(cu.getElementName() + "-cmpentries" + i, desc[i].getElementName(), imports[i]);
  }
}