private static void checkHierarchyOfEnclosedTypes(
     IType destinationType, RefactoringStatus result, IType type) throws JavaModelException {
   IType[] enclosedTypes = getAllEnclosedTypes(type);
   for (int i = 0; i < enclosedTypes.length; i++) {
     IType enclosedType = enclosedTypes[i];
     if (destinationType.getElementName().equals(enclosedType.getElementName())) {
       String message =
           Messages.format(
               RefactoringCoreMessages.MemberCheckUtil_type_name_conflict3,
               new String[] {getQualifiedLabel(enclosedType), getQualifiedLabel(type)});
       RefactoringStatusContext context =
           JavaStatusContext.create(
               destinationType.getCompilationUnit(), destinationType.getNameRange());
       result.addError(message, context);
     }
     if (typeNameExistsInEnclosingTypeChain(destinationType, enclosedType.getElementName())) {
       String message =
           Messages.format(
               RefactoringCoreMessages.MemberCheckUtil_type_name_conflict4,
               new String[] {getQualifiedLabel(enclosedType), getQualifiedLabel(type)});
       RefactoringStatusContext context =
           JavaStatusContext.create(
               destinationType.getCompilationUnit(), destinationType.getNameRange());
       result.addError(message, context);
     }
   }
 }
 private static void checkMethodInType(
     IType destinationType, RefactoringStatus result, IMethod method) throws JavaModelException {
   IMethod[] destinationTypeMethods = destinationType.getMethods();
   IMethod found = findMethod(method, destinationTypeMethods);
   if (found != null) {
     RefactoringStatusContext context =
         JavaStatusContext.create(destinationType.getCompilationUnit(), found.getSourceRange());
     String message =
         Messages.format(
             RefactoringCoreMessages.MemberCheckUtil_signature_exists,
             new String[] {
               BasicElementLabels.getJavaElementName(method.getElementName()),
               getQualifiedLabel(destinationType)
             });
     result.addError(message, context);
   } else {
     IMethod similar = Checks.findMethod(method, destinationType);
     if (similar != null) {
       String message =
           Messages.format(
               RefactoringCoreMessages.MemberCheckUtil_same_param_count,
               new String[] {
                 BasicElementLabels.getJavaElementName(method.getElementName()),
                 getQualifiedLabel(destinationType)
               });
       RefactoringStatusContext context =
           JavaStatusContext.create(
               destinationType.getCompilationUnit(), similar.getSourceRange());
       result.addWarning(message, context);
     }
   }
 }
Exemple #3
0
 public static void visitTypeAst(IType type, ASTVisitor visitor) {
   if (type != null && type.getCompilationUnit() != null) {
     ASTParser parser = ASTParser.newParser(AST.JLS3);
     parser.setSource(type.getCompilationUnit());
     parser.setResolveBindings(true);
     ASTNode node = parser.createAST(new NullProgressMonitor());
     node.accept(visitor);
   }
 }
 public UpdateRetentionAnnotationValueMarkerResolution(IType type) {
   super(type.getCompilationUnit());
   this.type = type;
   label =
       NLS.bind(
           JaxrsQuickFixMessages.UPDATE_RETENTION_ANNOTATION_VALUE_MARKER_RESOLUTION_TITLE,
           type.getElementName());
   init();
 }
 ////////////////////////////////////////////////////////////////////////////
 //
 // Java source
 //
 ////////////////////////////////////////////////////////////////////////////
 @Override
 protected String getJavaSourceToAssert() {
   try {
     IType type = m_javaProject.findType("test.client.Test");
     return type.getCompilationUnit().getSource();
   } catch (Throwable e) {
     throw ReflectionUtils.propagate(e);
   }
 }
 private boolean canEnable(IStructuredSelection selection) throws JavaModelException {
   if ((selection.size() == 1) && (selection.getFirstElement() instanceof IType)) {
     final IType type = (IType) selection.getFirstElement();
     return type.getCompilationUnit() != null && !type.isInterface();
   }
   if ((selection.size() == 1) && (selection.getFirstElement() instanceof ICompilationUnit))
     return true;
   return false;
 }
  public void testExtractInterfaceFromInterface2() throws Exception {
    String className = "A";
    String extendingInterfaceName = "I1";
    String newInterfaceName = "B";

    IType clas =
        getType(createCUfromTestFile(getPackageP(), getTopLevelTypeName(className)), className);
    ICompilationUnit cu = clas.getCompilationUnit();
    IPackageFragment pack = (IPackageFragment) cu.getParent();

    getType(
        createCUfromTestFile(getPackageP(), getTopLevelTypeName(extendingInterfaceName)),
        extendingInterfaceName);

    IPackageFragmentRoot root = RefactoringTestSetup.getDefaultSourceFolder();
    assertNotNull(root);
    IPackageFragment p2 = root.createPackageFragment("p2", true, null);
    getType(createCUfromTestFile(p2, getTopLevelTypeName("I2")), "I2");

    ExtractInterfaceProcessor processor =
        new ExtractInterfaceProcessor(
            clas, JavaPreferencesSettings.getCodeGenerationSettings(clas.getJavaProject()));
    Refactoring ref = new ProcessorBasedRefactoring(processor);

    processor.setTypeName(newInterfaceName);
    assertEquals(
        "interface name should be accepted",
        RefactoringStatus.OK,
        processor.checkTypeName(newInterfaceName).getSeverity());

    IMember[] extractableMembers = processor.getExtractableMembers();
    final IMember[] members = new IMember[extractableMembers.length - 1];
    List<IMember> list = new ArrayList<>();
    for (IMember iMember : extractableMembers) {
      if (!(iMember instanceof IField)) {
        list.add(iMember);
      }
    }
    processor.setExtractedMembers(list.toArray(members));
    processor.setReplace(true);
    processor.setAnnotations(false);
    RefactoringStatus performRefactoring = performRefactoring(ref);
    assertEquals("was supposed to pass", null, performRefactoring);
    assertEqualLines(
        "incorrect changes in " + className,
        getFileContents(getOutputTestFileName(className)),
        cu.getSource());

    ICompilationUnit interfaceCu = pack.getCompilationUnit(newInterfaceName + ".java");
    assertEqualLines(
        "incorrect interface created",
        getFileContents(getOutputTestFileName(newInterfaceName)),
        interfaceCu.getSource());
  }
  private void generateCode(
      Shell parentShell, IType objectClass, U data, LinkedHashSet<Method<T, U>> methods)
      throws Exception {
    IJavaElement currentPosition = data.getElementPosition();
    for (Method<T, U> method : methods) {
      MethodContent<T, U> methodContent = method.getMethodContent();
      T methodSkeleton = method.getMethodSkeleton();
      String methodContentString = methodContent.getMethodContent(objectClass, data);
      String source = methodSkeleton.getMethod(objectClass, data, methodContentString);

      for (String libraryToImport : methodSkeleton.getLibrariesToImport()) {
        objectClass.getCompilationUnit().createImport(libraryToImport, null, null);
      }
      for (String libraryToImport : methodContent.getLibrariesToImport(data)) {
        objectClass.getCompilationUnit().createImport(libraryToImport, null, null);
      }
      String formattedContent = format(parentShell, objectClass, source);
      currentPosition = objectClass.createMethod(formattedContent, currentPosition, true, null);
    }
    javaUiCodeAppender.revealInEditor(objectClass, currentPosition);
  }
  public static List<IJavaCompletionProposal> createProposalsForProblemOnSyncType(
      ASTNode problemNode, String extraAsyncMethodBindingKey) {
    TypeDeclaration syncTypeDecl =
        (TypeDeclaration) ASTResolving.findAncestor(problemNode, ASTNode.TYPE_DECLARATION);
    assert (syncTypeDecl != null);

    IType asyncType = RemoteServiceUtilities.findAsyncType(syncTypeDecl);
    if (asyncType == null) {
      return null;
    }

    MethodDeclaration extraAsyncMethodDecl =
        JavaASTUtils.findMethodDeclaration(
            asyncType.getCompilationUnit(), extraAsyncMethodBindingKey);
    if (extraAsyncMethodDecl == null) {
      return null;
    }

    return Collections.<IJavaCompletionProposal>singletonList(
        new DeleteMethodProposal(asyncType.getCompilationUnit(), extraAsyncMethodDecl));
  }
