/**
   * Determines the selected class.
   *
   * @param dObj the d obj
   * @throws IllegalArgumentException the illegal argument exception
   */
  protected final void determineSelectedClass(DataObject dObj) throws IllegalArgumentException {
    if (null != dObj) {

      FileObject fo = dObj.getPrimaryFile();

      JavaSource jsource = JavaSource.forFileObject(fo);

      if (jsource == null) {
        StatusDisplayer.getDefault().setStatusText("Not a Java file: " + fo.getPath());
      } else {
        // StatusDisplayer.getDefault().setStatusText("Hurray! A Java file: " + fo.getPath());

        try {
          jsource.runUserActionTask(
              (CompilationController p) -> {
                p.toPhase(JavaSource.Phase.ELEMENTS_RESOLVED);
                CompilationUnitTree tree = p.getCompilationUnit();
                MemberVisitor scanner = new MemberVisitor(p);
                scanner.scan(p.getCompilationUnit(), null);
                te = scanner.getTypeElement();
                Document document = p.getDocument();
              },
              true);
        } catch (IOException ex) {
          Exceptions.printStackTrace(ex);
        }
      }
    }
  }
  public void testAddExtends() throws Exception {
    testFile = new File(getWorkDir(), "Test.java");
    TestUtilities.copyStringToFile(
        testFile,
        "package hierbas.del.litoral;\n\n"
            + "import java.util.*;\n\n"
            + "public interface Test {\n"
            + "    public void taragui();\n"
            + "}\n");
    String golden =
        "package hierbas.del.litoral;\n\n"
            + "import java.util.*;\n\n"
            + "public interface Test extends Serializable {\n"
            + "    public void taragui();\n"
            + "}\n";
    JavaSource src = getJavaSource(testFile);

    Task task =
        new Task<WorkingCopy>() {

          public void run(WorkingCopy workingCopy) throws IOException {
            workingCopy.toPhase(Phase.RESOLVED);
            CompilationUnitTree cut = workingCopy.getCompilationUnit();
            TreeMaker make = workingCopy.getTreeMaker();

            for (Tree typeDecl : cut.getTypeDecls()) {
              // ensure that it is correct type declaration, i.e. class
              if (TreeUtilities.CLASS_TREE_KINDS.contains(typeDecl.getKind())) {
                ClassTree classTree = (ClassTree) typeDecl;
                List<ExpressionTree> implementz =
                    Collections.<ExpressionTree>singletonList(make.Identifier("Serializable"));
                ClassTree copy =
                    make.Class(
                        classTree.getModifiers(),
                        classTree.getSimpleName(),
                        classTree.getTypeParameters(),
                        classTree.getExtendsClause(),
                        implementz,
                        classTree.getMembers());
                workingCopy.rewrite(classTree, copy);
              }
            }
          }
        };
    src.runModificationTask(task).commit();
    String res = TestUtilities.copyFileToString(testFile);
    assertEquals(golden, res);
  }
  /* (non-Javadoc)
   * @see org.openide.util.actions.NodeAction#performAction(org.openide.nodes.Node[])
   */
  @Override
  protected void performAction(Node[] nodes) {
    // context.

    if (null != nodes) {
      for (Node currentnode : nodes) {
        DataObject dObj = currentnode.getLookup().lookup(DataObject.class);
        // Project pRoot = currentnode.getLookup().lookup(Project.class);
        Project pRoot = Te2mWizardBase.findProjectThatOwnsNode(currentnode);
        if (null != dObj) {
          determineSelectedClass(dObj);
          FileObject fo = dObj.getPrimaryFile();

          JavaSource jsource = JavaSource.forFileObject(fo);

          if (jsource == null) {
            StatusDisplayer.getDefault().setStatusText("Not a Java file: " + fo.getPath());
          } else {
            StatusDisplayer.getDefault().setStatusText("Hurray! A Java file: " + fo.getPath());

            executeWizard(currentnode);
          }
        }
      }
    }
  }
  private Collection<Token> performTest(String sourceCode, final int offset, boolean[] wasResolved)
      throws Exception {
    FileObject root = makeScratchDir(this);

    FileObject sourceDir = root.createFolder("src");
    FileObject buildDir = root.createFolder("build");
    FileObject cacheDir = root.createFolder("cache");

    source = sourceDir.createFolder("test").createData("Test.java");

    writeIntoFile(source, sourceCode);

    SourceUtilsTestUtil.prepareTest(sourceDir, buildDir, cacheDir, new FileObject[0]);

    DataObject od = DataObject.find(source);
    EditorCookie ec = od.getCookie(EditorCookie.class);
    Document doc = ec.openDocument();

    doc.putProperty(Language.class, JavaTokenId.language());
    doc.putProperty("mimeType", "text/x-java");

    return InstantRenamePerformer.computeChangePoints(
        SourceUtilsTestUtil.getCompilationInfo(JavaSource.forFileObject(source), Phase.RESOLVED),
        offset,
        wasResolved);
  }
 protected boolean enable(Node[] activatedNodes) {
   if (activatedNodes.length != 1) {
     return false;
   } else {
     FileObject fo = findFileObject(activatedNodes[0]);
     return fo != null
         && JavaSource.forFileObject(fo) != null
         && !fo.getName().endsWith("BeanInfo"); // NOI18N
   }
 }
 private void analyzePatternsImpl() {
   if (javaFile == null) {
     isCancelled = true;
     return;
   }
   checkState(0);
   state = 1;
   try {
     JavaSource.forFileObject(javaFile).runUserActionTask(this, true);
   } catch (Exception ex) {
     isCancelled = true;
     Exceptions.printStackTrace(ex);
   }
 }
