public void extractClassFile(IClassFile classFile) {
    // Verify that it's a top-level type, or a subtype of a top-level type
    //    try {
    //      IType declaring = classFile.getType();
    //      while (declaring != null) {
    //        if (declaring.isLocal() || declaring.isAnonymous()) {
    //          return;
    //        }
    //        declaring = declaring.getDeclaringType();
    //      }
    //    } catch (JavaModelException e) {
    //      logger.log(Level.SEVERE, "Error in extracting class file", e);
    //      return;
    //    }

    IJavaElement parent = classFile.getParent();
    while (true) {
      if (parent == null) {
        logger.log(Level.SEVERE, "Unable to find package for: " + classFile.getElementName());
        break;
      } else if (parent.getElementType() == IJavaElement.PACKAGE_FRAGMENT) {
        // Write the class file
        name = classFile.getElementName();
        path = parent.getElementName() + "." + name;
        fileWriter.writeClassFile(name, path);

        try {
          if (classFile.getType().isAnonymous()) {
            String fqn = classFile.getType().getFullyQualifiedName();
            String containingFqn = fqn.substring(0, fqn.lastIndexOf('$'));
            relationWriter.writeInside(
                classFile.getType().getFullyQualifiedName(), containingFqn, path);
          } else {
            relationWriter.writeInside(
                classFile.getType().getFullyQualifiedName(), parent.getElementName(), path);
            entityWriter.writePackage(parent.getElementName());
          }
        } catch (JavaModelException e) {
          logger.log(Level.SEVERE, "Error in extracting class file", e);
        }
        break;
      } else {
        logger.log(
            Level.SEVERE, classFile.getType().getFullyQualifiedName() + " should be top-level!");
        parent = parent.getParent();
      }
    }

    extractIType(classFile.getType());
    name = null;
    path = null;
  }
 /**
  * Runs the stub generation on the specified class file.
  *
  * @param file the class file
  * @param parent the parent store
  * @param monitor the progress monitor to use
  * @throws CoreException if an error occurs
  */
 @Override
 protected void run(final IClassFile file, final IFileStore parent, final IProgressMonitor monitor)
     throws CoreException {
   try {
     monitor.beginTask(getOperationLabel(), 2);
     final IType type = file.getType();
     if (type.isAnonymous() || type.isLocal() || type.isMember()) return;
     final String source = file.getSource();
     createCompilationUnit(
         parent,
         type.getElementName() + JavaModelUtil.DEFAULT_CU_SUFFIX,
         source != null ? source : "",
         monitor); //$NON-NLS-1$
   } finally {
     monitor.done();
   }
 }
 public static boolean isTopLevelOrAnonymous(IClassFile classFile) {
   if (classFile.getType() == null) {
     logger.log(Level.SEVERE, "Null type!" + classFile);
     return false;
   } else {
     IType type = classFile.getType();
     try {
       if (type.isMember() || type.isLocal()) {
         return false;
       } else {
         return true;
       }
     } catch (JavaModelException e) {
       logger.log(Level.SEVERE, "Error determining if class is top level", e);
       return true;
     }
   }
   //    return !classFile.getType().getFullyQualifiedName().contains("$");
   //    try {
   //      IType declaring = classFile.getType();
   //      boolean topLevel = true;
   //
   //      while (declaring != null) {
   //        if (declaring.isMember() || declaring.isLocal() || declaring.isAnonymous()) {
   //          topLevel = false;
   //          break;
   //        }
   //        declaring = declaring.getDeclaringType();
   //      }
   //
   //      if (topLevel) {
   //        // check if there is any $ in the fqn
   //        if (classFile.getType().getFullyQualifiedName().indexOf('$') == -1) {
   //          return true;
   //        } else {
   //          logger.log(Level.SEVERE, "isTopLevel thinks " +
   // classFile.getType().getFullyQualifiedName() + " is top-level");
   //          return true;
   //        }
   //      }
   //    } catch (JavaModelException e) {
   //      logger.log(Level.SEVERE, "Error in determining toplevel", e);
   //      return false;
   //    }
 }