Exemple #10
0
 private static void checkTypeInType(IType destinationType, RefactoringStatus result, IType type)
     throws JavaModelException {
   String typeName = type.getElementName();
   IType destinationTypeType = destinationType.getType(typeName);
   if (destinationTypeType.exists()) {
     String message =
         Messages.format(
             RefactoringCoreMessages.MemberCheckUtil_type_name_conflict0,
             new String[] {
               BasicElementLabels.getJavaElementName(typeName), getQualifiedLabel(destinationType)
             });
     RefactoringStatusContext context =
         JavaStatusContext.create(
             destinationType.getCompilationUnit(), destinationTypeType.getNameRange());
     result.addError(message, context);
   } else {
     // need to check the hierarchy of enclosing and enclosed types
     if (destinationType.getElementName().equals(typeName)) {
       String message =
           Messages.format(
               RefactoringCoreMessages.MemberCheckUtil_type_name_conflict1,
               getQualifiedLabel(type));
       RefactoringStatusContext context =
           JavaStatusContext.create(
               destinationType.getCompilationUnit(), destinationType.getNameRange());
       result.addError(message, context);
     }
     if (typeNameExistsInEnclosingTypeChain(destinationType, typeName)) {
       String message =
           Messages.format(
               RefactoringCoreMessages.MemberCheckUtil_type_name_conflict2,
               getQualifiedLabel(type));
       RefactoringStatusContext context =
           JavaStatusContext.create(
               destinationType.getCompilationUnit(), destinationType.getNameRange());
       result.addError(message, context);
     }
     checkHierarchyOfEnclosedTypes(destinationType, result, type);
   }
 }
 private IType getSelectedType(IStructuredSelection selection) throws JavaModelException {
   final Object[] elements = selection.toArray();
   if (elements.length == 1 && (elements[0] instanceof IType)) {
     final IType type = (IType) elements[0];
     if (type.getCompilationUnit() != null && !type.isInterface()) {
       return type;
     }
   } else if (elements[0] instanceof ICompilationUnit) {
     final IType type = ((ICompilationUnit) elements[0]).findPrimaryType();
     if (type != null && !type.isInterface()) return type;
   }
   return null;
 }
 private static String createTypeQuery(final Object draggedElement) {
   final IType type = (IType) draggedElement;
   final ICompilationUnit cU = type.getCompilationUnit();
   final IClassFile cF = type.getClassFile();
   if (cU != null) {
     final String packagename = Resolver.resolveFullyQualifiedPackageName(cU);
     final String classname = Resolver.resolveClassName(type);
     return String.format("%s('%s','%s')", CLASS_WITH_MEMBERS, packagename, classname);
   } else {
     final String packagename = Resolver.resolveFullyQualifiedPackageName(cF);
     final String classname = Resolver.resolveClassName(type);
     return String.format("%s('%s','%s')", CLASS_WITH_MEMBERS, packagename, classname);
   }
 }
Exemple #13
0
 private static void checkFieldInType(
     IType destinationType, RefactoringStatus result, IField field) throws JavaModelException {
   IField destinationTypeField = destinationType.getField(field.getElementName());
   if (!destinationTypeField.exists()) return;
   String message =
       Messages.format(
           RefactoringCoreMessages.MemberCheckUtil_field_exists,
           new String[] {
             BasicElementLabels.getJavaElementName(field.getElementName()),
             getQualifiedLabel(destinationType)
           });
   RefactoringStatusContext context =
       JavaStatusContext.create(
           destinationType.getCompilationUnit(), destinationTypeField.getSourceRange());
   result.addError(message, context);
 }
Exemple #14
0
 public static boolean isTypeGroovyElement(IType type) {
   // TODO CD verify following check with Groovy Eclipse
   ICompilationUnit cu = type.getCompilationUnit();
   if (cu != null && cu.getResource() != null) {
     return cu.getResource().getName().endsWith(GROOVY_FILE_EXTENSION);
   } else if (cu != null) {
     try {
       IResource resource = cu.getUnderlyingResource();
       if (resource != null) {
         return resource.getName().endsWith(GROOVY_FILE_EXTENSION);
       }
     } catch (JavaModelException e) {
       // ignore
     }
   }
   return false;
 }
  @Override
  public RefactoringStatus checkInitialConditions(IProgressMonitor pm)
      throws CoreException, OperationCanceledException {

    RefactoringStatus result = new RefactoringStatus();
    result.merge(Checks.checkAvailability(targetClass));

    if (result.hasFatalError()) return result;

    fRoot = new RefactoringASTParser(AST.JLS3).parse(targetClass.getCompilationUnit(), true, pm);
    ISourceRange sourceRange = targetClass.getNameRange();

    ASTNode node = NodeFinder.perform(fRoot, sourceRange.getOffset(), sourceRange.getLength());
    if (node == null) {
      return mappingErrorFound(result, node);
    } else {
      targetClassDeclaration = ASTNodeSearchUtil.getTypeDeclarationNode(targetClass, fRoot);
    }
    fRewriter = ASTRewrite.create(fRoot.getAST());
    return result;
  }
  /** @see IJavaElementRequestor */
  public void acceptType(IType type) {
    try {
      if (this.unitToSkip != null && this.unitToSkip.equals(type.getCompilationUnit())) {
        return;
      }
      char[] packageName = type.getPackageFragment().getElementName().toCharArray();
      boolean isBinary = type instanceof BinaryType;

      // determine associated access restriction
      AccessRestriction accessRestriction = null;

      if (this.checkAccessRestrictions
          && (isBinary || !type.getJavaProject().equals(this.project))) {
        PackageFragmentRoot root =
            (PackageFragmentRoot) type.getAncestor(IJavaElement.PACKAGE_FRAGMENT_ROOT);
        ClasspathEntry entry = (ClasspathEntry) this.nameLookup.rootToResolvedEntries.get(root);
        if (entry != null) { // reverse map always contains resolved CP entry
          AccessRuleSet accessRuleSet = entry.getAccessRuleSet();
          if (accessRuleSet != null) {
            // TODO (philippe) improve char[] <-> String conversions to avoid performing them on the
            // fly
            char[][] packageChars = CharOperation.splitOn('.', packageName);
            char[] fileWithoutExtension = type.getElementName().toCharArray();
            accessRestriction =
                accessRuleSet.getViolatedRestriction(
                    CharOperation.concatWith(packageChars, fileWithoutExtension, '/'));
          }
        }
      }
      this.requestor.acceptType(
          packageName,
          type.getElementName().toCharArray(),
          null,
          type.getFlags(),
          accessRestriction);
    } catch (JavaModelException jme) {
      // ignore
    }
  }
 /* test overloading of private base method */
 public void testCheckOverloading9() throws Exception {
   // focus type -> C
   ICompilationUnit cu = _c.getCompilationUnit();
   int[] selection = getSelection(cu.getSource());
   _refactoring = new ExtractMethodRefactoring(cu, selection[0], selection[1]);
   _refactoring.setMethodName("n");
   _refactoring.setVisibility(Modifier.PRIVATE);
   _refactoring.checkInitialConditions(new NullProgressMonitor());
   IMethod[] inheritedMethods = RefactoringUtil.getInheritedMethods(_c, true, true, false, null);
   RefactoringStatus expected =
       RefactoringUtil.addOverloadingWarning(new ExtractMethodOverloadingMsgCreator());
   RefactoringStatus actual =
       RefactoringUtil.checkOverloading(
           inheritedMethods,
           _refactoring.getMethodName(),
           fetchNewParameterTypes(),
           new ExtractMethodOverloadingMsgCreator());
   assertEquals(expected.getSeverity(), actual.getSeverity());
   assertNotNull(
       expected.getEntryMatchingCode(Corext.getPluginId(), OTRefactoringStatusCodes.OVERLOADING));
   assertNotNull(
       actual.getEntryMatchingCode(Corext.getPluginId(), OTRefactoringStatusCodes.OVERLOADING));
 }
