Пример #1
0
  public MClassJDT(MPackageJDT mpkg, String name) {
    String fullname = "???." + name;
    ICompilationUnit workingCopy = null;
    try {
      IPackageFragment jdtPackage = (IPackageFragment) mpkg.getJdtPackageInfo().getParent();
      fullname = jdtPackage.getElementName() + "." + name;
      if (jdtPackage.getCompilationUnit(name + ".java").exists())
        throw new MyRuntimeException("Class with name '" + fullname + "' already exists.");
      IProgressMonitor monitor = MyMonitor.currentMonitor();

      String content = "public class " + name + " {}";
      ICompilationUnit cu = jdtPackage.createCompilationUnit(name + ".java", content, true, null);
      workingCopy = cu.getWorkingCopy(monitor);
      workingCopy.createPackageDeclaration(jdtPackage.getElementName(), monitor);

      String source = ((IOpenable) workingCopy).getBuffer().getContents();

      Map<?, ?> options = EclipseUtils.getJdtCorePreferences(jdtPackage);

      // instantiate the default code formatter with the given options
      final CodeFormatter codeFormatter =
          ToolFactory.createCodeFormatter(options, ToolFactory.M_FORMAT_NEW);

      TextEdit edit =
          codeFormatter.format(
              CodeFormatter.K_COMPILATION_UNIT, source, 0, source.length(), 0, null);

      if (edit == null) {
        throw new MyRuntimeException("Can't format the source: " + source);
      }

      workingCopy.applyTextEdit(edit, monitor);
      workingCopy.commitWorkingCopy(false, monitor);
      workingCopy.discardWorkingCopy();

      jdtCu = jdtPackage.getCompilationUnit(name + ".java");
    } catch (JavaModelException e) {
      throw new MyRuntimeException("Can not create '" + fullname + "' class.", e);
    } finally {
      if (workingCopy != null)
        try {
          workingCopy.discardWorkingCopy();
        } catch (JavaModelException e) {
          throw new MyRuntimeException(e);
        }
    }
  }
Пример #2
0
 /**
  * Formats the specified compilation unit.
  *
  * @param unit the compilation unit to format
  * @param monitor the monitor for the operation
  * @throws JavaModelException
  */
 public static void formatUnitSourceCode(ICompilationUnit unit, IProgressMonitor monitor)
     throws JavaModelException {
   CodeFormatter formatter = ToolFactory.createCodeFormatter(null);
   ISourceRange range = unit.getSourceRange();
   TextEdit formatEdit =
       formatter.format(
           CodeFormatter.K_COMPILATION_UNIT,
           unit.getSource(),
           range.getOffset(),
           range.getLength(),
           0,
           null);
   if (formatEdit != null && formatEdit.hasChildren()) {
     unit.applyTextEdit(formatEdit, monitor);
   } else {
     monitor.done();
   }
 }