/**
   * Updates the content of <code>cu</code>, modifying the type name and/or package declaration as
   * necessary.
   *
   * @return an AST rewrite or null if no rewrite needed
   */
  private TextEdit updateContent(ICompilationUnit cu, PackageFragment dest, String newName)
      throws JavaModelException {
    String[] currPackageName = ((PackageFragment) cu.getParent()).names;
    String[] destPackageName = dest.names;
    if (Util.equalArraysOrNull(currPackageName, destPackageName) && newName == null) {
      return null; // nothing to change
    } else {
      // ensure cu is consistent (noop if already consistent)
      cu.makeConsistent(this.progressMonitor);

      // GROOVY start
      // don't use the ASTParser if not a Java compilation unit
      if (LanguageSupportFactory.isInterestingSourceFile(cu.getElementName())) {
        // ZALUUM
        // old return updateNonJavaContent(cu, destPackageName, currPackageName, newName);
        return LanguageSupportFactory.updateContent(cu, destPackageName, currPackageName, newName);
        // END ZALUUM
      }
      // GROOVY end

      this.parser.setSource(cu);
      CompilationUnit astCU = (CompilationUnit) this.parser.createAST(this.progressMonitor);
      AST ast = astCU.getAST();
      ASTRewrite rewrite = ASTRewrite.create(ast);
      updateTypeName(cu, astCU, cu.getElementName(), newName, rewrite);
      updatePackageStatement(astCU, destPackageName, rewrite, cu);
      return rewrite.rewriteAST();
    }
  }
  public void testPositiveSourceFolderSourceLocation() throws Exception {
    IResource res = get14Project().getProject().getFolder("src");
    IPackageFragmentRoot root = get14Project().getPackageFragmentRoot(res);
    IJavaSourceLocation location = new PackageFragmentRootSourceLocation(root);

    Object source = location.findSourceElement("Breakpoints");
    assertTrue("Did not find source for 'Breakpoints'", source instanceof ICompilationUnit);
    ICompilationUnit cu = (ICompilationUnit) source;
    assertEquals("Did not find source for 'Breakpoints'", cu.getElementName(), "Breakpoints.java");

    source = location.findSourceElement("org.eclipse.debug.tests.targets.InfiniteLoop");
    assertTrue("Did not find source for 'InfiniteLoop'", source instanceof ICompilationUnit);
    cu = (ICompilationUnit) source;
    assertEquals("Did not find source for 'Breakpoints'", cu.getElementName(), "InfiniteLoop.java");
  }
  /**
   * Gets the fully qualified class name for an active file. For example, its value is foo.bar.Baz.
   *
   * @param file Get fully qualified class file.
   * @return The fully qualified class name. For example,foo.bar.Baz.
   */
  private String getFullyQualifedClassName(IFile file) {
    String fullClassName = "";
    if (file.exists() && file.getName().endsWith(EclipseSensorConstants.JAVA_EXT)) {
      ICompilationUnit compilationUnit = (ICompilationUnit) JavaCore.create(file);
      String className = compilationUnit.getElementName();
      if (className.endsWith(EclipseSensorConstants.JAVA_EXT)) {
        className = className.substring(0, className.length() - 5);
      }

      try {
        IPackageDeclaration[] packageDeclarations = compilationUnit.getPackageDeclarations();
        // Should only have one package declaration
        if (packageDeclarations == null || packageDeclarations.length == 0) {
          fullClassName = className;
        } else {
          fullClassName = packageDeclarations[0].getElementName() + '.' + className;
        }
      } catch (JavaModelException e) {
        // This exception will be thrown if user is working on a Java but did not open
        // it with "Java Perspective". Thus, the Java Model does not exist to parse
        // Java files. So we only log out exception while Eclipse's Java Perspective
        // exits.
        if (!e.isDoesNotExist()) {
          EclipseSensorPlugin.getDefault().log(file.getName(), e);
        }
      }
    }

    return fullClassName;
  }
Example #4
0
 @Override
 public String toString() {
   return "("
       + ModifiableMClass.class.getSimpleName()
       + ")"
       + jdtCu.getParent().getElementName()
       + "."
       + jdtCu.getElementName();
 }
Example #5
0
 /**
  * @since 2.3
  * @deprecated This method is not used anymore.
  */
 @Deprecated
 protected String getExpectedPrimaryTypeNameFor(ICompilationUnit cu) {
   String fileName = cu.getElementName();
   String typeName = fileName.substring(0, fileName.lastIndexOf('.'));
   IPackageFragment pkg = (IPackageFragment) cu.getParent();
   if (!pkg.isDefaultPackage()) {
     typeName = pkg.getElementName() + '.' + typeName;
   }
   return typeName;
 }