Beispiel #4
0
  public IJavaElement getElementAtConsideringSibling(int position) throws JavaModelException {
    IPackageFragment fragment = (IPackageFragment) getParent();
    PackageFragmentRoot root =
        (PackageFragmentRoot) fragment.getAncestor(IJavaElement.PACKAGE_FRAGMENT_ROOT);
    SourceMapper mapper = root.getSourceMapper();
    if (mapper == null) {
      return null;
    } else {
      int index = this.name.indexOf('$');
      int prefixLength = index < 0 ? this.name.length() : index;

      IType type = null;
      int start = -1;
      int end = Integer.MAX_VALUE;
      IJavaElement[] children = fragment.getChildren();
      for (int i = 0; i < children.length; i++) {
        String childName = children[i].getElementName();

        int childIndex = childName.indexOf('$');
        int childPrefixLength = childIndex < 0 ? childName.indexOf('.') : childIndex;
        if (prefixLength == childPrefixLength
            && this.name.regionMatches(0, childName, 0, prefixLength)) {
          IClassFile classFile = (IClassFile) children[i];

          // ensure this class file's buffer is open so that source ranges are computed
          classFile.getBuffer();

          SourceRange range = mapper.getSourceRange(classFile.getType());
          if (range == SourceMapper.UNKNOWN_RANGE) continue;
          int newStart = range.getOffset();
          int newEnd = newStart + range.getLength() - 1;
          if (newStart > start && newEnd < end && newStart <= position && newEnd >= position) {
            type = classFile.getType();
            start = newStart;
            end = newEnd;
          }
        }
      }
      if (type != null) {
        return findElement(type, position, mapper);
      }
      return null;
    }
  }
  public void testPositiveSystemLibrarySourceLocation() throws Exception {
    IClasspathEntry[] cpes = get14Project().getRawClasspath();
    IClasspathEntry lib = null;
    for (int i = 0; i < cpes.length; i++) {
      if (cpes[i].getEntryKind() == IClasspathEntry.CPE_CONTAINER) {
        if (cpes[i].getPath().equals(new Path(JRE_CONTAINER_1_4_CPE_NAME))) {
          lib = cpes[i];
          break;
        }
      }
    }
    assertNotNull("Could not find JRE_CONTAINER entry", lib);

    IPackageFragmentRoot[] roots = get14Project().findPackageFragmentRoots(lib);
    Object source = null;
    for (int i = 0; i < roots.length; i++) {
      IPackageFragmentRoot root = roots[i];
      IJavaSourceLocation location = new PackageFragmentRootSourceLocation(root);
      source = location.findSourceElement("java.lang.Object");
      if (source != null) {
        break;
      }
    }

    assertTrue("Did not find source for 'Object'", source instanceof IClassFile);
    IClassFile cf = (IClassFile) source;
    assertEquals("Did not find source for 'Object'", "Object.class", cf.getElementName());

    for (int i = 0; i < roots.length; i++) {
      IPackageFragmentRoot root = roots[i];
      IJavaSourceLocation location = new PackageFragmentRootSourceLocation(root);
      source = location.findSourceElement("java.util.Vector$1");
      if (source != null) {
        break;
      }
    }
    assertTrue("Did not find source for 'Vector$1'", source instanceof IClassFile);
    cf = (IClassFile) source;
    assertEquals("Did not find source for 'Vector$1'", "Vector$1.class", cf.getElementName());
  }
 /**
  * Runs the stub generation on the specified class file.
  *
  * @param file the class file
  * @param parent the parent store
  * @param monitor the progress monitor to use
  * @throws CoreException if an error occurs
  */
 protected void run(final IClassFile file, final IFileStore parent, final IProgressMonitor monitor)
     throws CoreException {
   try {
     monitor.beginTask(RefactoringCoreMessages.StubCreationOperation_creating_type_stubs, 2);
     SubProgressMonitor subProgressMonitor = new SubProgressMonitor(monitor, 1);
     final IType type = file.getType();
     if (type.isAnonymous() || type.isLocal() || type.isMember()) return;
     String source = new StubCreator(fStubInvisible).createStub(type, subProgressMonitor);
     createCompilationUnit(
         parent, type.getElementName() + JavaModelUtil.DEFAULT_CU_SUFFIX, source, monitor);
   } finally {
     monitor.done();
   }
 }