示例#7
0
    @Override
    public ChangeInfo implement() throws Exception {
      JavaSource js = JavaSource.forFileObject(sourceCode);

      js.runModificationTask(
              new Task<WorkingCopy>() {
                @Override
                public void run(WorkingCopy parameter) throws Exception {
                  parameter.toPhase(Phase.RESOLVED);
                  TypeElement suppressWarningsAnnotation = null;

                  for (String ann : SUPPRESS_WARNINGS_ANNOTATIONS) {
                    if ((suppressWarningsAnnotation = parameter.getElements().getTypeElement(ann))
                        != null) break;
                  }

                  if (suppressWarningsAnnotation == null) {
                    NotifyDescriptor nd =
                        new NotifyDescriptor.Message(
                            "Cannot find SuppressWarnings annotation with Retention.CLASS, please add some on the classpath",
                            NotifyDescriptor.WARNING_MESSAGE);
                    DialogDisplayer.getDefault().notifyLater(nd);
                    return;
                  }

                  int realPos;

                  if (pos != (-1)) {
                    realPos = pos;
                  } else {
                    realPos =
                        (int) parameter.getCompilationUnit().getLineMap().getPosition(line, 0);
                  }

                  TreePath tp = parameter.getTreeUtilities().pathFor(realPos);

                  while (tp != null && !ANNOTATABLE.contains(tp.getLeaf().getKind())) {
                    tp = tp.getParentPath();
                  }

                  if (tp == null) return;

                  ModifiersTree mods;
                  Tree leaf = tp.getLeaf();

                  switch (leaf.getKind()) {
                    case ANNOTATION_TYPE:
                    case CLASS:
                    case ENUM:
                    case INTERFACE:
                      mods = ((ClassTree) leaf).getModifiers();
                      break;
                    case METHOD:
                      mods = ((MethodTree) leaf).getModifiers();
                      break;
                    case VARIABLE:
                      mods = ((MethodTree) leaf).getModifiers();
                      break;
                    default:
                      throw new IllegalStateException(leaf.getKind().name());
                  }

                  parameter.rewrite(
                      mods,
                      GeneratorUtilities.get(parameter)
                          .appendToAnnotationValue(
                              mods,
                              suppressWarningsAnnotation,
                              "value",
                              parameter.getTreeMaker().Literal(bugId)));
                }
              })
          .commit();

      return null;
    }
