Package org.eclipse.jdt.core

Examples of org.eclipse.jdt.core.ICompilationUnit


  /**
   * Test for {@link Utils#getSingleModule(ICompilationUnit)}.
   */
  public void test_getSingleModule_ICompilationUnit() throws Exception {
    IType entryPointType = m_testProject.getJavaProject().findType("test.client.Module");
    ICompilationUnit compilationUnit = entryPointType.getCompilationUnit();
    assertModuleDescriptionPath("src/test/Module.gwt.xml", Utils.getSingleModule(compilationUnit));
  }
View Full Code Here


        + " finished. Format the Sourcecode properly...");

    // TODO: this kind of code formatting seems very smelly.
    // Source:
    // http://help.eclipse.org/indigo/topic/org.eclipse.jdt.doc.isv/guide/jdt_api_manip.htm
    ICompilationUnit icu = (ICompilationUnit) JavaUI
        .getEditorInputJavaElement(PluginUI.getActiveEditor()
            .getEditorInput());
    String source = "";
    try {
      source = icu.getSource();
    } catch (JavaModelException e) {
      CrashReporter.reportException(e);
      logger.debug(e.getLocalizedMessage());
    }

    // If we shouldn't format the source code -- exit.
    if (!Activator.getDefault().getPreferenceStore()
        .getString(PreferenceConstants.P_FORMAT).equals("true")) {
      return;
    }

    // Take default Eclipse formatting options
    @SuppressWarnings("unchecked")
    Map<String, String> options = DefaultCodeFormatterConstants
        .getEclipseDefaultSettings();

    // initialize the compiler settings to be able to format 1.6
    // code
    options.put(JavaCore.COMPILER_COMPLIANCE, JavaCore.VERSION_1_6);
    options.put(JavaCore.COMPILER_CODEGEN_TARGET_PLATFORM,
        JavaCore.VERSION_1_6);
    options.put(JavaCore.COMPILER_SOURCE, JavaCore.VERSION_1_6);

    // change the option to wrap each enum constant on a new line
    options.put(
        DefaultCodeFormatterConstants.FORMATTER_COMMENT_FORMAT_JAVADOC_COMMENT,
        DefaultCodeFormatterConstants.TRUE);

    // instantiate the default code formatter with the given options
    final CodeFormatter codeFormatter = ToolFactory
        .createCodeFormatter(options);
    final TextEdit editCode = codeFormatter.format(
        CodeFormatter.K_COMPILATION_UNIT
            | CodeFormatter.F_INCLUDE_COMMENTS, source, 0,
        source.length(), 0, System.getProperty("line.separator"));

    IDocument document = new Document(source);

    if (icu != null && document != null && editCode != null) {
      try {
        editCode.apply(document);
      } catch (MalformedTreeException e) {
        CrashReporter.reportException(e);
      } catch (BadLocationException e) {
        CrashReporter.reportException(e);
      }

      try {
        icu.becomeWorkingCopy(null);
        icu.getBuffer().setContents(document.get());
        icu.reconcile(ICompilationUnit.NO_AST, false, null, null);
        icu.commitWorkingCopy(true, null);
        icu.discardWorkingCopy();
      } catch (JavaModelException e) {
        CrashReporter.reportException(e);
        logger.debug("Reconcile operation on ICompilationUnit failed.\r\n"
            + e.getLocalizedMessage());
      }
View Full Code Here

        + " finished. Format the Sourcecode properly...");

    // TODO: this kind of code formatting seems very smelly.
    // Source:
    // http://help.eclipse.org/indigo/topic/org.eclipse.jdt.doc.isv/guide/jdt_api_manip.htm
    ICompilationUnit icu = (ICompilationUnit) JavaUI
        .getEditorInputJavaElement(PluginUI.getActiveEditor()
            .getEditorInput());
    String source = "";
    try {
      source = icu.getSource();
    } catch (JavaModelException e1) {
      logger.debug(e1.getLocalizedMessage());
    }

    // If we shouldn't format the source code -- exit.
    if (!Activator.getDefault().getPreferenceStore()
        .getString(PreferenceConstants.P_FORMAT).equals("true")) {
      return;
    }

    // Take default Eclipse formatting options
    @SuppressWarnings("unchecked")
    Map<String, String> options = DefaultCodeFormatterConstants
        .getEclipseDefaultSettings();

    // initialize the compiler settings to be able to format 1.6
    // code
    options.put(JavaCore.COMPILER_COMPLIANCE, JavaCore.VERSION_1_6);
    options.put(JavaCore.COMPILER_CODEGEN_TARGET_PLATFORM,
        JavaCore.VERSION_1_6);
    options.put(JavaCore.COMPILER_SOURCE, JavaCore.VERSION_1_6);

    // change the option to wrap each enum constant on a new line
    options.put(
        DefaultCodeFormatterConstants.FORMATTER_COMMENT_FORMAT_JAVADOC_COMMENT,
        DefaultCodeFormatterConstants.TRUE);

    // instantiate the default code formatter with the given options
    final CodeFormatter codeFormatter = ToolFactory
        .createCodeFormatter(options);
    final TextEdit editCode = codeFormatter.format(
        CodeFormatter.K_COMPILATION_UNIT
            | CodeFormatter.F_INCLUDE_COMMENTS, source, 0,
        source.length(), 0, System.getProperty("line.separator"));

    IDocument document = new Document(source);

    if (icu != null && document != null && editCode != null) {
      try {
        editCode.apply(document);
      } catch (MalformedTreeException e) {
        e.printStackTrace();
      } catch (BadLocationException e) {
        e.printStackTrace();
      }

      try {
        icu.becomeWorkingCopy(null);
        icu.getBuffer().setContents(document.get());
        icu.reconcile(ICompilationUnit.NO_AST, false, null, null);
        icu.commitWorkingCopy(true, null);
        icu.discardWorkingCopy();
      } catch (JavaModelException e) {
        logger.debug("Reconcile operation on ICompilationUnit failed.\r\n"
            + e.getLocalizedMessage());
      }
    }