Example #6
0
  /**
   * @see
   *     edu.buffalo.cse.green.RefactorHandler#handleMove(edu.buffalo.cse.green.editor.model.RootModel,
   *     org.eclipse.jdt.core.IJavaElement, org.eclipse.jdt.core.IJavaElement)
   */
  public void handleMove(RootModel root, E sourceElement, E targetElement) {
    try {
      List<IJavaElement> cus = root.getElementsOfKind(COMPILATION_UNIT);
      ICompilationUnit[] newCUs = targetElement.getCompilationUnits();

      for (IJavaElement cuElement : cus) {
        ICompilationUnit iCU = (ICompilationUnit) cuElement;
        if (JavaModelListener.sameElements(iCU.getAncestor(PACKAGE_FRAGMENT), sourceElement)) {
          for (ICompilationUnit cu : newCUs) {
            if (cu.getElementName().equals(iCU.getElementName())) {
              CompilationUnitRefactorHandler.instance().handleMove(root, iCU, cu);
            }
          }
        }
      }
    } catch (JavaModelException e) {
      e.printStackTrace();
    }
  }
 protected void compareCompilationUnits(final Map<String, ICompilationUnit> units)
     throws IOException, JavaModelException {
   for (Map.Entry<String, ICompilationUnit> entry : units.entrySet()) {
     String cuName = entry.getKey();
     ICompilationUnit unit = entry.getValue();
     String expected = getFileContents(getOutputTestFileName(cuName));
     String actual = unit.getSource();
     String message = "incorrect changes in " + unit.getElementName();
     assertEqualLines(message, expected, actual);
   }
 }
 private void collectPrivateMethods(ICompilationUnit cu, Set<IMethod> collector) {
   try {
     for (IType type : cu.getAllTypes()) {
       for (IMethod method : type.getMethods()) {
         maybeAddMethod(method, collector);
       }
     }
   } catch (JavaModelException jamox) {
     trace(jamox, cu.getElementName());
   }
 }
  protected void handleCompilationUnit(ICompilationUnit cu) {
    monitor.worked(1);
    monitor.subTask(cu.getElementName());

    try {
      CompilationUnit unit = JavaASTUtil.parseCompilationUnit(cu, monitor);

      currentUnit = (ICompilationUnit) unit.getJavaElement();

      handleUnit(unit);

    } catch (Exception ex) {
      addErrorMsg("Failed to handle unit " + cu.getElementName() + ":" + ex.toString());
      PatternUIPlugin.logWarning("Failed to handle unit " + cu.getElementName(), ex);
    } catch (Throwable ex) {
      addErrorMsg("Failed to handle unit " + cu.getElementName() + ":" + ex.toString());
      PatternUIPlugin.logError("Failed to handle unit " + cu.getElementName(), ex);
    } finally {
      currentUnit = null;
    }
  }
Example #10
0
 @Override
 public void setMPackage(ModifiableMPackage destMPackage) {
   try {
     String destPackageName = destMPackage.getName();
     IPackageFragmentRoot srcRoot = (IPackageFragmentRoot) jdtCu.getParent().getParent();
     IPackageFragment jdtDestPackage = srcRoot.getPackageFragment(destPackageName);
     jdtCu.move(jdtDestPackage, null, null, false, MyMonitor.currentMonitor());
     jdtCu = jdtDestPackage.getCompilationUnit(jdtCu.getElementName());
   } catch (JavaModelException e) {
     throw new MyRuntimeException("Move " + this + " to " + destMPackage, e);
   }
 }
 private void checkCompileErrors(
     RefactoringStatus result, CompilationUnit root, ICompilationUnit element) {
   IProblem[] messages = root.getProblems();
   for (int i = 0; i < messages.length; i++) {
     IProblem problem = messages[i];
     if (!isIgnorableProblem(problem)) {
       result.addError(
           Messages.format("MakeImmutableClass: Compiler errors", element.getElementName()),
           JavaStatusContext.create(element));
       return;
     }
   }
 }
