@Override
 public Description matchCompilationUnit(CompilationUnitTree tree, VisitorState state) {
   if (tree.getTypeDecls().size() <= 1) {
     // package-info.java files have zero top-level declarations, everything
     // else should have exactly one.
     return Description.NO_MATCH;
   }
   if (tree.getPackageName() == null) {
     // Real code doesn't use the default package.
     return Description.NO_MATCH;
   }
   List<String> names = new ArrayList<>();
   for (Tree member : tree.getTypeDecls()) {
     if (member instanceof ClassTree) {
       ClassTree classMember = (ClassTree) member;
       switch (classMember.getKind()) {
         case CLASS:
         case INTERFACE:
         case ANNOTATION_TYPE:
         case ENUM:
           SuppressWarnings suppression =
               ASTHelpers.getAnnotation(classMember, SuppressWarnings.class);
           if (suppression != null
               && !Collections.disjoint(Arrays.asList(suppression.value()), allNames())) {
             // If any top-level classes have @SuppressWarnings("TopLevel"), ignore
             // this compilation unit. We can't rely on the normal suppression
             // mechanism because the only enclosing element is the package declaration,
             // and @SuppressWarnings can't be applied to packages.
             return Description.NO_MATCH;
           }
           names.add(classMember.getSimpleName().toString());
           break;
         default:
           break;
       }
     }
   }
   if (names.size() <= 1) {
     // this can happen with multiple type declarations if some of them are
     // empty (e.g. ";" at the top level counts as an empty type decl)
     return Description.NO_MATCH;
   }
   String message =
       String.format(
           "Expected at most one top-level class declaration, instead found: %s",
           Joiner.on(", ").join(names));
   return buildDescription(tree.getPackageName()).setMessage(message).build();
 }
  @Override
  public ImmutableList<Note> analyzeFile(
      final ShipshapeContext shipshapeContext,
      final JavaCompilationDetails compilationDetails,
      final CompilationUnitTree file,
      String path)
      throws AnalyzerException {

    final ImmutableList.Builder<Note> notes = new ImmutableList.Builder<>();

    // Don't run error-prone if the compilation failed in any way.
    if (compilationDetails.hasCompileErrors() || compilationDetails.inBadCompilationState()) {
      return ImmutableList.of();
    }

    // TODO(ciera): Create an EnabledPredicate that uses a configuration file
    // and push that change upstream to errorprone.
    Scanner scanner = new ErrorProneScanner(ErrorProneScanner.EnabledPredicate.DEFAULT_CHECKS);

    JavacTask javacTask = compilationDetails.getJavac();
    Context context = ((JavacTaskImpl) javacTask).getContext();
    JCCompilationUnit compilationUnit = (JCCompilationUnit) file;

    CharSequence source = null;
    try {
      source = file.getSourceFile().getCharContent(false);
    } catch (IOException e) {
      logger.severe(e, "Unable to read source file " + path, shipshapeContext, CATEGORY);
    }
    NoteAdapter adapter =
        new NoteAdapter(
            notes,
            path,
            compilationUnit,
            shipshapeContext,
            source,
            compilationDetails.getEncoding());
    scanner.scan(file, new VisitorState(context, adapter));
    return notes.build();
  }