Exemple #18
0
 /**
  * Creates a problem for a specific reference in the workspace
  *
  * @param reference reference
  * @param associated java project (with reference source location)
  * @return problem or <code>null</code> if none
  * @exception CoreException if something goes wrong
  */
 protected IApiProblem createProblem(IReference reference, IJavaProject javaProject) {
   IProject project = javaProject.getProject();
   if (ApiPlugin.getDefault().getSeverityLevel(getSeverityKey(), project)
       == ApiPlugin.SEVERITY_IGNORE) {
     return null;
   }
   try {
     String lookupName = getTypeName(reference.getMember()).replace('$', '.');
     IType type = javaProject.findType(lookupName, new NullProgressMonitor());
     if (type == null) {
       return null;
     }
     ICompilationUnit compilationUnit = type.getCompilationUnit();
     if (compilationUnit == null) {
       return null;
     }
     IResource resource = Util.getResource(project, type);
     if (resource == null) {
       return null;
     }
     int charStart = -1;
     int charEnd = -1;
     int lineNumber = reference.getLineNumber();
     IJavaElement element = compilationUnit;
     if (!Util.isManifest(resource.getProjectRelativePath()) && !type.isBinary()) {
       IDocument document = Util.getDocument(compilationUnit);
       // retrieve line number, char start and char end
       if (lineNumber > 0) {
         lineNumber--;
       }
       // get the source range for the problem
       try {
         Position pos = getSourceRange(type, document, reference);
         if (pos != null) {
           charStart = pos.getOffset();
           if (charStart != -1) {
             charEnd = charStart + pos.getLength();
             lineNumber = document.getLineOfOffset(charStart);
           }
         }
       } catch (CoreException e) {
         ApiPlugin.log(e);
         return null;
       } catch (BadLocationException e) {
         ApiPlugin.log(e);
         return null;
       }
       if (charStart > -1) {
         element = compilationUnit.getElementAt(charStart);
       }
     }
     return ApiProblemFactory.newApiUsageProblem(
         resource.getProjectRelativePath().toPortableString(),
         type.getFullyQualifiedName(),
         getMessageArgs(reference),
         new String[] {
           IApiMarkerConstants.MARKER_ATTR_HANDLE_ID, IApiMarkerConstants.API_MARKER_ATTR_ID
         },
         new Object[] {
           (element == null
               ? compilationUnit.getHandleIdentifier()
               : element.getHandleIdentifier()),
           new Integer(IApiMarkerConstants.API_USAGE_MARKER_ID)
         },
         lineNumber,
         charStart,
         charEnd,
         getElementType(reference),
         getProblemKind(),
         getProblemFlags(reference));
   } catch (CoreException e) {
     ApiPlugin.log(e);
   }
   return null;
 }
  /** Configure this type hierarchy based on the given potential subtypes. */
  private void buildFromPotentialSubtypes(
      String[] allPotentialSubTypes, HashSet localTypes, IProgressMonitor monitor) {
    IType focusType = getType();

    // substitute compilation units with working copies
    HashMap wcPaths = new HashMap(); // a map from path to working copies
    int wcLength;
    org.eclipse.jdt.core.ICompilationUnit[] workingCopies = this.hierarchy.workingCopies;
    if (workingCopies != null && (wcLength = workingCopies.length) > 0) {
      String[] newPaths = new String[wcLength];
      for (int i = 0; i < wcLength; i++) {
        org.eclipse.jdt.core.ICompilationUnit workingCopy = workingCopies[i];
        String path = workingCopy.getPath().toString();
        wcPaths.put(path, workingCopy);
        newPaths[i] = path;
      }
      int potentialSubtypesLength = allPotentialSubTypes.length;
      System.arraycopy(
          allPotentialSubTypes,
          0,
          allPotentialSubTypes = new String[potentialSubtypesLength + wcLength],
          0,
          potentialSubtypesLength);
      System.arraycopy(newPaths, 0, allPotentialSubTypes, potentialSubtypesLength, wcLength);
    }

    int length = allPotentialSubTypes.length;

    // inject the compilation unit of the focus type (so that types in
    // this cu have special visibility permission (this is also usefull
    // when the cu is a working copy)
    Openable focusCU = (Openable) focusType.getCompilationUnit();
    String focusPath = null;
    if (focusCU != null) {
      focusPath = focusCU.getPath().toString();
      if (length > 0) {
        System.arraycopy(
            allPotentialSubTypes, 0, allPotentialSubTypes = new String[length + 1], 0, length);
        allPotentialSubTypes[length] = focusPath;
      } else {
        allPotentialSubTypes = new String[] {focusPath};
      }
      length++;
    }

    /*
     * Sort in alphabetical order so that potential subtypes are grouped per project
     */
    Arrays.sort(allPotentialSubTypes);

    ArrayList potentialSubtypes = new ArrayList();
    try {
      // create element infos for subtypes
      HandleFactory factory = new HandleFactory();
      IJavaProject currentProject = null;
      if (monitor != null)
        monitor.beginTask(
            "", length * 2 /* 1 for build binding, 1 for connect hierarchy*/); // $NON-NLS-1$
      for (int i = 0; i < length; i++) {
        try {
          String resourcePath = allPotentialSubTypes[i];

          // skip duplicate paths (e.g. if focus path was injected when it was already a potential
          // subtype)
          if (i > 0 && resourcePath.equals(allPotentialSubTypes[i - 1])) continue;

          Openable handle;
          org.eclipse.jdt.core.ICompilationUnit workingCopy =
              (org.eclipse.jdt.core.ICompilationUnit) wcPaths.get(resourcePath);
          if (workingCopy != null) {
            handle = (Openable) workingCopy;
          } else {
            handle =
                resourcePath.equals(focusPath)
                    ? focusCU
                    : factory.createOpenable(resourcePath, this.scope);
            if (handle == null) continue; // match is outside classpath
          }

          IJavaProject project = handle.getJavaProject();
          if (currentProject == null) {
            currentProject = project;
            potentialSubtypes = new ArrayList(5);
          } else if (!currentProject.equals(project)) {
            // build current project
            buildForProject(
                (JavaProject) currentProject,
                potentialSubtypes,
                workingCopies,
                localTypes,
                monitor);
            currentProject = project;
            potentialSubtypes = new ArrayList(5);
          }

          potentialSubtypes.add(handle);
        } catch (JavaModelException e) {
          continue;
        }
      }

      // build last project
      try {
        if (currentProject == null) {
          // case of no potential subtypes
          currentProject = focusType.getJavaProject();
          if (focusType.isBinary()) {
            potentialSubtypes.add(focusType.getClassFile());
          } else {
            potentialSubtypes.add(focusType.getCompilationUnit());
          }
        }
        buildForProject(
            (JavaProject) currentProject, potentialSubtypes, workingCopies, localTypes, monitor);
      } catch (JavaModelException e) {
        // ignore
      }

      // Compute hierarchy of focus type if not already done (case of a type with potential subtypes
      // that are not real subtypes)
      if (!this.hierarchy.contains(focusType)) {
        try {
          currentProject = focusType.getJavaProject();
          potentialSubtypes = new ArrayList();
          if (focusType.isBinary()) {
            potentialSubtypes.add(focusType.getClassFile());
          } else {
            potentialSubtypes.add(focusType.getCompilationUnit());
          }
          buildForProject(
              (JavaProject) currentProject, potentialSubtypes, workingCopies, localTypes, monitor);
        } catch (JavaModelException e) {
          // ignore
        }
      }

      // Add focus if not already in (case of a type with no explicit super type)
      if (!this.hierarchy.contains(focusType)) {
        this.hierarchy.addRootClass(focusType);
      }
    } finally {
      if (monitor != null) monitor.done();
    }
  }
  /**
   * @param insideTagBody
   * @param tagBody
   * @param templateTag
   * @param contextMap
   * @param placeHolders
   * @param spacesBeforeCursor
   * @param overrideMethods
   * @param exist
   * @param overWrite
   * @param type
   * @throws JavaModelException
   * @throws Exception
   */
  public void createClassFromTag(
      final String className,
      final Object packge,
      final Object project,
      String insideTagBody,
      final Map<String, Object> contextMap,
      final Map<String, Object> placeHolders,
      final ICompilationUnit compUnit,
      final String typeToCreate,
      final String spacesBeforeCursor,
      boolean overrideMethods,
      final boolean exist,
      final boolean overWrite)
      throws JavaModelException, Exception {
    final VersionControlPreferences versionControlPreferences =
        VersionControlPreferences.getInstance();
    if (typeToCreate.equals(ACTION_ENTITY.Innerclass.getValue())) {
      compUnit.becomeWorkingCopy(null);
      final File newFileObj = new File(compUnit.getResource().getLocationURI().toString());
      /*final FastCodeCheckinCache checkinCache = FastCodeCheckinCache.getInstance();
      checkinCache.getFilesToCheckIn().add(new FastCodeFileForCheckin(INITIATED, newFileObj.getAbsolutePath()));*/

      try {
        // addOrUpdateFileStatusInCache(newFileObj);
        final IType innerClassType = SourceUtil.createInnerClass(insideTagBody, compUnit);
        /*final boolean prjShared = !isEmpty(compUnit.getResource().getProject().getPersistentProperties());
        final boolean prjConfigured = !isEmpty(isPrjConfigured(compUnit.getResource().getProject().getName()));*/
        if ((Boolean) placeHolders.get(AUTO_CHECKIN)) {
          if (proceedWithAutoCheckin(newFileObj, compUnit.getResource().getProject())) {
            final IFile file = (IFile) innerClassType.getResource(); // .getLocationURI());
            List<FastCodeEntityHolder> chngsForType =
                ((Map<Object, List<FastCodeEntityHolder>>) contextMap.get(FC_OBJ_CREATED))
                    .get(file);
            if (chngsForType == null) {
              chngsForType = new ArrayList<FastCodeEntityHolder>();
              final List<Object> innerClassList = new ArrayList<Object>();
              innerClassList.add(new FastCodeType(innerClassType));
              chngsForType.add(new FastCodeEntityHolder(PLACEHOLDER_INNERCLASSES, innerClassList));
            } else {
              boolean isNew = true;
              Object fastCodeFieldList = null;
              for (final FastCodeEntityHolder fcEntityHolder : chngsForType) {
                if (fcEntityHolder.getEntityName().equals(PLACEHOLDER_INNERCLASSES)) {
                  fastCodeFieldList = fcEntityHolder.getFastCodeEntity();
                  isNew = false;
                  break;
                }
              }

              if (isNew) {
                fastCodeFieldList = new ArrayList<Object>();
                ((List<Object>) fastCodeFieldList).add(innerClassType);
                chngsForType.add(
                    new FastCodeEntityHolder(PLACEHOLDER_INNERCLASSES, fastCodeFieldList));
              } else {
                ((List<Object>) fastCodeFieldList).add(innerClassType);
              }

              /*Object innerClassList = chngsForType.get("innerClasses");
              if (innerClassList == null) {
              	innerClassList = new ArrayList<Object>();
              }
              ((List<Object>) innerClassList).add(new FastCodeType(innerClassType));
              chngsForType.put("innerClasses", innerClassList);*/
            }
            ((Map<Object, List<FastCodeEntityHolder>>) contextMap.get(FC_OBJ_CREATED))
                .put(file, chngsForType);
          }
        }
      } catch (final FastCodeRepositoryException ex) {
        ex.printStackTrace();
      }
      compUnit.commitWorkingCopy(false, null);
      compUnit.discardWorkingCopy();
      return;
    }

    final IJavaProject prj =
        project instanceof String ? getJavaProject((String) project) : (IJavaProject) project;
    /*IJavaProject prj = getJavaProject(project);// getJavaProject(attributes.get(PLACEHOLDER_PROJECT));
    if (prj == null) {
    	prj = getJavaProject(placeHolders.get(PLACEHOLDER_PROJECT) instanceof FastCodeProject ? ((FastCodeProject) placeHolders
    			.get(PLACEHOLDER_PROJECT)).getName() : (String) placeHolders.get(PLACEHOLDER_PROJECT));
    }

    if (prj == null) {
    	prj = this.javaProject = this.javaProject == null ? getWorkingJavaProjectFromUser() : this.javaProject;//did for j2ee base
    }*/
    if (prj == null) {
      throw new Exception("Can not continue without java  project.");
    }
    final String srcPath =
        typeToCreate.equals(ACTION_ENTITY.Test.getValue())
            ? getDefaultPathFromProject(prj, typeToCreate, EMPTY_STR)
            : getDefaultPathFromProject(prj, "source", EMPTY_STR);
    IPackageFragment pkgFrgmt = null;
    final TemplateTagsProcessor templateTagsProcessor = new TemplateTagsProcessor();
    if (packge instanceof String && !isEmpty((String) packge)
        || packge instanceof IPackageFragment) {
      pkgFrgmt =
          packge instanceof String
              ? templateTagsProcessor.getPackageFragment(
                  prj,
                  srcPath,
                  (String) packge,
                  typeToCreate.equals(ACTION_ENTITY.Test.getValue()) ? typeToCreate : "source")
              : (IPackageFragment) packge;
    }
    if (pkgFrgmt == null) {
      /*final boolean prjShared = !isEmpty(prj.getProject().getPersistentProperties());
      final boolean prjConfigured = !isEmpty(isPrjConfigured(prj.getProject().getName()));*/
      File file = null;
      if ((Boolean) placeHolders.get(AUTO_CHECKIN)) {
        if (proceedWithAutoCheckin(file, prj.getProject())) {
          final String prjURI = prj.getResource().getLocationURI().toString();
          final String path = prjURI.substring(prjURI.indexOf(COLON) + 1);
          final String newPackURL =
              path + srcPath + FILE_SEPARATOR + ((String) packge).replace(DOT, FILE_SEPARATOR);
          file = new File(newPackURL);
          // final FastCodeCheckinCache checkinCache = FastCodeCheckinCache.getInstance();
          addOrUpdateFileStatusInCache(file);
          // checkinCache.getFilesToCheckIn().add(new FastCodeFileForCheckin(INITIATED,
          // file.getAbsolutePath()));
        }
      }
      pkgFrgmt =
          templateTagsProcessor.createPackage(
              prj, (String) packge, typeToCreate, contextMap); // createPackage(prj,
      // attributes.get(PLACEHOLDER_PACKAGE));
      if ((Boolean) placeHolders.get(AUTO_CHECKIN)) {
        if (proceedWithAutoCheckin(null, prj.getProject())) {
          final IFile ifile = getIFileFromFile(file);
          List<FastCodeEntityHolder> chngsForType =
              ((Map<Object, List<FastCodeEntityHolder>>) contextMap.get(FC_OBJ_CREATED)).get(ifile);
          if (chngsForType == null) {
            chngsForType = new ArrayList<FastCodeEntityHolder>();
            chngsForType.add(
                new FastCodeEntityHolder(PLACEHOLDER_PACKAGE, new FastCodePackage(pkgFrgmt)));
          }
          ((Map<Object, List<FastCodeEntityHolder>>) contextMap.get(FC_OBJ_CREATED))
              .put(ifile, chngsForType);
        }
      }
    }

    boolean createFileAlone = true;
    if ((Boolean) placeHolders.get(AUTO_CHECKIN)) {
      String path;
      try {
        final boolean prjShared =
            !isEmpty(pkgFrgmt.getResource().getProject().getPersistentProperties());
        final boolean prjConfigured =
            !isEmpty(isPrjConfigured(pkgFrgmt.getResource().getProject().getName()));
        createFileAlone = !(versionControlPreferences.isEnable() && prjShared && prjConfigured);

        final String prjURI = pkgFrgmt.getResource().getLocationURI().toString();
        path = prjURI.substring(prjURI.indexOf(COLON) + 1);
        final File newFileObj = new File(path + FORWARD_SLASH + className + DOT + JAVA_EXTENSION);
        if (versionControlPreferences.isEnable() && prjShared && prjConfigured) {
          final RepositoryService repositoryService = getRepositoryServiceClass();
          try {
            if (repositoryService.isFileInRepository(
                newFileObj)) { // && !MessageDialog.openQuestion(new Shell(), "File present in
                               // repository", "File already present in repository. Click yes to
                               // overwrite")) {
              /*MessageDialog.openWarning(new Shell(), "File present in repository", className + " is already present in repository. Please synchronise and try again.");
              return;*/
              createFileAlone =
                  MessageDialog.openQuestion(
                      new Shell(),
                      "File present in repository",
                      "File "
                          + newFileObj.getName()
                          + " already present in repository. Click yes to just create the file, No to return without any action.");
              if (!createFileAlone) {
                return;
              }
            }
          } catch (final Throwable th) {
            th.printStackTrace();
            createFileAlone = true;
          }
        }
        final FastCodeCheckinCache checkinCache = FastCodeCheckinCache.getInstance();
        checkinCache
            .getFilesToCheckIn()
            .add(new FastCodeFileForCheckin(INITIATED, newFileObj.getAbsolutePath()));

      } catch (final FastCodeRepositoryException ex) {
        ex.printStackTrace();
      }
    }

    /*if (parseClassName(insideTagBody) == null) {
    	insideTagBody = MODIFIER_PUBLIC + SPACE + typeToCreate + SPACE + className + SPACE + LEFT_CURL + NEWLINE + insideTagBody
    			+ NEWLINE + RIGHT_CURL;
    }*/

    final Object codeFormatter = createCodeFormatter(prj.getProject());
    if (!isEmpty(insideTagBody)) {
      insideTagBody = formatCode(insideTagBody.trim(), codeFormatter);
    }
    ICompilationUnit compilationUnit = null;
    if (exist) {
      if (overWrite) {
        final IType type = prj.findType(pkgFrgmt.getElementName() + DOT + className.trim());
        if (type.getCompilationUnit().hasUnsavedChanges()) {
          type.getCompilationUnit().save(new NullProgressMonitor(), true);
        }
        // type.getCompilationUnit().delete(true, new NullProgressMonitor());
        insideTagBody = buildClass(insideTagBody, pkgFrgmt, prj, className);

        // type.getCompilationUnit().getBuffer().setContents(insideTagBody);
        final ReplaceEdit replaceEdit =
            new ReplaceEdit(0, type.getCompilationUnit().getSource().length(), insideTagBody);
        type.getCompilationUnit().applyTextEdit(replaceEdit, new NullProgressMonitor());
        compilationUnit = type.getCompilationUnit();
        compilationUnit.becomeWorkingCopy(null);
        compilationUnit.commitWorkingCopy(false, null);
        compilationUnit.discardWorkingCopy();

        // refreshProject(prj.getElementName());
      } else {
        return;
      }
    } else {
      compilationUnit = SourceUtil.createClass(insideTagBody, pkgFrgmt, prj, className);
    }

    if (compilationUnit == null) {
      return;
    }
    if (!typeToCreate.equals(ACTION_ENTITY.Interface.getValue())) {
      if (compilationUnit.findPrimaryType().getSuperclassName() != null) {
        final IType superClassType =
            prj.findType(
                getFQNameFromFieldTypeName(
                    compilationUnit.findPrimaryType().getSuperclassName(), compilationUnit));
        if (superClassType != null && superClassType.exists()) {
          if (Flags.isAbstract(
              superClassType
                  .getFlags()) /*Modifier.isAbstract(Class.forName(superClassType.getFullyQualifiedName()).getModifiers())*/) {
            overrideMethods = true;
          }
        }
      }
      if (overrideMethods) {
        final String superInterfaces[] = compilationUnit.findPrimaryType().getSuperInterfaceNames();
        if (superInterfaces != null) {
          for (final String superInertafce : superInterfaces) {
            final IType superIntType =
                prj.findType(getFQNameFromFieldTypeName(superInertafce, compilationUnit));
            final FastCodeContext fastCodeContext = new FastCodeContext(superIntType);
            final CreateSimilarDescriptorClass createSimilarDescriptorClass =
                new CreateSimilarDescriptorClass.Builder().withClassType(CLASS_TYPE.CLASS).build();
            implementInterfaceMethods(
                superIntType,
                fastCodeContext,
                compilationUnit.findPrimaryType(),
                null,
                createSimilarDescriptorClass);
            final IType[] superInterfaceType = getSuperInterfacesType(superIntType);
            if (superInterfaceType != null) {
              for (final IType type : superInterfaceType) {
                if (type == null || !type.exists()) {
                  continue;
                }
                final FastCodeContext context = new FastCodeContext(type);
                implementInterfaceMethods(
                    type,
                    context,
                    compilationUnit.findPrimaryType(),
                    null,
                    createSimilarDescriptorClass);
              }
            }
          }
        }
        overrideBaseClassMethods(compilationUnit);
      }
    }
    /*
     * final IType newType = compilationUnit.findPrimaryType(); String
     * superClassName = newType.getSuperclassName(); if
     * (!isEmpty(superClassName)) { final IType superClassType =
     * prj.findType(getFQNameFromFieldTypeName(newType.getSuperclassName(),
     * newType.getCompilationUnit())); final FastCodeContext fastCodeContext
     * = new FastCodeContext(superClassType); final
     * CreateSimilarDescriptorClass createSimilarDescriptorClass = new
     * CreateSimilarDescriptorClass.Builder().withClassType(
     * CLASS_TYPE.CLASS).build(); for (final IMethod method :
     * superClassType.getMethods()) { if (method.isConstructor()) {
     * overrideConstructor(method, newType); final MethodBuilder
     * methodBuilder = new SimilarMethodBuilder(fastCodeContext);
     * methodBuilder.buildMethod(method, newType, null,
     * createSimilarDescriptorClass); } } }
     */
    contextMap.put(
        "Class_" + compilationUnit.getElementName(),
        new FastCodeObject(compilationUnit, ACTION_ENTITY.Class.getValue()));

    if (!createFileAlone) {
      final IFile fileObj =
          (IFile) compilationUnit.findPrimaryType().getResource(); // .getLocationURI());
      List<FastCodeEntityHolder> chngsForType =
          ((Map<Object, List<FastCodeEntityHolder>>) contextMap.get(FC_OBJ_CREATED)).get(fileObj);
      if (chngsForType == null) {
        chngsForType = new ArrayList<FastCodeEntityHolder>();
        chngsForType.add(
            new FastCodeEntityHolder(
                PLACEHOLDER_CLASS, new FastCodeType(compilationUnit.findPrimaryType())));
      }
      ((Map<Object, List<FastCodeEntityHolder>>) contextMap.get(FC_OBJ_CREATED))
          .put(fileObj, chngsForType);
    }
    /*final Map<String, Object> listofChange = ((Map<Object, Map<String, Object>>) contextMap.get("changes_for_File")).get(file);
    if (chngsForType == null) {
    	chngsForType = new HashMap<String, Object>();
    	chngsForType.put("class", CREATE_CLASS); //fastCodeCache.getCommentKey().get(fastCodeCache.getCommentKey().indexOf("create.class.field"))
    }
    ((Map<Object, Map<String, Object>>) contextMap.get("changes_for_File")).put(file, listofChange);*/
  }
  private void buildForProject(
      JavaProject project,
      ArrayList potentialSubtypes,
      org.eclipse.jdt.core.ICompilationUnit[] workingCopies,
      HashSet localTypes,
      IProgressMonitor monitor)
      throws JavaModelException {
    // resolve
    int openablesLength = potentialSubtypes.size();
    if (openablesLength > 0) {
      // copy vectors into arrays
      Openable[] openables = new Openable[openablesLength];
      potentialSubtypes.toArray(openables);

      // sort in the order of roots and in reverse alphabetical order for .class file
      // since requesting top level types in the process of caching an enclosing type is
      // not supported by the lookup environment
      IPackageFragmentRoot[] roots = project.getPackageFragmentRoots();
      int rootsLength = roots.length;
      final HashtableOfObjectToInt indexes = new HashtableOfObjectToInt(openablesLength);
      for (int i = 0; i < openablesLength; i++) {
        IJavaElement root = openables[i].getAncestor(IJavaElement.PACKAGE_FRAGMENT_ROOT);
        int index;
        for (index = 0; index < rootsLength; index++) {
          if (roots[index].equals(root)) break;
        }
        indexes.put(openables[i], index);
      }
      Arrays.sort(
          openables,
          new Comparator() {
            public int compare(Object a, Object b) {
              int aIndex = indexes.get(a);
              int bIndex = indexes.get(b);
              if (aIndex != bIndex) return aIndex - bIndex;
              return ((Openable) b).getElementName().compareTo(((Openable) a).getElementName());
            }
          });

      IType focusType = getType();
      boolean inProjectOfFocusType =
          focusType != null && focusType.getJavaProject().equals(project);
      org.eclipse.jdt.core.ICompilationUnit[] unitsToLookInside = null;
      if (inProjectOfFocusType) {
        org.eclipse.jdt.core.ICompilationUnit unitToLookInside = focusType.getCompilationUnit();
        if (unitToLookInside != null) {
          int wcLength = workingCopies == null ? 0 : workingCopies.length;
          if (wcLength == 0) {
            unitsToLookInside = new org.eclipse.jdt.core.ICompilationUnit[] {unitToLookInside};
          } else {
            unitsToLookInside = new org.eclipse.jdt.core.ICompilationUnit[wcLength + 1];
            unitsToLookInside[0] = unitToLookInside;
            System.arraycopy(workingCopies, 0, unitsToLookInside, 1, wcLength);
          }
        } else {
          unitsToLookInside = workingCopies;
        }
      }

      SearchableEnvironment searchableEnvironment =
          project.newSearchableNameEnvironment(unitsToLookInside);
      this.nameLookup = searchableEnvironment.nameLookup;
      Map options = project.getOptions(true);
      // disable task tags to speed up parsing
      options.put(JavaCore.COMPILER_TASK_TAGS, ""); // $NON-NLS-1$
      this.hierarchyResolver =
          new HierarchyResolver(searchableEnvironment, options, this, new DefaultProblemFactory());
      if (focusType != null) {
        Member declaringMember = ((Member) focusType).getOuterMostLocalContext();
        if (declaringMember == null) {
          // top level or member type
          if (!inProjectOfFocusType) {
            char[] typeQualifiedName = focusType.getTypeQualifiedName('.').toCharArray();
            String[] packageName = ((PackageFragment) focusType.getPackageFragment()).names;
            if (searchableEnvironment.findType(typeQualifiedName, Util.toCharArrays(packageName))
                == null) {
              // focus type is not visible in this project: no need to go further
              return;
            }
          }
        } else {
          // local or anonymous type
          Openable openable;
          if (declaringMember.isBinary()) {
            openable = (Openable) declaringMember.getClassFile();
          } else {
            openable = (Openable) declaringMember.getCompilationUnit();
          }
          localTypes = new HashSet();
          localTypes.add(openable.getPath().toString());
          this.hierarchyResolver.resolve(new Openable[] {openable}, localTypes, monitor);
          return;
        }
      }
      this.hierarchyResolver.resolve(openables, localTypes, monitor);
    }
  }