View Full Code Here

        + " finished. Format the Sourcecode properly...");

    // TODO: this kind of code formatting seems very smelly.
    // Source:
    // http://help.eclipse.org/indigo/topic/org.eclipse.jdt.doc.isv/guide/jdt_api_manip.htm
    ICompilationUnit icu = (ICompilationUnit) JavaUI
        .getEditorInputJavaElement(PluginUI.getActiveEditor()
            .getEditorInput());
    String source = "";
    try {
      source = icu.getSource();
    } catch (JavaModelException e1) {
      logger.debug(e1.getLocalizedMessage());
    }

    // take default Eclipse formatting options
    HashMap<String, String> options = new HashMap<String, String>();

    // initialize the compiler settings to be able to format 1.6
    // code
    options.put(JavaCore.COMPILER_COMPLIANCE, JavaCore.VERSION_1_6);
    options.put(JavaCore.COMPILER_CODEGEN_TARGET_PLATFORM,
        JavaCore.VERSION_1_6);
    options.put(JavaCore.COMPILER_SOURCE, JavaCore.VERSION_1_6);

    // change the option to wrap each enum constant on a new line
    options.put(
        DefaultCodeFormatterConstants.FORMATTER_COMMENT_FORMAT_JAVADOC_COMMENT,
        DefaultCodeFormatterConstants.TRUE);

    // instantiate the default code formatter with the given options
    final CodeFormatter codeFormatter = ToolFactory
        .createCodeFormatter(options);
    final TextEdit editCode = codeFormatter.format(
        CodeFormatter.K_COMPILATION_UNIT
            | CodeFormatter.F_INCLUDE_COMMENTS, source, 0,
        source.length(), 0, System.getProperty("line.separator"));

    IDocument document = new Document(source);

    if (icu != null && document != null && editCode != null) {
      try {
        editCode.apply(document);
      } catch (MalformedTreeException e) {
        e.printStackTrace();
      } catch (BadLocationException e) {
        e.printStackTrace();
      }

      try {
        icu.becomeWorkingCopy(null);
        icu.getBuffer().setContents(document.get());
        icu.reconcile(ICompilationUnit.NO_AST, false, null, null);
        icu.commitWorkingCopy(true, null);
        icu.discardWorkingCopy();
      } catch (JavaModelException e) {
        logger.debug("Reconcile operation on ICompilationUnit failed.\r\n"
            + e.getLocalizedMessage());
      }
    }