Example #3
0
  public void run(WorkingCopy workingCopy) throws Exception {
    try {
      workingCopy.toPhase(JavaSource.Phase.ELEMENTS_RESOLVED);

      CompilationUnitTree cut = workingCopy.getCompilationUnit();
      ClassTree classTree = (ClassTree) cut.getTypeDecls().get(0);

      TreeMaker make = workingCopy.getTreeMaker();

      // Import org.glassfish.openesb.pojose.api.annotation.POJO
      //       org.glassfish.openesb.pojose.api.annotation.Operation

      CompilationUnitTree copy =
          make.addCompUnitImport(
              cut,
              make.Import(make.Identifier(GeneratorUtil.PROVIDER_QUAL_CLASS_ANNOTATION), false));
      // workingCopy.rewrite(cut, copy);
      // cut = workingCopy.getCompilationUnit();
      // classTree = (ClassTree) cut.getTypeDecls().get(0);

      CompilationUnitTree copy1 =
          make.addCompUnitImport(
              copy,
              make.Import(
                  make.Identifier(GeneratorUtil.POJO_QUAL_OPERATION_ANNOTATION_CLASS), false));

      copy =
          make.addCompUnitImport(
              copy1, make.Import(make.Identifier(GeneratorUtil.CTX_QUAL_CLASS_ANNOTATION), false));

      copy1 =
          make.addCompUnitImport(
              copy, make.Import(make.Identifier(GeneratorUtil.RSRC_QUAL_CLASS_ANNOTATION), false));

      workingCopy.rewrite(cut, copy1);
      cut = workingCopy.getCompilationUnit();
      classTree = (ClassTree) cut.getTypeDecls().get(0);

      // ADD POJO CLASS TYPE ANNOTATION
      /*
      Document dox = workingCopy.getDocument();
      Element[] arrayOfElements = dox.getRootElements();
      for ( Element el : arrayOfElements) {
         displayElements(el,0);
      }*/

      List<ExpressionTree> argumentValueList = new ArrayList<ExpressionTree>();
      if (annotationArguments != null) {
        Set<Map.Entry<String, Object>> annArgValSet = annotationArguments.entrySet();
        for (Map.Entry<String, Object> mapenty : annArgValSet) {
          argumentValueList.add(
              GeneratorUtil.createAnnotationArgument(make, mapenty.getKey(), mapenty.getValue()));
        }
      }
      AnnotationTree pojoAnnTypeTree =
          GeneratorUtil.createAnnotation(
              make, workingCopy, GeneratorUtil.PROVIDER_CLASS_ANNOTATION, argumentValueList);

      ModifiersTree oldTree = classTree.getModifiers();
      ModifiersTree newTree = make.Modifiers(oldTree, Collections.singletonList(pojoAnnTypeTree));
      workingCopy.rewrite(oldTree, newTree);
      cut = workingCopy.getCompilationUnit();
      classTree = (ClassTree) cut.getTypeDecls().get(0);

      ModifiersTree modifiers =
          handleModifiersAndAnnotations(make, workingCopy, GeneratorUtil.RSRC_ANNOTATION, null);

      VariableTree variableTree =
          GeneratorUtil.createField(
              make,
              workingCopy,
              modifiers,
              GeneratorUtil
                  .POJO_CTX_VARIABLE, // TODO: Check if this variable is not used by this class.
              GeneratorUtil.CTX_ANNOTATION, // NOI18N
              null);

      ClassTree newClassTree1 = make.addClassMember(classTree, variableTree);
      // workingCopy.rewrite(classTree, newClassTree1);

      // CompilationUnitTree modClassTree = make.addCompUnitTypeDecl(cut, pojoAnnTypeTree);
      // workingCopy.rewrite(cut, modClassTree);
      cut = workingCopy.getCompilationUnit();
      classTree = newClassTree1; // (ClassTree) cut.getTypeDecls().get(0);
      // ADD POJO OPERATION.
      boolean bOperationReturnsVoid =
          methodReturnType == null || methodReturnType.equals(GeneratorUtil.GENERATE_VOID);
      argumentValueList = new ArrayList<ExpressionTree>();
      if (!bOperationReturnsVoid && this.operationArguments != null) {
        Set<Map.Entry<String, Object>> annArgValSet = operationArguments.entrySet();
        for (Map.Entry<String, Object> mapenty : annArgValSet) {
          argumentValueList.add(
              GeneratorUtil.createAnnotationArgument(make, mapenty.getKey(), mapenty.getValue()));
        }
      }
      AnnotationTree anTree =
          GeneratorUtil.createAnnotation(make, workingCopy, annotationType, argumentValueList);
      Tree returnType = null;
      boolean bReturnVoid = false;
      if (bOperationReturnsVoid) {
        returnType = make.PrimitiveType(TypeKind.VOID); // return type
        bReturnVoid = true;
      } else {
        returnType = GeneratorUtil.createType(make, workingCopy, methodReturnType);
      }

      List<TypeParameterTree> listOfInputTypes = new ArrayList<TypeParameterTree>();
      List<VariableTree> listOfInputVariables = new ArrayList<VariableTree>();
      //   ModifiersTree modTree = make.Modifiers(Collections.singleton(Modifier.PUBLIC));
      ModifiersTree parMods = make.Modifiers(Collections.EMPTY_SET, Collections.EMPTY_LIST);

      int ix = 0;
      String inputVariableName = null;
      String inputVariableType = null;
      VariableTree inputIdentifier = null;
      for (String argumentType : methodArgumentType) {
        if (!argumentType.equals("")) {
          //  listOfInputTypes.add(  make.TypeParameter(argumentType, null));
          inputVariableName = GeneratorUtil.POJO_VARIABLE_NAME_PREFIX + (ix++);
          inputVariableType = argumentType;
          inputIdentifier =
              GeneratorUtil.createField(
                  make,
                  workingCopy,
                  parMods
                  /** modTree* */
                  ,
                  inputVariableName,
                  argumentType,
                  null);
          listOfInputVariables.add(inputIdentifier);
        }
      }

      BlockTree blockTree = null;
      if (bReturnVoid) {
        blockTree = make.Block(Collections.EMPTY_LIST, false);
      } else {
        // List<ExpressionTree> returnExpList =
        // Collections.singletonList((ExpressionTree)make.Identifier("null"));
        if (inputVariableType != null
            && this.methodReturnType != null
            && methodReturnType.equals(inputVariableType)) {
          ReturnTree retTree = make.Return(make.Identifier(inputVariableName));
          blockTree = make.Block(Collections.singletonList(retTree), false);

        } else {
          ReturnTree retTree = make.Return(make.Identifier("null"));
          blockTree = make.Block(Collections.singletonList(retTree), false);
        }
      }

      MethodTree newMethod =
          make.Method(
              make.Modifiers(
                  Collections.singleton(Modifier.PUBLIC), // modifiers
                  Collections.singletonList(anTree)), // modifiers and annotations
              methodName, // name
              returnType, // return type
              Collections.EMPTY_LIST, // listOfInputTypes, // type parameters for parameters
              listOfInputVariables, // parameters
              Collections.EMPTY_LIST,
              blockTree, // empty statement block
              null // default value - not applicable here, used by annotations
              );
      ClassTree oldClassTree = (ClassTree) cut.getTypeDecls().get(0);
      ClassTree newClassTree = make.addClassMember(classTree, newMethod);
      workingCopy.rewrite(oldClassTree, newClassTree);
    } catch (Exception e) {
      myException = e;
      throw e;
    }
  }
Example #4
0
 public TaskEvent(Kind kind, CompilationUnitTree unit, TypeElement clazz) {
   this(kind, unit.getSourceFile(), unit, clazz);
 }
Example #5
0
 public TaskEvent(Kind kind, CompilationUnitTree unit) {
   this(kind, unit.getSourceFile(), unit, null);
 }