Exemple #22
0
    /**
     * Resolves a type name in the context of the declaring type.
     *
     * @param refTypeSig the type name in signature notation (for example 'QVector') this can also
     *     be an array type, but dimensions will be ignored.
     * @param declaringType the context for resolving (type where the reference was made in)
     * @return returns the fully qualified type name or build-in-type name. if a unresolved type
     *     couldn't be resolved null is returned
     * @throws JavaModelException thrown when the type can not be accessed
     */
    public IType resolveType(String refTypeSig, IType declaringType) throws JavaModelException {
      IJavaProject javaProject = declaringType.getJavaProject();

      int arrayCount = Signature.getArrayCount(refTypeSig);
      char type = refTypeSig.charAt(arrayCount);
      if (type == Signature.C_UNRESOLVED) {
        String name = ""; // $NON-NLS-1$
        int bracket = refTypeSig.indexOf(Signature.C_GENERIC_START, arrayCount + 1);
        if (bracket > 0) name = refTypeSig.substring(arrayCount + 1, bracket);
        else {
          int semi = refTypeSig.indexOf(Signature.C_SEMICOLON, arrayCount + 1);
          if (semi == -1) {
            throw new IllegalArgumentException();
          }
          name = refTypeSig.substring(arrayCount + 1, semi);
        }

        String dotTypeName = "." + name;
        String dotBaseTypeName = null;
        String dotExtensionTypeName = null;
        int dotIndex = name.indexOf('.');
        if (dotIndex != -1) {
          // We might get a fully qualified type name -- Qcom.apple.jingle.eo.MZProgramNodeType;
          IType resolvedType = javaProject.findType(name);
          if (resolvedType != null) {
            return resolvedType;
          }
          // If not, then this might be a nested type reference on another type, so let's split it
          // to look for that in our imports later
          dotBaseTypeName = "." + name.substring(0, dotIndex);
          dotExtensionTypeName = name.substring(dotIndex);
        }

        IImportDeclaration[] importDeclarations = declaringType.getCompilationUnit().getImports();
        // Loop over the imports and look for the import of our symbol
        for (IImportDeclaration declaration : importDeclarations) {
          String importName = declaration.getElementName();
          // If it's a .* import, then pop off the package name and lookup the type
          if (declaration.isOnDemand()) {
            String packageName = importName.substring(0, importName.lastIndexOf('.'));
            String possibleTypeName = packageName + dotTypeName;
            IType onDemandPackageType = javaProject.findType(possibleTypeName);
            if (onDemandPackageType != null) {
              return onDemandPackageType;
            }
          }
          // If it's not a .* import, then does the import end with our type name?
          else if (importName.endsWith(dotTypeName)) {
            IType importType = javaProject.findType(importName);
            if (importType != null) {
              return importType;
            }
          }
          // If it doesn't, check to see if we were a dotted type ("Outer.Inner") and check to see
          // if Outer is imported
          else if (dotBaseTypeName != null && importName.endsWith(dotBaseTypeName)) {
            // ... then look for Outer.Inner
            IType importNestedType = javaProject.findType(importName + dotExtensionTypeName);
            if (importNestedType != null) {
              return importNestedType;
            }
          }
        }

        // Is this a java.lang.Xxx class that we get for free?
        String javaLangTypeName = "java.lang" + dotTypeName;
        IType javaLangType = javaProject.findType(javaLangTypeName);
        if (javaLangType != null) {
          return javaLangType;
        }

        // What about an inner type of our own class?
        String innerTypeName = declaringType.getFullyQualifiedName('.') + dotTypeName;
        IType innerType = javaProject.findType(innerTypeName);
        if (innerType != null) {
          return innerType;
        }

        // Are we declared in a package?
        IPackageFragment declaringTypePackageFragment = declaringType.getPackageFragment();
        if (declaringTypePackageFragment != null) {
          // ... if so, is this name in our package, so it didn't need an import?
          String samePackageTypeName = declaringTypePackageFragment.getElementName() + dotTypeName;
          IType samePackageType = javaProject.findType(samePackageTypeName);
          if (samePackageType != null) {
            return samePackageType;
          }
        } else {
          // If we were in the default package, is that class in the default package too?
          IType defaultPackageType = javaProject.findType(name);
          if (defaultPackageType != null) {
            return defaultPackageType;
          }
        }

        String slowResolvedTypeName = JavaModelUtil.getResolvedTypeName(refTypeSig, _type);
        if (slowResolvedTypeName != null) {
          IType slowResolvedType = javaProject.findType(slowResolvedTypeName);
          if (slowResolvedType != null) {
            return slowResolvedType;
          }
        }

        return null;
      } else {
        // We were given an Lxxx; signature ... just look it up
        String resolvedTypeName = Signature.toString(refTypeSig.substring(arrayCount));
        IType resolvedType = javaProject.findType(resolvedTypeName);
        return resolvedType;
      }
    }
  /**
   * Creates a qualified class name from a class name which doesn't contain package name.
   *
   * @param parent a full qualified class name of the class which uses this variable
   * @param type a class name which doesn't contain package name
   * @return full a created qualified class name
   */
  public static String getFullQName(IType parent, String type) {
    if (type.indexOf('.') >= 0) {
      return type;
    }
    if (isPrimitive(type)) {
      return type;
    }
    IJavaProject project = parent.getJavaProject();
    try {
      IType javaType = project.findType("java.lang." + type);
      if (javaType != null && javaType.exists()) {
        return javaType.getFullyQualifiedName();
      }
    } catch (Exception ex) {
      ex.printStackTrace();
    }
    while (true) {
      try {
        IType javaType = project.findType(parent.getFullyQualifiedName() + "." + type);
        if (javaType != null && javaType.exists()) {
          return parent.getFullyQualifiedName() + "." + type;
        }
      } catch (Exception ex) {
        ex.printStackTrace();
      }
      try {
        IType javaType =
            project.findType(parent.getPackageFragment().getElementName() + "." + type);
        if (javaType != null && javaType.exists()) {
          return javaType.getFullyQualifiedName();
        }
      } catch (Exception ex) {
        ex.printStackTrace();
      }
      try {
        IImportDeclaration[] imports = parent.getCompilationUnit().getImports();
        for (int i = 0; i < imports.length; i++) {
          String importName = imports[i].getElementName();
          if (importName.endsWith("." + type)) {
            return importName;
          }
          if (importName.endsWith(".*")) {
            try {
              IType javaType = project.findType(importName.replaceFirst("\\*$", type));
              if (javaType != null && javaType.exists()) {
                return javaType.getFullyQualifiedName();
              }
            } catch (Exception ex) {
            }
          }
        }
      } catch (Exception ex) {
        ex.printStackTrace();
      }

      try {
        // スーパークラス
        if (parent.getSuperclassTypeSignature() == null) {
          break;
        }
        String superClass =
            JavaUtil.getFullQName(parent, Signature.toString(parent.getSuperclassTypeSignature()));

        if (superClass.startsWith("java.lang.")) {
          break;
        }

        parent = parent.getJavaProject().findType(superClass);
      } catch (JavaModelException ex) {
      }
    }
    return type;
  }
 /**
  * Sets the extra default values from the given 'type' argument unless it already exists
  *
  * @param type the selected {@link IType}
  */
 private void setDefaultValues(final IType type) {
   setDefaultValues(type.getCompilationUnit());
 }
 /** @see net.sf.commonclipse.Generator#addImports(org.eclipse.jdt.core.IType) */
 @Override
 protected void addImports(IType type) throws JavaModelException {
   type.getCompilationUnit().createImport(BUILDER_CLASS, null, null);
 }
 public static boolean isTestCase(IType type) {
   if (type == null) {
     return false;
   }
   return isTestCase(type.getCompilationUnit());
 }
 public RemoveDeprecatedQuickFixProposal(
     int offset, int length, boolean missingEndQuote, String className, IType type) {
   super(offset, length, missingEndQuote);
   this.className = className;
   this.cu = type.getCompilationUnit();
 }