View Full Code Here

        String sourceCode = (String) selectedElement
            .getProperty(ResultProperty.RAW_SOURCE.name());

        // If a CompilatonUnit with the same name exists and is
        // opened, we must close it before overwrite.
        ICompilationUnit icu = pkg.getCompilationUnit(name + ".java");
        if (icu != null && icu.isWorkingCopy()) {
          icu.close();
        }

        // Create the compilationUnit
        final ICompilationUnit icu2 = pkg
            .createCompilationUnit(
                name + ".java",
                sourceCode,
                Activator
                    .getDefault()
                    .getPreferenceStore()
                    .getBoolean(
                        PreferenceConstants.P_OVERWRITE_ON_INSERT),
                null);

        icu2.createPackageDeclaration(pkg.getElementName(), null);

        IFile input = (IFile) icu2.getResource();
        final IEditorInput editorInput = new FileEditorInput(input);
        final IEditorDescriptor desc = PlatformUI.getWorkbench()
            .getEditorRegistry().getDefaultEditor(input.getName());

        PlatformUI.getWorkbench().getDisplay()
View Full Code Here

  private void insertType(IPackageFragment pkg, String name,
      String sourceCode, boolean openInEditor,
      final IProgressMonitor monitor) throws Exception {
    // If a CompilatonUnit with the same name exists and is
    // opened, we must close it before overwrite.
    ICompilationUnit icu = pkg.getCompilationUnit(name + ".java");
    if (icu != null && icu.isWorkingCopy()) {
      icu.close();
    }

    // Create the compilationUnit
    final ICompilationUnit icu2 = pkg.createCompilationUnit(name + ".java",
        sourceCode, Activator.getDefault().getPreferenceStore()
            .getBoolean(PreferenceConstants.P_OVERWRITE_ON_INSERT),
        monitor);

    icu2.createPackageDeclaration(pkg.getElementName(), monitor);

    if (openInEditor) {
      IFile input = (IFile) icu2.getResource();
      final IEditorInput editorInput = new FileEditorInput(input);
      final IEditorDescriptor desc = PlatformUI.getWorkbench()
          .getEditorRegistry().getDefaultEditor(input.getName());

      PlatformUI.getWorkbench().getDisplay().syncExec(new Runnable() {
        @Override
        public void run() {
          try {
            IEditorPart editor = PlatformUI.getWorkbench()
                .getActiveWorkbenchWindow().getActivePage()
                .openEditor(editorInput, desc.getId());

            // Organize imports if necessary
            if (Activator
                .getDefault()
                .getPreferenceStore()
                .getBoolean(
                    PreferenceConstants.P_ORGANIZE_IMPORTS)) {
              OrganizeImportsAction organize = new OrganizeImportsAction(
                  editor.getEditorSite());
              organize.run(icu2);
            }

            // Format code properly
            if (Activator
                .getDefault()
                .getPreferenceStore()
                .getBoolean(
                    PreferenceConstants.P_FORMAT_ON_INSERT)) {
              FormatAllAction format = new FormatAllAction(editor
                  .getEditorSite());
              format.runOnMultiple(new ICompilationUnit[] { icu2 });
            }
            icu2.commitWorkingCopy(true, monitor);
          } catch (Exception e) {
            logger.debug(e.toString());
            CrashReporter.reportException(e);
          }
        }
      });
    }
    icu2.close();
  }