示例#8
0
  private static int[] spanFor(
      CompilationInfo info, JavaSource js, final PackageMemberAnnotation annotation) {
    final int[] result = new int[] {-1, -1};
    class TaskImpl implements Task<CompilationInfo> {
      @Override
      public void run(final CompilationInfo parameter) {
        TypeElement clazz = parameter.getElements().getTypeElement(annotation.getClassName());

        if (clazz == null) {
          // XXX: log
          return;
        }

        Element resolved = null;

        if (annotation instanceof FieldAnnotation) {
          FieldAnnotation fa = (FieldAnnotation) annotation;

          for (VariableElement var : ElementFilter.fieldsIn(clazz.getEnclosedElements())) {
            if (var.getSimpleName().contentEquals(fa.getFieldName())) {
              resolved = var;
              break;
            }
          }
        } else if (annotation instanceof MethodAnnotation) {
          MethodAnnotation ma = (MethodAnnotation) annotation;

          for (ExecutableElement method : ElementFilter.methodsIn(clazz.getEnclosedElements())) {
            if (method.getSimpleName().contentEquals(ma.getMethodName())) {
              if (ma.getMethodSignature()
                  .equals(SourceUtils.getJVMSignature(ElementHandle.create(method))[2])) {
                resolved = method;
                break;
              }
            }
          }
        } else if (annotation instanceof ClassAnnotation) {
          resolved = clazz;
        }

        if (resolved == null) {
          // XXX: log
          return;
        }

        final Element resolvedFin = resolved;

        new CancellableTreePathScanner<Void, Void>() {
          @Override
          public Void visitVariable(VariableTree node, Void p) {
            if (resolvedFin.equals(parameter.getTrees().getElement(getCurrentPath()))) {
              int[] span = parameter.getTreeUtilities().findNameSpan(node);

              if (span != null) {
                result[0] = span[0];
                result[1] = span[1];
              }
            }

            return super.visitVariable(node, p);
          }

          @Override
          public Void visitMethod(MethodTree node, Void p) {
            if (resolvedFin.equals(parameter.getTrees().getElement(getCurrentPath()))) {
              int[] span = parameter.getTreeUtilities().findNameSpan(node);

              if (span != null) {
                result[0] = span[0];
                result[1] = span[1];
              }
            }

            return super.visitMethod(node, p);
          }

          @Override
          public Void visitClass(ClassTree node, Void p) {
            if (resolvedFin.equals(parameter.getTrees().getElement(getCurrentPath()))) {
              int[] span = parameter.getTreeUtilities().findNameSpan(node);

              if (span != null) {
                result[0] = span[0];
                result[1] = span[1];
              }
            }

            return super.visitClass(node, p);
          }
        }.scan(parameter.getCompilationUnit(), null);
      }
    };

    final TaskImpl convertor = new TaskImpl();

    if (info != null) {
      convertor.run(info);
    } else {
      try {
        js.runUserActionTask(
            new Task<CompilationController>() {
              @Override
              public void run(CompilationController parameter) throws Exception {
                parameter.toPhase(
                    Phase.RESOLVED); // XXX: ENTER should be enough in most cases, but not for
                // anonymous innerclasses.
                convertor.run(parameter);
              }
            },
            true);
      } catch (IOException ex) {
        Exceptions.printStackTrace(ex);
      }
    }

    return result;
  }