Exemple #28
0
 public String getSourceCode() throws JavaModelException {
   return type.getCompilationUnit().getSource();
 }
  private void run(Shell shell, IType type) throws CoreException {
    final OverrideMethodDialog dialog = new OverrideMethodDialog(shell, fEditor, type, false);
    if (!dialog.hasMethodsToOverride()) {
      MessageDialog.openInformation(
          shell, getDialogTitle(), ActionMessages.OverrideMethodsAction_error_nothing_found);
      notifyResult(false);
      return;
    }
    if (dialog.open() != Window.OK) {
      notifyResult(false);
      return;
    }

    final Object[] selected = dialog.getResult();
    if (selected == null) {
      notifyResult(false);
      return;
    }

    ArrayList<IMethodBinding> methods = new ArrayList<IMethodBinding>();
    for (int i = 0; i < selected.length; i++) {
      Object elem = selected[i];
      if (elem instanceof IMethodBinding) {
        methods.add((IMethodBinding) elem);
      }
    }
    IMethodBinding[] methodToOverride = methods.toArray(new IMethodBinding[methods.size()]);

    final IEditorPart editor = JavaUI.openInEditor(type.getCompilationUnit());
    final IRewriteTarget target =
        editor != null ? (IRewriteTarget) editor.getAdapter(IRewriteTarget.class) : null;
    if (target != null) target.beginCompoundChange();
    try {
      CompilationUnit astRoot = dialog.getCompilationUnit();
      final ITypeBinding typeBinding = ASTNodes.getTypeBinding(astRoot, type);
      int insertPos = dialog.getInsertOffset();

      AddUnimplementedMethodsOperation operation =
          (AddUnimplementedMethodsOperation)
              createRunnable(
                  astRoot, typeBinding, methodToOverride, insertPos, dialog.getGenerateComment());
      IRunnableContext context = JavaPlugin.getActiveWorkbenchWindow();
      if (context == null) context = new BusyIndicatorRunnableContext();
      PlatformUI.getWorkbench()
          .getProgressService()
          .runInUI(
              context,
              new WorkbenchRunnableAdapter(operation, operation.getSchedulingRule()),
              operation.getSchedulingRule());
      final String[] created = operation.getCreatedMethods();
      if (created == null || created.length == 0)
        MessageDialog.openInformation(
            shell, getDialogTitle(), ActionMessages.OverrideMethodsAction_error_nothing_found);
    } catch (InvocationTargetException exception) {
      ExceptionHandler.handle(exception, shell, getDialogTitle(), null);
    } catch (InterruptedException exception) {
      // Do nothing. Operation has been canceled by user.
    } finally {
      if (target != null) target.endCompoundChange();
    }
    notifyResult(true);
  }
  @SuppressWarnings({"unchecked"})
  @Override
  public RefactoringStatus checkFinalConditions(IProgressMonitor pm)
      throws CoreException, OperationCanceledException {
    RefactoringStatus result = new RefactoringStatus();
    fChangeManager.clear();
    pm.beginTask("", 12);
    pm.setTaskName("Convert to AtomicInteger checking preconditions");
    pm.worked(1);
    if (result.hasFatalError()) return result;
    pm.setTaskName("ConvertToAtomicInteger searching for cunits");
    final SubProgressMonitor subPm = new SubProgressMonitor(pm, 5);
    ICompilationUnit[] affectedCUs =
        RefactoringSearchEngine.findAffectedCompilationUnits(
            SearchPattern.createPattern(targetClass, IJavaSearchConstants.ALL_OCCURRENCES),
            RefactoringScopeFactory.create(targetClass, true),
            subPm,
            result,
            true);

    if (result.hasFatalError()) return result;

    pm.setTaskName("Analyzing the field");
    IProgressMonitor sub = new SubProgressMonitor(pm, 5);
    sub.beginTask("", affectedCUs.length);

    List ownerDescriptions = new ArrayList();
    ICompilationUnit owner = targetClass.getCompilationUnit();

    for (int i = 0; i < affectedCUs.length; i++) {
      ICompilationUnit unit = affectedCUs[i];
      sub.subTask(unit.getElementName());
      CompilationUnit root = null;
      ASTRewrite rewriter = null;
      List descriptions;
      if (owner.equals(unit)) {
        root = fRoot;
        rewriter = fRewriter;
        descriptions = ownerDescriptions;
      } else {
        root = new RefactoringASTParser(AST.JLS3).parse(unit, true);
        rewriter = ASTRewrite.create(root.getAST());
        descriptions = new ArrayList();
      }
      checkCompileErrors(result, root, unit);

      // We will perform a different set of analysis and rewrites for the compilation unit
      // containing the
      // target class and other compilation units
      if (owner.equals(unit)) {

        // Analysis passes
        ClassMutatorAnalysis mutatorAnalysis = new ClassMutatorAnalysis(targetClass, pm);
        mutatorAnalysis.findMutators();

        ClassConstructorAnalysis constructorAnalysis =
            new ClassConstructorAnalysis(targetClassDeclaration);
        targetClassDeclaration.accept(constructorAnalysis);

        // Rewrite pass
        MakeClassImmutableRewriter immutableRewriter =
            new MakeClassImmutableRewriter(this, unit, rewriter);
        immutableRewriter.rewrite(targetClassDeclaration, mutatorAnalysis, constructorAnalysis);

        result.merge(immutableRewriter.getStatus());
        if (result.hasFatalError()) {
          fChangeManager.clear();
          return result;
        }
      } else {

        // descriptions.addAll(immutableRewriter.getGroupDescriptions());
        createEdits(unit, rewriter, descriptions);
      }

      sub.worked(1);
      if (pm.isCanceled()) throw new OperationCanceledException();
    }

    createEdits(owner, fRewriter, ownerDescriptions);

    sub.done();
    IFile[] filesToBeModified = ResourceUtil.getFiles(fChangeManager.getAllCompilationUnits());
    result.merge(Checks.validateModifiesFiles(filesToBeModified, getValidationContext()));
    if (result.hasFatalError()) return result;
    ResourceChangeChecker.checkFilesToBeChanged(filesToBeModified, new SubProgressMonitor(pm, 1));
    return result;
  }