Beispiel #7
0
 protected TypedElement createTypedElement(IJavaElement javaElement, BitSet modes) {
   String name;
   IClassFile classFile = (IClassFile) javaElement.getAncestor(IJavaElement.CLASS_FILE);
   // existing read-only class files
   if (classFile != null) {
     name = classFile.getPath().toOSString();
     if (!name.endsWith(".class")) { // $NON-NLS-1$
       name += '/' + JdtUtils.getFullBytecodeName(classFile);
     }
   } else {
     // usual eclipse - generated bytecode
     name = JdtUtils.getByteCodePath(javaElement);
   }
   String methodName = null;
   if (javaElement.getElementType() == IJavaElement.METHOD
       || javaElement.getElementType() == IJavaElement.INITIALIZER) {
     methodName = JdtUtils.getMethodSignature(javaElement);
     if (methodName != null) {
       name += ":" + methodName;
     }
   }
   return new TypedElement(name, methodName, TypedElement.TYPE_BYTECODE, javaElement, modes);
 }
  /* (non-JavaDoc)
   * Method declared in SelectionDispatchAction.
   */
  private IMember getMember(IStructuredSelection selection) {
    if (selection.size() != 1) return null;
    Object o = selection.getFirstElement();
    if (o instanceof IMember) {
      IMember member = (IMember) o;
      try {
        if (member.getNameRange() == null) return null;
      } catch (JavaModelException ex) {
        return null;
      }

      IClassFile file = member.getClassFile();
      if (file != null) {
        try {
          if (file.getSourceRange() != null) return member;
        } catch (JavaModelException e) {
          return null;
        }
      }
      return member;
    }
    return null;
  }
 public JArray<? extends JWorkspaceClass> getClasses() {
   if (classes == null) {
     try {
       IType type = jdtJavaBinaryFile.getType();
       IType[] types;
       if (JavaModelJDTUtil.elementExists(type)) {
         types = new IType[] {type};
       } else {
         types = new IType[0];
       }
       classes =
           JDTFactory.getInstance().buildArray(types, JDTFactory.getInstance().getClassBuilder());
     } catch (Exception e) {
       throw new InternalModelException(e);
     }
   }
   return classes;
 }
 /**
  * Returns the primary type of a class file.
  *
  * @param classFile the class file
  * @return returns the primary type of the class file, or <code>null</code> if is does not have
  *     one
  */
 private IType getMainType(IClassFile classFile) {
   IType type = classFile.getType();
   return type != null && type.exists() ? type : null;
 }
  public char[][][] collect() throws JavaModelException {
    if (this.type != null) {
      // Collect the paths of the cus that are in the hierarchy of the given type
      this.result = new char[1][][];
      this.resultIndex = 0;
      JavaProject javaProject = (JavaProject) this.type.getJavaProject();
      this.locator.initialize(javaProject, 0);
      try {
        if (this.type.isBinary()) {
          BinaryTypeBinding binding = this.locator.cacheBinaryType(this.type, null);
          if (binding != null) collectSuperTypeNames(binding);
        } else {
          ICompilationUnit unit = this.type.getCompilationUnit();
          SourceType sourceType = (SourceType) this.type;
          boolean isTopLevelOrMember = sourceType.getOuterMostLocalContext() == null;
          CompilationUnitDeclaration parsedUnit = buildBindings(unit, isTopLevelOrMember);
          if (parsedUnit != null) {
            TypeDeclaration typeDecl = new ASTNodeFinder(parsedUnit).findType(this.type);
            if (typeDecl != null && typeDecl.binding != null)
              collectSuperTypeNames(typeDecl.binding);
          }
        }
      } catch (AbortCompilation e) {
        // problem with classpath: report inacurrate matches
        return null;
      }
      if (this.result.length > this.resultIndex)
        System.arraycopy(
            this.result, 0, this.result = new char[this.resultIndex][][], 0, this.resultIndex);
      return this.result;
    }

    // Collect the paths of the cus that declare a type which matches declaringQualification +
    // declaringSimpleName
    String[] paths = this.getPathsOfDeclaringType();
    if (paths == null) return null;

    // Create bindings from source types and binary types and collect super type names of the type
    // declaration
    // that match the given declaring type
    Util.sort(paths); // sort by projects
    JavaProject previousProject = null;
    this.result = new char[1][][];
    this.resultIndex = 0;
    for (int i = 0, length = paths.length; i < length; i++) {
      try {
        Openable openable = this.locator.handleFactory.createOpenable(paths[i], this.locator.scope);
        if (openable == null) continue; // outside classpath

        IJavaProject project = openable.getJavaProject();
        if (!project.equals(previousProject)) {
          previousProject = (JavaProject) project;
          this.locator.initialize(previousProject, 0);
        }
        if (openable instanceof ICompilationUnit) {
          ICompilationUnit unit = (ICompilationUnit) openable;
          CompilationUnitDeclaration parsedUnit =
              buildBindings(
                  unit, true /*only toplevel and member types are visible to the focus type*/);
          if (parsedUnit != null)
            parsedUnit.traverse(new TypeDeclarationVisitor(), parsedUnit.scope);
        } else if (openable instanceof IClassFile) {
          IClassFile classFile = (IClassFile) openable;
          BinaryTypeBinding binding = this.locator.cacheBinaryType(classFile.getType(), null);
          if (matches(binding)) collectSuperTypeNames(binding);
        }
      } catch (AbortCompilation e) {
        // ignore: continue with next element
      } catch (JavaModelException e) {
        // ignore: continue with next element
      }
    }
    if (this.result.length > this.resultIndex)
      System.arraycopy(
          this.result, 0, this.result = new char[this.resultIndex][][], 0, this.resultIndex);
    return this.result;
  }