示例#9
0
  public static List<ErrorDescription> runFindBugs(
      CompilationInfo info,
      Preferences customSettings,
      String singleBug,
      FileObject sourceRoot,
      Iterable<? extends String> classNames,
      FindBugsProgress progress,
      SigFilesValidator validator) {
    List<ErrorDescription> result = new ArrayList<ErrorDescription>();

    try {
      Class.forName(
          "org.netbeans.modules.findbugs.NbClassFactory",
          true,
          RunFindBugs.class.getClassLoader()); // NOI18N
      Project p = new Project();
      URL[] binaryRoots =
          CacheBinaryForSourceQuery.findCacheBinaryRoots(sourceRoot.toURL()).getRoots();

      if (classNames == null) {
        for (URL binary : binaryRoots) {
          try {
            p.addFile(new File(binary.toURI()).getAbsolutePath());
          } catch (URISyntaxException ex) {
            Exceptions.printStackTrace(ex);
          }
        }
      } else {
        ClassPath binary = ClassPathSupport.createClassPath(binaryRoots);
        List<FileObject> sigFiles = new ArrayList<FileObject>();

        for (String className : classNames) {
          FileObject classFO = binary.findResource(className.replace('.', '/') + ".sig"); // NOI18N

          if (classFO != null) {
            sigFiles.add(classFO);
          } else {
            LOG.log(
                Level.WARNING,
                "Cannot find sig file for: "
                    + className); // TODO: should probably become FINE eventually
          }
        }

        assert validator != null;

        if (!validator.validate(sigFiles)) return null;

        for (FileObject classFO : sigFiles) {
          p.addFile(new File(classFO.toURI()).getAbsolutePath());
        }

        addCompileRootAsSource(p, sourceRoot);
      }

      ClassPath compile = ClassPath.getClassPath(sourceRoot, ClassPath.COMPILE);

      for (FileObject compileRoot : compile.getRoots()) {
        addCompileRoot(p, compileRoot);
      }

      BugCollectionBugReporter r =
          new BugCollectionBugReporter(p) {
            @Override
            protected void emitLine(String line) {
              LOG.log(Level.FINE, line);
            }
          };

      r.setPriorityThreshold(Integer.MAX_VALUE);
      r.setRankThreshold(Integer.MAX_VALUE);

      FindBugs2 engine = new FindBugs2();

      engine.setProject(p);
      engine.setNoClassOk(true);
      engine.setBugReporter(r);

      if (progress != null) {
        engine.setProgressCallback(progress);
      }

      boolean inEditor = validator != null;
      Preferences settings =
          customSettings != null
              ? customSettings
              : NbPreferences.forModule(RunFindBugs.class).node("global-settings");
      UserPreferences preferences;

      if (singleBug != null) {
        singleBug = singleBug.substring(PREFIX_FINDBUGS.length());
        preferences = forSingleBug(singleBug);
      } else {
        preferences = readPreferences(settings, customSettings != null);
      }

      if (preferences == null) {
        // nothing enabled, stop
        return result;
      }

      engine.setUserPreferences(preferences);
      engine.setDetectorFactoryCollection(DetectorFactoryCollection.instance());

      LOG.log(Level.FINE, "Running FindBugs");

      engine.execute();

      Map<FileObject, List<BugInstance>> file2Bugs = new HashMap<FileObject, List<BugInstance>>();

      for (BugInstance b : r.getBugCollection().getCollection()) {
        if (singleBug != null && !singleBug.equals(b.getBugPattern().getType())) continue;
        if (singleBug == null
            && !settings.getBoolean(
                b.getBugPattern().getType(),
                customSettings == null && isEnabledByDefault(b.getBugPattern()))) {
          continue;
        }

        SourceLineAnnotation sourceLine = b.getPrimarySourceLineAnnotation();
        FileObject sourceFile = null;

        if (sourceLine != null) {
          sourceFile = sourceRoot.getFileObject(sourceLine.getSourcePath());

          if (sourceFile != null) {
            List<BugInstance> bugs = file2Bugs.get(sourceFile);

            if (bugs == null) {
              file2Bugs.put(sourceFile, bugs = new ArrayList<BugInstance>());
            }

            bugs.add(b);
          } else {
            LOG.log(
                Level.WARNING,
                "{0}, location: {1}:{2}",
                new Object[] {b, sourceLine.getSourcePath(), sourceLine.getStartLine()});
          }
        }
      }

      for (Entry<FileObject, List<BugInstance>> e : file2Bugs.entrySet()) {
        int[] lineOffsets = null;
        FileObject sourceFile = e.getKey();
        DataObject d = DataObject.find(sourceFile);
        EditorCookie ec = d.getLookup().lookup(EditorCookie.class);
        Document doc = ec.getDocument();
        JavaSource js = null;

        for (BugInstance b : e.getValue()) {
          SourceLineAnnotation sourceLine = b.getPrimarySourceLineAnnotation();

          if (sourceLine.getStartLine() >= 0) {
            LazyFixList fixes =
                prepareFixes(b, inEditor, sourceFile, sourceLine.getStartLine(), null);

            if (doc != null) {
              result.add(
                  ErrorDescriptionFactory.createErrorDescription(
                      PREFIX_FINDBUGS + b.getType(),
                      Severity.VERIFIER,
                      b.getMessageWithoutPrefix(),
                      b.getBugPattern().getDetailHTML(),
                      fixes,
                      doc,
                      sourceLine.getStartLine()));
            } else {
              if (lineOffsets == null) {
                lineOffsets = computeLineMap(sourceFile, FileEncodingQuery.getEncoding(sourceFile));
              }

              int edLine = 2 * (Math.min(sourceLine.getStartLine(), lineOffsets.length / 2) - 1);

              result.add(
                  ErrorDescriptionFactory.createErrorDescription(
                      PREFIX_FINDBUGS + b.getType(),
                      Severity.VERIFIER,
                      b.getMessageWithoutPrefix(),
                      b.getBugPattern().getDetailHTML(),
                      fixes,
                      sourceFile,
                      lineOffsets[edLine],
                      lineOffsets[edLine + 1]));
            }
          } else {
            if (js == null) {
              js = JavaSource.forFileObject(sourceFile);
            }
            addByElementAnnotation(b, info, sourceFile, js, result, inEditor);
          }
        }
      }
    } catch (ClassNotFoundException ex) {
      Exceptions.printStackTrace(ex);
    } catch (IOException ex) {
      Exceptions.printStackTrace(ex);
    } catch (InterruptedException ex) {
      LOG.log(Level.FINE, null, ex);
    }

    return result;
  }