View Full Code Here

   * @see org.eclipse.swt.dnd.DropTargetListener#drop(org.eclipse.swt.dnd.
   * DropTargetEvent)
   */
  @Override
  public void drop(DropTargetEvent event) {
    ICompilationUnit icu = (ICompilationUnit) JavaUI
        .getEditorInputJavaElement(PluginUI.getActiveEditor()
            .getEditorInput());

    if (event.data == null) {
      logger.trace("Nothing to insert");
View Full Code Here

      MethodDeclaration methodDeclaration) throws JavaModelException,
      MalformedTreeException, BadLocationException {
    boolean overwrite = Activator.getDefault().getPreferenceStore()
        .getBoolean(PreferenceConstants.P_OVERWRITE_ON_INSERT);

    ICompilationUnit cpu = target.getWorkingCopy(null);
    // creation of DOM/AST from an ICompilationUnit
    ASTParser parser = ASTParser.newParser(AST.JLS3);
    parser.setSource(cpu);
    CompilationUnit astRoot = (CompilationUnit) parser.createAST(null);

    StringBuffer signature = new StringBuffer();
    signature.append(methodDeclaration.getName().getFullyQualifiedName()
        + " ( ");
    for (Object param : methodDeclaration.parameters()) {
      if (param instanceof SingleVariableDeclaration) {
        signature.append(((SingleVariableDeclaration) param).getType()
            .toString() + " ");
      }
    }
    signature.append(") : " + methodDeclaration.getReturnType2());

    methodDeclaration.setProperty("Signature", signature.toString());

    // creation of ASTRewrite
    astRoot.recordModifications();
    IMethod method = null;
    String content = createPreambule(methodDeclaration) + "\r\n"
        + methodDeclaration.toString();
    try {
      method = astRoot.getTypeRoot().findPrimaryType()
          .createMethod(content, null, overwrite, null);
    } catch (JavaModelException e) {
      CrashReporter.reportException(e);
      logger.debug("Method could not be created: "
          + e.getLocalizedMessage());
    }

    if (method != null) {
      if (overwrite) {
        IMethod[] methods = astRoot.getTypeRoot().findPrimaryType()
            .findMethods(method);
        for (int i = 0; i < methods.length - 1; i++) {
          methods[i].delete(false, null);
        }
      }
    }

    // update of the compilation unit
    cpu.getBuffer().setContents(
        astRoot.getTypeRoot().findPrimaryType().getCompilationUnit()
            .getSource());
    cpu.reconcile(ICompilationUnit.NO_AST, false, null, null);
    cpu.commitWorkingCopy(false, null);
  }
View Full Code Here

   */
  private void insertDeclaration(ICompilationUnit target,
      TypeDeclaration typeDeclaration) throws JavaModelException,
      MalformedTreeException, BadLocationException {
    try {
      ICompilationUnit icu = target.getWorkingCopy(null);

      // creation of DOM/AST from an ICompilationUnit
      ASTParser parser = ASTParser.newParser(AST.JLS3);
      parser.setSource(icu);
      CompilationUnit astRoot = (CompilationUnit) parser.createAST(null);

      StringBuffer signature = new StringBuffer();
      signature.append(typeDeclaration.getName().getFullyQualifiedName());

      typeDeclaration.setProperty("Signature", signature.toString());

      TypeDeclaration dropTypeDec = (TypeDeclaration) ASTNode
          .copySubtree(astRoot.getAST(), typeDeclaration);

      // creation of ASTRewrite
      AST ast = astRoot.getAST();
      ASTRewrite rewrite = ASTRewrite.create(ast);

      // description of the change
      for (Object typeObj : astRoot.types()) {
        if (typeObj instanceof TypeDeclaration) {
          TypeDeclaration typeDec = (TypeDeclaration) typeObj;
          if (typeDec.getName().toString()
              .equals(dropTypeDec.getName().toString())) {
            logger.debug("Replace existing type declaration");
            if (Activator
                .getDefault()
                .getPreferenceStore()
                .getString(
                    PreferenceConstants.P_OVERWRITE_ON_INSERT)
                .equals("true")) {
              rewrite.remove(typeDec, null);
            }
          }
        }
      }

      ASTNode a = ASTNode.copySubtree(ast, dropTypeDec);
      @SuppressWarnings("unchecked")
      List<TypeDeclaration> types = astRoot.types();
      ArrayList<TypeDeclaration> newTypes = new ArrayList<TypeDeclaration>();
      newTypes.add((TypeDeclaration) a);
      if (types.addAll(newTypes)) {
        if (!target.getElementName().equals(
            dropTypeDec.getName().toString() + ".java")) {
          List<?> modifiers = dropTypeDec.modifiers();
          for (Object mod : modifiers) {
            if (mod instanceof Modifier) {
              Modifier modifier = (Modifier) mod;
              if (modifier.getKeyword().toString()
                  .equals("public")) {
                dropTypeDec.modifiers().remove(modifier);
                break;
              }
            }
          }
        }
        String preambule = createPreambule(typeDeclaration) + "\r\n";
        icu.createType(preambule + dropTypeDec.toString(), null, true,
            null);
        logger.debug("New type added successfully");
      }

      String source = icu.getSource();
      Document document = new Document(source);

      // computation of the text edits
      TextEdit edits = rewrite.rewriteAST(document, icu.getJavaProject()
          .getOptions(true));

      // computation of the new source code
      if (edits != null) {
        edits.apply(document);
      }

      String newSource = document.get();

      // update of the compilation unit
      icu.getBuffer().setContents(newSource);
      icu.reconcile(ICompilationUnit.NO_AST, false, null, null);
      icu.commitWorkingCopy(false, null);
      icu.discardWorkingCopy();
    } catch (Exception e) {
      CrashReporter.reportException(e);
      logger.debug("Could not insert result: " + e.toString());
    }
  }
View Full Code Here

      // Insert method
      if (selectedElement.getNodeType() == BodyDeclaration.METHOD_DECLARATION) {
        boolean overwrite = Activator.getDefault().getPreferenceStore()
            .getBoolean(PreferenceConstants.P_OVERWRITE_ON_INSERT);
        ICompilationUnit cpu = target.getWorkingCopy(null);
        // creation of DOM/AST from an ICompilationUnit
        ASTParser parser = ASTParser.newParser(AST.JLS3);
        parser.setSource(cpu);
        CompilationUnit astRoot = (CompilationUnit) parser
            .createAST(null);

        // creation of ASTRewrite
        astRoot.recordModifications();
        IMethod method = null;
        String content = createPreambule(selectedElement) + "\r\n"
            + selectedElement.toString();
        try {
          method = astRoot.getTypeRoot().findPrimaryType()
              .createMethod(content, null, overwrite, null);
        } catch (JavaModelException e) {
          logger.debug("Method could not be created: "
              + e.getLocalizedMessage());
        }

        if (method != null) {
          if (overwrite) {
            IMethod[] methods = astRoot.getTypeRoot()
                .findPrimaryType().findMethods(method);
            for (int i = 0; i < methods.length - 1; i++) {
              methods[i].delete(false, null);
            }
          }
        }

        // update of the compilation unit
        cpu.getBuffer().setContents(
            astRoot.getTypeRoot().findPrimaryType()
                .getCompilationUnit().getSource());
        cpu.reconcile(ICompilationUnit.NO_AST, false, null, null);
        cpu.commitWorkingCopy(false, null);
        return Status.OK_STATUS;
      }

      // Insert class
      if (selectedElement.getNodeType() == BodyDeclaration.TYPE_DECLARATION) {
        TypeDeclaration typeDec = (TypeDeclaration) selectedElement;
        String name = typeDec.getName().toString();
        String sourceCode = (String) selectedElement
            .getProperty(ResultProperty.RAW_SOURCE.name());

        // If a CompilatonUnit with the same name exists and is
        // opened, we must close it before overwrite.
        ICompilationUnit icu = pkg.getCompilationUnit(name + ".java");
        if (icu != null && icu.isWorkingCopy()) {
          icu.close();
        }

        // Create the compilationUnit
        final ICompilationUnit icu2 = pkg
            .createCompilationUnit(
                name + ".java",
                sourceCode,
                Activator
                    .getDefault()
                    .getPreferenceStore()
                    .getBoolean(
                        PreferenceConstants.P_OVERWRITE_ON_INSERT),
                null);

        icu2.createPackageDeclaration(pkg.getElementName(), null);

        IFile input = (IFile) icu2.getResource();
        final IEditorInput editorInput = new FileEditorInput(input);
        final IEditorDescriptor desc = PlatformUI.getWorkbench()
            .getEditorRegistry().getDefaultEditor(input.getName());

        PlatformUI.getWorkbench().getDisplay()
View Full Code Here

TOP

Related Classes of org.eclipse.jdt.core.ICompilationUnit

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.