Example #12
0
  /** Launch a compilation unit (a source file) based test. */
  public static void launchCompilationUnitConfiguration(
      IJavaProject ijp, ICompilationUnit icu, String mode) {
    IType[] types = null;
    try {
      types = icu.getTypes();
    } catch (JavaModelException jme) {
      TestNGPlugin.log(
          new Status(
              IStatus.ERROR,
              TestNGPlugin.PLUGIN_ID,
              TestNGPluginConstants.LAUNCH_ERROR,
              "No types in compilation unit " + icu.getElementName(),
              jme));
    }

    if (null == types) return;

    IType mainType = icu.findPrimaryType();
    final String confName = mainType != null ? mainType.getElementName() : icu.getElementName();

    launchTypeBasedConfiguration(ijp, confName, types, mode);
  }
 public void buildFinished(IJavaProject project) {
   try {
     StringBuilder sb = new StringBuilder();
     PreProcessing(project.getElementName());
     IEclipsePreferences prefs = InstanceScope.INSTANCE.getNode(Constants.BUNDLE_NAME);
     String fileName =
         prefs.get("LTiEFileName", "Empty String") + project.getElementName() + ".MTD";
     sb.append("<COMPILE_INSTANCE>");
     Calendar c = Calendar.getInstance();
     SimpleDateFormat format = new SimpleDateFormat("EEE, MMM d, yyyy 'at' HH:mm:ss z");
     sb.append(
         "<TIME UTC=\"" + c.getTimeInMillis() + "\">" + format.format(c.getTime()) + "</TIME>");
     IPackageFragment[] packages = project.getPackageFragments();
     sb.append("<PACKAGES>");
     for (IPackageFragment aPackage : packages) {
       if (aPackage.getKind() == IPackageFragmentRoot.K_SOURCE) {
         String packageName =
             aPackage.getElementName().isEmpty() ? "default" : aPackage.getElementName();
         Constants.writer.println("Package Fragment Name: " + packageName);
         sb.append("<PACKAGE>");
         sb.append("<NAME>" + packageName + "</NAME>");
         sb.append("<FILES>");
         for (ICompilationUnit unit : aPackage.getCompilationUnits()) {
           sb.append("<FILE>");
           sb.append("<NAME>" + unit.getElementName() + "</NAME>");
           printFileInternals(unit, sb);
           printFilesProblems(unit, sb);
           sb.append("<SOURCE>" + StringEscapeUtils.escapeHtml4(unit.getSource()) + "</SOURCE>");
           sb.append("</FILE>");
         }
         ProcessUMLFiles(aPackage.getNonJavaResources(), sb);
         sb.append("</FILES>");
         sb.append("</PACKAGE>");
       }
     }
     sb.append("</PACKAGES>");
     Object[] nonJavaResources = project.getNonJavaResources();
     if (nonJavaResources != null && nonJavaResources.length > 0) {
       sb.append("<FILES>");
       ProcessUMLFiles(nonJavaResources, sb);
       sb.append("</FILES>");
     }
     sb.append("</COMPILE_INSTANCE>");
     PrintWriter out = new PrintWriter(new FileWriter(fileName, true));
     out.write(XMLFormatter.format(sb.toString()));
     out.close();
   } catch (Exception e) {
     e.printStackTrace(Constants.writer);
   }
 }
 /**
  * Updates the content of <code>cu</code>, modifying the type name and/or package declaration as
  * necessary.
  *
  * @return an AST rewrite or null if no rewrite needed
  */
 private TextEdit updateContent(ICompilationUnit cu, PackageFragment dest, String newName)
     throws JavaModelException {
   String[] currPackageName = ((PackageFragment) cu.getParent()).names;
   String[] destPackageName = dest.names;
   if (Util.equalArraysOrNull(currPackageName, destPackageName) && newName == null) {
     return null; // nothing to change
   } else {
     // ensure cu is consistent (noop if already consistent)
     cu.makeConsistent(this.progressMonitor);
     this.parser.setSource(cu);
     CompilationUnit astCU = (CompilationUnit) this.parser.createAST(this.progressMonitor);
     AST ast = astCU.getAST();
     ASTRewrite rewrite = ASTRewrite.create(ast);
     updateTypeName(cu, astCU, cu.getElementName(), newName, rewrite);
     updatePackageStatement(astCU, destPackageName, rewrite, cu);
     return rewrite.rewriteAST();
   }
 }
Example #15
0
  /** 取得Quick Fix後改變的程式碼 */
  private Change getChange(CompilationUnit actRoot, ASTRewrite rewrite) {
    try {
      ICompilationUnit cu = (ICompilationUnit) actOpenable;
      Document document = new Document(cu.getBuffer().getContents());

      TextEdit edits = null;
      if (rewrite != null) edits = rewrite.rewriteAST(document, null);
      else edits = actRoot.rewrite(document, cu.getJavaProject().getOptions(true));

      TextFileChange textFileChange =
          new TextFileChange(cu.getElementName(), (IFile) cu.getResource());
      textFileChange.setEdit(edits);

      return textFileChange;
    } catch (JavaModelException e) {
      logger.error("[Apply Change Rethrow Unchecked Exception] EXCEPTION ", e);
    }
    return null;
  }
Example #16
0
 @Override
 public String getName() {
   String name = jdtCu.getElementName();
   return name.substring(0, name.length() - ".java".length());
 }
Example #17
0
 public AssistCompilationUnit(
     ICompilationUnit compilationUnit, WorkingCopyOwner owner, Map bindingCache, Map infoCache) {
   super((PackageFragment) compilationUnit.getParent(), compilationUnit.getElementName(), owner);
   this.bindingCache = bindingCache;
   this.infoCache = infoCache;
 }
  @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;
  }
  /**
   * Copies/moves a compilation unit with the name <code>newCUName</code> to the destination
   * package.<br>
   * The package statement in the compilation unit is updated if necessary. The main type of the
   * compilation unit is renamed if necessary.
   *
   * @exception JavaModelException if the operation is unable to complete
   */
  private void processCompilationUnitResource(ICompilationUnit source, PackageFragment dest)
      throws JavaModelException {
    String newCUName = getNewNameFor(source);
    String destName = (newCUName != null) ? newCUName : source.getElementName();
    TextEdit edit = updateContent(source, dest, newCUName); // null if unchanged

    // TODO (frederic) remove when bug 67606 will be fixed (bug 67823)
    // store encoding (fix bug 66898)
    IFile sourceResource = (IFile) source.getResource();
    String sourceEncoding = null;
    try {
      sourceEncoding = sourceResource.getCharset(false);
    } catch (CoreException ce) {
      // no problem, use default encoding
    }
    // end todo
    // copy resource
    IContainer destFolder = (IContainer) dest.getResource(); // can be an IFolder or an IProject
    IFile destFile = destFolder.getFile(new Path(destName));
    org.eclipse.jdt.internal.core.CompilationUnit destCU =
        new org.eclipse.jdt.internal.core.CompilationUnit(
            dest, destName, DefaultWorkingCopyOwner.PRIMARY);
    if (!destFile.equals(sourceResource)) {
      try {
        if (!destCU.isWorkingCopy()) {
          if (destFile.exists()) {
            if (this.force) {
              // we can remove it
              deleteResource(destFile, IResource.KEEP_HISTORY);
              destCU.close(); // ensure the in-memory buffer for the dest CU is closed
            } else {
              // abort
              throw new JavaModelException(
                  new JavaModelStatus(
                      IJavaModelStatusConstants.NAME_COLLISION,
                      Messages.bind(
                          Messages.status_nameCollision, destFile.getFullPath().toString())));
            }
          }
          int flags = this.force ? IResource.FORCE : IResource.NONE;
          if (isMove()) {
            flags |= IResource.KEEP_HISTORY;
            sourceResource.move(destFile.getFullPath(), flags, getSubProgressMonitor(1));
          } else {
            if (edit != null) flags |= IResource.KEEP_HISTORY;
            sourceResource.copy(destFile.getFullPath(), flags, getSubProgressMonitor(1));
          }
          setAttribute(HAS_MODIFIED_RESOURCE_ATTR, TRUE);
        } else {
          destCU.getBuffer().setContents(source.getBuffer().getContents());
        }
      } catch (JavaModelException e) {
        throw e;
      } catch (CoreException e) {
        throw new JavaModelException(e);
      }

      // update new resource content
      if (edit != null) {
        boolean wasReadOnly = destFile.isReadOnly();
        try {
          saveContent(dest, destName, edit, sourceEncoding, destFile);
        } catch (CoreException e) {
          if (e instanceof JavaModelException) throw (JavaModelException) e;
          throw new JavaModelException(e);
        } finally {
          Util.setReadOnly(destFile, wasReadOnly);
        }
      }

      // register the correct change deltas
      prepareDeltas(source, destCU, isMove());
      if (newCUName != null) {
        // the main type has been renamed
        String oldName = Util.getNameWithoutJavaLikeExtension(source.getElementName());
        String newName = Util.getNameWithoutJavaLikeExtension(newCUName);
        prepareDeltas(source.getType(oldName), destCU.getType(newName), isMove());
      }
    } else {
      if (!this.force) {
        throw new JavaModelException(
            new JavaModelStatus(
                IJavaModelStatusConstants.NAME_COLLISION,
                Messages.bind(Messages.status_nameCollision, destFile.getFullPath().toString())));
      }
      // update new resource content
      // in case we do a saveas on the same resource we have to simply update the contents
      // see http://dev.eclipse.org/bugs/show_bug.cgi?id=9351
      if (edit != null) {
        saveContent(dest, destName, edit, sourceEncoding, destFile);
      }
    }
  }
Example #20
0
  /**
   * @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);*/
  }