com.github.javaparser.ast.Modifier Java Examples

The following examples show how to use com.github.javaparser.ast.Modifier. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: DecisionConfigGenerator.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
private MethodDeclaration generateMergeEventListenerConfigMethod() {
    BlockStmt body = new BlockStmt().addStatement(new ReturnStmt(newObject(CachedDecisionEventListenerConfig.class,
            callMerge(
                    VAR_DECISION_EVENT_LISTENER_CONFIG,
                    DecisionEventListenerConfig.class, "listeners",
                    VAR_DMN_RUNTIME_EVENT_LISTENERS
            )
    )));

    return method(Modifier.Keyword.PRIVATE, DecisionEventListenerConfig.class, METHOD_MERGE_DECISION_EVENT_LISTENER_CONFIG,
            nodeList(
                    new Parameter().setType(genericType(Collection.class, DecisionEventListenerConfig.class)).setName(VAR_DECISION_EVENT_LISTENER_CONFIG),
                    new Parameter().setType(genericType(Collection.class, DMNRuntimeEventListener.class)).setName(VAR_DMN_RUNTIME_EVENT_LISTENERS)
            ),
            body);
}
 
Example #2
Source File: RuleUnitInstanceGenerator.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
public ClassOrInterfaceDeclaration classDeclaration() {
    String canonicalName = ruleUnitDescription.getRuleUnitName();
    ClassOrInterfaceDeclaration classDecl = new ClassOrInterfaceDeclaration()
            .setName(targetTypeName)
            .addModifier(Modifier.Keyword.PUBLIC);
    classDecl
            .addExtendedType(
                    new ClassOrInterfaceType(null, AbstractRuleUnitInstance.class.getCanonicalName())
                            .setTypeArguments(new ClassOrInterfaceType(null, canonicalName)))
            .addConstructor(Modifier.Keyword.PUBLIC)
            .addParameter(RuleUnitGenerator.ruleUnitType(canonicalName), "unit")
            .addParameter(canonicalName, "value")
            .addParameter(KieSession.class.getCanonicalName(), "session")
            .setBody(new BlockStmt().addStatement(new MethodCallExpr(
                    "super",
                    new NameExpr("unit"),
                    new NameExpr("value"),
                    new NameExpr("session")
            )));
    classDecl.addMember(bindMethod());
    classDecl.getMembers().sort(new BodyDeclarationComparator());
    return classDecl;
}
 
Example #3
Source File: ProcessConfigGenerator.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
private MethodDeclaration generateMergeEventListenerConfigMethod() {
    BlockStmt body = new BlockStmt().addStatement(new ReturnStmt(newObject(CachedProcessEventListenerConfig.class,
            callMerge(
                    VAR_PROCESS_EVENT_LISTENER_CONFIGS,
                    ProcessEventListenerConfig.class, "listeners",
                    VAR_PROCESS_EVENT_LISTENERS
            )
    )));

    return method(Modifier.Keyword.PRIVATE, ProcessEventListenerConfig.class, METHOD_MERGE_PROCESS_EVENT_LISTENER_CONFIG,
            NodeList.nodeList(
                    new Parameter().setType(genericType(Collection.class, ProcessEventListenerConfig.class)).setName(VAR_PROCESS_EVENT_LISTENER_CONFIGS),
                    new Parameter().setType(genericType(Collection.class, ProcessEventListener.class)).setName(VAR_PROCESS_EVENT_LISTENERS)
            ),
            body);
}
 
Example #4
Source File: LazyTest.java    From TestSmellDetector with GNU General Public License v3.0 6 votes vote down vote up
/**
 * The purpose of this method is to 'visit' all test methods.
 */
@Override
public void visit(MethodDeclaration n, Void arg) {
    // ensure that this method is only executed for the test file
    if (Objects.equals(fileType, TEST_FILE)) {
        if (Util.isValidTestMethod(n)) {
            currentMethod = n;
            testMethod = new TestMethod(currentMethod.getNameAsString());
            testMethod.setHasSmell(false); //default value is false (i.e. no smell)
            super.visit(n, arg);

            //reset values for next method
            currentMethod = null;
            productionVariables = new ArrayList<>();
        }
    } else { //collect a list of all public/protected members of the production class
        for (Modifier modifier : n.getModifiers()) {
            if (modifier.name().toLowerCase().equals("public") || modifier.name().toLowerCase().equals("protected")) {
                productionMethods.add(n);
            }
        }

    }
}
 
Example #5
Source File: IgnoredTest.java    From TestSmellDetector with GNU General Public License v3.0 6 votes vote down vote up
/**
 * The purpose of this method is to 'visit' all test methods in the test file.
 */
@Override
public void visit(MethodDeclaration n, Void arg) {

    //JUnit 4
    //check if test method has Ignore annotation
    if (n.getAnnotationByName("Test").isPresent()) {
        if (n.getAnnotationByName("Ignore").isPresent()) {
            testMethod = new TestMethod(n.getNameAsString());
            testMethod.setHasSmell(true);
            smellyElementList.add(testMethod);
            return;
        }
    }

    //JUnit 3
    //check if test method is not public
    if (n.getNameAsString().toLowerCase().startsWith("test")) {
        if (!n.getModifiers().contains(Modifier.PUBLIC)) {
            testMethod = new TestMethod(n.getNameAsString());
            testMethod.setHasSmell(true);
            smellyElementList.add(testMethod);
            return;
        }
    }
}
 
Example #6
Source File: ProcessesContainerGenerator.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
public ProcessesContainerGenerator(String packageName) {
    super("Processes", "processes", Processes.class);
    this.packageName = packageName;
    this.processes = new ArrayList<>();
    this.factoryMethods = new ArrayList<>();
    this.applicationDeclarations = new NodeList<>();

    byProcessIdMethodDeclaration = new MethodDeclaration()
            .addModifier(Modifier.Keyword.PUBLIC)
            .setName("processById")
            .setType(new ClassOrInterfaceType(null, org.kie.kogito.process.Process.class.getCanonicalName())
                             .setTypeArguments(new WildcardType(new ClassOrInterfaceType(null, Model.class.getCanonicalName()))))
            .setBody(new BlockStmt())
            .addParameter("String", "processId");

    processesMethodDeclaration = new MethodDeclaration()
            .addModifier(Modifier.Keyword.PUBLIC)
            .setName("processIds")
            .setType(new ClassOrInterfaceType(null, Collection.class.getCanonicalName())
                             .setTypeArguments(new ClassOrInterfaceType(null, "String")))
            .setBody(new BlockStmt());

    applicationDeclarations.add(byProcessIdMethodDeclaration);
    applicationDeclarations.add(processesMethodDeclaration);
}
 
Example #7
Source File: RuleConfigGenerator.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
public List<BodyDeclaration<?>> members() {

        if (annotator != null) {
            FieldDeclaration relcFieldDeclaration = annotator.withOptionalInjection(new FieldDeclaration().addVariable(new VariableDeclarator(genericType(annotator.multiInstanceInjectionType(), RuleEventListenerConfig.class), VAR_RULE_EVENT_LISTENER_CONFIGS)));
            members.add(relcFieldDeclaration);

            FieldDeclaration aelFieldDeclaration = annotator.withOptionalInjection(new FieldDeclaration().addVariable(new VariableDeclarator(genericType(annotator.multiInstanceInjectionType(), AgendaEventListener.class), VAR_AGENDA_EVENT_LISTENERS)));
            members.add(aelFieldDeclaration);

            FieldDeclaration rrelFieldDeclaration = annotator.withOptionalInjection(new FieldDeclaration().addVariable(new VariableDeclarator(genericType(annotator.multiInstanceInjectionType(), RuleRuntimeEventListener.class), VAR_RULE_RUNTIME_EVENT_LISTENERS)));
            members.add(rrelFieldDeclaration);

            members.add(generateExtractEventListenerConfigMethod());
            members.add(generateMergeEventListenerConfigMethod());
        } else {
            FieldDeclaration defaultRelcFieldDeclaration = new FieldDeclaration()
                    .setModifiers(Modifier.Keyword.PRIVATE)
                    .addVariable(new VariableDeclarator(new ClassOrInterfaceType(null, RuleEventListenerConfig.class.getCanonicalName()), VAR_DEFAULT_RULE_EVENT_LISTENER_CONFIG, newObject(DefaultRuleEventListenerConfig.class)));
            members.add(defaultRelcFieldDeclaration);
        }

        return members;
    }
 
Example #8
Source File: ProcessGenerator.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
private MethodDeclaration createInstanceGenericWithBusinessKeyMethod(String processInstanceFQCN) {
    MethodDeclaration methodDeclaration = new MethodDeclaration();

    ReturnStmt returnStmt = new ReturnStmt(
            new MethodCallExpr(new ThisExpr(), "createInstance")
            .addArgument(new NameExpr(BUSINESS_KEY))
            .addArgument(new CastExpr(new ClassOrInterfaceType(null, modelTypeName), new NameExpr("value"))));

    methodDeclaration.setName("createInstance")
            .addModifier(Modifier.Keyword.PUBLIC)
            .addParameter(String.class.getCanonicalName(), BUSINESS_KEY)
            .addParameter(Model.class.getCanonicalName(), "value")
            .setType(processInstanceFQCN)
            .setBody(new BlockStmt()
                             .addStatement(returnStmt));
    return methodDeclaration;
}
 
Example #9
Source File: ParameterNameVisitor.java    From meghanada-server with GNU General Public License v3.0 6 votes vote down vote up
private void getParameterNames(MethodDeclaration methodDeclaration, boolean isInterface) {
  NodeList<Modifier> modifiers = methodDeclaration.getModifiers();
  if (isInterface || modifiers.contains(Modifier.publicModifier())) {
    String methodName = methodDeclaration.getName().getIdentifier();
    List<Parameter> parameters = methodDeclaration.getParameters();
    names.className = this.className;
    List<List<ParameterName>> parameterNames =
        names.names.computeIfAbsent(methodName, k -> new ArrayList<>(4));

    final List<ParameterName> temp = new ArrayList<>(8);
    for (final Parameter parameter : parameters) {
      ParameterName parameterName = new ParameterName();
      String type = parameter.getType().toString();
      String name = parameter.getName().getIdentifier();
      if (name.contains("[]")) {
        type = type + "[]";
        name = COMPILE.matcher(name).replaceAll(Matcher.quoteReplacement(""));
      }
      parameterName.type = type;
      parameterName.name = name;
      temp.add(parameterName);
    }
    parameterNames.add(temp);
  }
}
 
Example #10
Source File: ProcessGenerator.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
private MethodDeclaration createInstanceWithBusinessKeyMethod(String processInstanceFQCN) {
    MethodDeclaration methodDeclaration = new MethodDeclaration();

    ReturnStmt returnStmt = new ReturnStmt(
            new ObjectCreationExpr()
                    .setType(processInstanceFQCN)
                    .setArguments(NodeList.nodeList(
                            new ThisExpr(),
                            new NameExpr("value"),
                            new NameExpr(BUSINESS_KEY),
                            createProcessRuntime())));

    methodDeclaration.setName("createInstance")
            .addModifier(Modifier.Keyword.PUBLIC)
            .addParameter(String.class.getCanonicalName(), BUSINESS_KEY)
            .addParameter(modelTypeName, "value")
            .setType(processInstanceFQCN)
            .setBody(new BlockStmt()
                             .addStatement(returnStmt));
    return methodDeclaration;
}
 
Example #11
Source File: ProcessGenerator.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
private MethodDeclaration createInstanceMethod(String processInstanceFQCN) {
    MethodDeclaration methodDeclaration = new MethodDeclaration();

    ReturnStmt returnStmt = new ReturnStmt(
            new ObjectCreationExpr()
                    .setType(processInstanceFQCN)
                    .setArguments(NodeList.nodeList(
                            new ThisExpr(),
                            new NameExpr("value"),
                            createProcessRuntime())));

    methodDeclaration.setName("createInstance")
            .addModifier(Modifier.Keyword.PUBLIC)
            .addParameter(modelTypeName, "value")
            .setType(processInstanceFQCN)
            .setBody(new BlockStmt()
                             .addStatement(returnStmt));
    return methodDeclaration;
}
 
Example #12
Source File: GroovydocJavaVisitor.java    From groovy with Apache License 2.0 6 votes vote down vote up
private SimpleGroovyClassDoc visit(TypeDeclaration<?> n) {
    SimpleGroovyClassDoc parent = null;
    List<String> imports = getImports();
    String name = n.getNameAsString();
    if (n.isNestedType()) {
        parent = currentClassDoc;
        name = parent.name() + "$" + name;
    }
    currentClassDoc = new SimpleGroovyClassDoc(imports, aliases, name.replace('$', '.'), links);
    NodeList<Modifier> mods = n.getModifiers();
    if (parent != null) {
        parent.addNested(currentClassDoc);
        if (parent.isInterface()) {
            // an inner interface/class within an interface is public
            mods.add(Modifier.publicModifier());
        }
    }
    setModifiers(mods, currentClassDoc);
    processAnnotations(currentClassDoc, n);
    currentClassDoc.setFullPathName(withSlashes(packagePath + FS + name));
    classDocs.put(currentClassDoc.getFullPathName(), currentClassDoc);
    n.getJavadocComment().ifPresent(javadocComment ->
            currentClassDoc.setRawCommentText(javadocComment.getContent()));
    return parent;
}
 
Example #13
Source File: GroovydocJavaVisitor.java    From groovy with Apache License 2.0 6 votes vote down vote up
private void setModifiers(NodeList<Modifier> modifiers, SimpleGroovyAbstractableElementDoc elementDoc) {
    if (modifiers.contains(Modifier.publicModifier())) {
        elementDoc.setPublic(true);
    }
    if (modifiers.contains(Modifier.staticModifier())) {
        elementDoc.setStatic(true);
    }
    if (modifiers.contains(Modifier.abstractModifier())) {
        elementDoc.setAbstract(true);
    }
    if (modifiers.contains(Modifier.finalModifier())) {
        elementDoc.setFinal(true);
    }
    if (modifiers.contains(Modifier.protectedModifier())) {
        elementDoc.setProtected(true);
    }
    if (modifiers.contains(Modifier.privateModifier())) {
        elementDoc.setPrivate(true);
    }
}
 
Example #14
Source File: ProcessInstanceGenerator.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
private MethodDeclaration unbind() {
    String modelName = model.getModelClassSimpleName();
    BlockStmt body = new BlockStmt()
            .addStatement(model.fromMap("variables", "vmap"));

    return new MethodDeclaration()
            .setModifiers(Modifier.Keyword.PROTECTED)
            .setName("unbind")
            .setType(new VoidType())
            .addParameter(modelName, "variables")
            .addParameter(new ClassOrInterfaceType()
                                  .setName("java.util.Map")
                                  .setTypeArguments(new ClassOrInterfaceType().setName("String"),
                                                    new ClassOrInterfaceType().setName("Object")),
                          "vmap")
            .setBody(body);
}
 
Example #15
Source File: GroovydocJavaVisitor.java    From groovy with Apache License 2.0 6 votes vote down vote up
private void setConstructorOrMethodCommon(CallableDeclaration<? extends CallableDeclaration<?>> n, SimpleGroovyExecutableMemberDoc methOrCons) {
    n.getJavadocComment().ifPresent(javadocComment ->
            methOrCons.setRawCommentText(javadocComment.getContent()));
    NodeList<Modifier> mods = n.getModifiers();
    if (currentClassDoc.isInterface()) {
        mods.add(Modifier.publicModifier());
    }
    setModifiers(mods, methOrCons);
    processAnnotations(methOrCons, n);
    for (Parameter param : n.getParameters()) {
        SimpleGroovyParameter p = new SimpleGroovyParameter(param.getNameAsString());
        processAnnotations(p, param);
        p.setType(makeType(param.getType()));
        methOrCons.add(p);
    }
}
 
Example #16
Source File: RuleConfigGenerator.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
private MethodDeclaration generateMergeEventListenerConfigMethod() {
    BlockStmt body = new BlockStmt().addStatement(new ReturnStmt(newObject(CachedRuleEventListenerConfig.class,
            callMerge(
                    VAR_RULE_EVENT_LISTENER_CONFIGS,
                    RuleEventListenerConfig.class, "agendaListeners",
                    VAR_AGENDA_EVENT_LISTENERS
            ),
            callMerge(
                    VAR_RULE_EVENT_LISTENER_CONFIGS,
                    RuleEventListenerConfig.class, "ruleRuntimeListeners",
                    VAR_RULE_RUNTIME_EVENT_LISTENERS
            )
    )));

    return method(Modifier.Keyword.PRIVATE, RuleEventListenerConfig.class, METHOD_MERGE_RULE_EVENT_LISTENER_CONFIG,
            NodeList.nodeList(
                    new Parameter().setType(genericType(Collection.class, RuleEventListenerConfig.class)).setName(VAR_RULE_EVENT_LISTENER_CONFIGS),
                    new Parameter().setType(genericType(Collection.class, AgendaEventListener.class)).setName(VAR_AGENDA_EVENT_LISTENERS),
                    new Parameter().setType(genericType(Collection.class, RuleRuntimeEventListener.class)).setName(VAR_RULE_RUNTIME_EVENT_LISTENERS)
            ),
            body);
}
 
Example #17
Source File: DecisionConfigGenerator.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
public List<BodyDeclaration<?>> members() {

        if (annotator != null) {
            FieldDeclaration delcFieldDeclaration = annotator.withOptionalInjection(new FieldDeclaration()
                    .addVariable(new VariableDeclarator(genericType(annotator.multiInstanceInjectionType(), DecisionEventListenerConfig.class), VAR_DECISION_EVENT_LISTENER_CONFIG)));
            members.add(delcFieldDeclaration);

            FieldDeclaration drelFieldDeclaration = annotator.withOptionalInjection(new FieldDeclaration()
                    .addVariable(new VariableDeclarator(genericType(annotator.multiInstanceInjectionType(), DMNRuntimeEventListener.class), VAR_DMN_RUNTIME_EVENT_LISTENERS)));
            members.add(drelFieldDeclaration);

            members.add(generateExtractEventListenerConfigMethod());
            members.add(generateMergeEventListenerConfigMethod());
        } else {
            FieldDeclaration defaultDelcFieldDeclaration = new FieldDeclaration()
                    .setModifiers(Modifier.Keyword.PRIVATE)
                    .addVariable(new VariableDeclarator(new ClassOrInterfaceType(null, DecisionEventListenerConfig.class.getCanonicalName()), VAR_DEFAULT_DECISION_EVENT_LISTENER_CONFIG, newObject(DefaultDecisionEventListenerConfig.class)));
            members.add(defaultDelcFieldDeclaration);
        }

        return members;
    }
 
Example #18
Source File: AbstractApplicationSection.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
public MethodDeclaration factoryMethod() {
    return new MethodDeclaration()
            .setModifiers(Modifier.Keyword.PUBLIC)
            .setType( sectionClassName )
            .setName(methodName)
            .setBody(new BlockStmt().addStatement(new ReturnStmt(new NameExpr(methodName))));
}
 
Example #19
Source File: ModelMetaData.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
private FieldDeclaration declareField(String name, String type) {
    return new FieldDeclaration().addVariable(
            new VariableDeclarator()
                    .setType(type)
                    .setName(name))
            .addModifier(Modifier.Keyword.PRIVATE);
}
 
Example #20
Source File: JavaClassBuilderImpl.java    From chrome-devtools-java-client with Apache License 2.0 5 votes vote down vote up
/**
 * Adds the private field of a given type to this class.
 *
 * @param name Field name.
 * @param type Field type.
 */
@Override
public void addPrivateField(String name, String type, String description) {
  String fieldName = getFieldName(name);
  declaration.addField(type, fieldName, Modifier.PRIVATE);
  fieldDescriptions.put(fieldName, description);
}
 
Example #21
Source File: ParseHelper.java    From genDoc with Apache License 2.0 5 votes vote down vote up
static List<String> parseModifiers(NodeWithModifiers<? extends Node> nodeWithModifiers) {

        EnumSet<Modifier> enumSet = nodeWithModifiers.getModifiers();

        if (enumSet != null && !enumSet.isEmpty()) {
            List<String> modifierList = new ArrayList<String>();
            for (Modifier modifier : enumSet) {
                modifierList.add(modifier.asString());
            }

            return modifierList;
        }

        return null;
    }
 
Example #22
Source File: EagerTest.java    From TestSmellDetector with GNU General Public License v3.0 5 votes vote down vote up
/**
 * The purpose of this method is to 'visit' all test methods.
 */
@Override
public void visit(MethodDeclaration n, Void arg) {
    // ensure that this method is only executed for the test file
    if (Objects.equals(fileType, TEST_FILE)) {
        if (Util.isValidTestMethod(n)) {
            currentMethod = n;
            testMethod = new TestMethod(currentMethod.getNameAsString());
            testMethod.setHasSmell(false); //default value is false (i.e. no smell)
            super.visit(n, arg);

            testMethod.setHasSmell(eagerCount > 1); //the method has a smell if there is more than 1 call to production methods
            smellyElementList.add(testMethod);

            //reset values for next method
            currentMethod = null;
            eagerCount = 0;
            productionVariables = new ArrayList<>();
            calledMethods = new ArrayList<>();
        }
    } else { //collect a list of all public/protected members of the production class
        for (Modifier modifier : n.getModifiers()) {
            if (modifier.name().toLowerCase().equals("public") || modifier.name().toLowerCase().equals("protected")) {
                productionMethods.add(n);
            }
        }

    }
}
 
Example #23
Source File: ReorderModifier.java    From Refactoring-Bot with MIT License 5 votes vote down vote up
/**
 * Reorder modifiers of a given field or method to comply with the JLS
 */
@Override
public String performRefactoring(BotIssue issue, GitConfiguration gitConfig) throws Exception {
	String filepath = gitConfig.getRepoFolder() + File.separator + issue.getFilePath();
	FileInputStream in = new FileInputStream(filepath);
	CompilationUnit compilationUnit = LexicalPreservingPrinter.setup(StaticJavaParser.parse(in));

	FieldDeclaration field = RefactoringHelper.getFieldDeclarationByLineNumber(issue.getLine(), compilationUnit);
	MethodDeclaration method = RefactoringHelper.getMethodDeclarationByLineNumber(issue.getLine(),
			compilationUnit);
	boolean isModifierListUnchanged = false;
	NodeList<Modifier> modifiersInCorrectOrder;
	if (field != null) {
		modifiersInCorrectOrder = getModifiersInCorrectOrder(field.getModifiers());
		isModifierListUnchanged = field.getModifiers().equals(modifiersInCorrectOrder);
		field.setModifiers(new NodeList<Modifier>());
		field.setModifiers(modifiersInCorrectOrder);
	} else if (method != null) {
		modifiersInCorrectOrder = getModifiersInCorrectOrder(method.getModifiers());
		isModifierListUnchanged = method.getModifiers().equals(modifiersInCorrectOrder);
		method.setModifiers(new NodeList<Modifier>());
		method.setModifiers(modifiersInCorrectOrder);
	} else {
		throw new BotRefactoringException("Could not find method or field declaration at the given line!");
	}

	if (isModifierListUnchanged) {
		throw new BotRefactoringException("All modifiers are in correct order! Nothing to refactor.");
	}

	// Save changes to file
	PrintWriter out = new PrintWriter(filepath);
	out.println(LexicalPreservingPrinter.print(compilationUnit));
	out.close();

	// Return commit message
	return "Reordered modifiers to comply with the Java Language Specification";
}
 
Example #24
Source File: ReorderModifiersTest.java    From Refactoring-Bot with MIT License 5 votes vote down vote up
private boolean assertAllModifiersInCorrectOrder(List<Modifier> modifiers) {
	// Following the JLS, this is the expected order:
	ArrayList<String> modifiersInCorrectOrder = new ArrayList<>();
	modifiersInCorrectOrder.add("public");
	modifiersInCorrectOrder.add("protected");
	modifiersInCorrectOrder.add("private");
	modifiersInCorrectOrder.add("abstract");
	modifiersInCorrectOrder.add("static");
	modifiersInCorrectOrder.add("final");
	modifiersInCorrectOrder.add("transient");
	modifiersInCorrectOrder.add("volatile");
	modifiersInCorrectOrder.add("synchronized");
	modifiersInCorrectOrder.add("native");
	modifiersInCorrectOrder.add("strictfp");

	int lastIndex = 0;
	String nameOfLastModifier = "";
	for (Modifier modifier : modifiers) {
		String modifierName = StringUtils.strip(modifier.toString());
		if (!modifiersInCorrectOrder.contains(modifierName)) {
			throw new IllegalArgumentException("Unknown modifier: " + modifierName);
		}
		int listIndexOfModifier = modifiersInCorrectOrder.indexOf(modifierName);
		if (lastIndex > listIndexOfModifier) {
			throw new AssertionError("Modifier '" + modifierName + "' is expected to be declared before modifier '"
					+ nameOfLastModifier + "'");
		}
		lastIndex = listIndexOfModifier;
		nameOfLastModifier = modifierName;
	}
	return true;
}
 
Example #25
Source File: Util.java    From TestSmellDetector with GNU General Public License v3.0 5 votes vote down vote up
public static boolean isValidTestMethod(MethodDeclaration n) {
    boolean valid = false;

    if (!n.getAnnotationByName("Ignore").isPresent()) {
        //only analyze methods that either have a @test annotation (Junit 4) or the method name starts with 'test'
        if (n.getAnnotationByName("Test").isPresent() || n.getNameAsString().toLowerCase().startsWith("test")) {
            //must be a public method
            if (n.getModifiers().contains(Modifier.PUBLIC)) {
                valid = true;
            }
        }
    }

    return valid;
}
 
Example #26
Source File: Util.java    From TestSmellDetector with GNU General Public License v3.0 5 votes vote down vote up
public static boolean isValidSetupMethod(MethodDeclaration n) {
    boolean valid = false;

    if (!n.getAnnotationByName("Ignore").isPresent()) {
        //only analyze methods that either have a @Before annotation (Junit 4) or the method name is 'setUp'
        if (n.getAnnotationByName("Before").isPresent() || n.getNameAsString().equals("setUp")) {
            //must be a public method
            if (n.getModifiers().contains(Modifier.PUBLIC)) {
                valid = true;
            }
        }
    }

    return valid;
}
 
Example #27
Source File: MigrateJCas.java    From uima-uimaj with Apache License 2.0 5 votes vote down vote up
private boolean hasTypeFields(NodeList<BodyDeclaration<?>> members) {
    boolean hasType = false;
    boolean hasTypeId = false;
    for (BodyDeclaration<?> bd : members) {
      if (bd instanceof FieldDeclaration) {
        FieldDeclaration f = (FieldDeclaration)bd;
        EnumSet<Modifier> m = f.getModifiers();
        if (m.contains(Modifier.PUBLIC) &&
            m.contains(Modifier.STATIC) &&
            m.contains(Modifier.FINAL) 
//            &&
//            getTypeName(f.getType()).equals("int")
            ) {
          List<VariableDeclarator> vds = f.getVariables();
          for (VariableDeclarator vd : vds) {
            if (vd.getType().equals(intType)) {
              String n = vd.getNameAsString();
              if (n.equals("type")) hasType = true;
              if (n.equals("typeIndexID")) hasTypeId = true;
              if (hasTypeId && hasType) {
                return true;
              }
            }
          }
        }
      }
    } // end of for
    return false;
  }
 
Example #28
Source File: ParameterNameVisitor.java    From meghanada-server with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void visit(ClassOrInterfaceDeclaration n, Object arg) {
  super.visit(n, arg);
  NodeList<Modifier> modifiers = n.getModifiers();
  if (!modifiers.contains(Modifier.privateModifier())) {
    final List<BodyDeclaration<?>> members = n.getMembers();
    final SimpleName simpleName = n.getName();
    final String clazz = simpleName.getId();
    // String clazz = n.getName();
    this.className = this.pkg + '.' + clazz;
    log.debug("class {}", this.className);
    int i = 0;
    for (final BodyDeclaration<?> body : members) {
      if (body instanceof MethodDeclaration) {
        MethodDeclaration methodDeclaration = (MethodDeclaration) body;
        this.getParameterNames(methodDeclaration, n.isInterface());
        i++;
      } else if (body instanceof ConstructorDeclaration) {
        // Constructor
      } else if (body instanceof ClassOrInterfaceDeclaration) {
        final ClassOrInterfaceDeclaration classOrInterfaceDeclaration =
            (ClassOrInterfaceDeclaration) body;
        String name = classOrInterfaceDeclaration.getName().getIdentifier();
        String key = this.pkg + '.' + name;
        name = this.originClassName + '.' + name;
        for (MethodParameterNames mpn : this.parameterNamesList) {
          if (mpn != null && mpn.className != null && mpn.className.equals(key)) {
            mpn.className = name;
          }
        }
      }
    }

    if (i > 0 && this.names.className != null) {
      this.parameterNamesList.add(this.names);
      this.names = new MethodParameterNames();
    }
  }
}
 
Example #29
Source File: TypeIndexer.java    From jql with MIT License 5 votes vote down vote up
public void index(TypeDeclaration<?> type, int cuId) {
    EnumSet<Modifier> modifiers = type.getModifiers();
    boolean isInterface = type instanceof ClassOrInterfaceDeclaration && ((ClassOrInterfaceDeclaration) type).isInterface();
    boolean isAnnotation = type instanceof AnnotationDeclaration;
    boolean isEnumeration = type instanceof EnumDeclaration;
    boolean isClass = !isAnnotation && !isEnumeration && !isInterface;
    
    Type t = new Type(type.getNameAsString(), type.isPublic(), type.isStatic(), modifiers.contains(FINAL), modifiers.contains(ABSTRACT), isClass, isInterface, isEnumeration, isAnnotation, cuId);
    int typeId = typeDao.save(t);

    for (BodyDeclaration member : type.getMembers()) {
        bodyDeclarationIndexer.index(member, typeId);
    }
}
 
Example #30
Source File: ConfigurableEagerTest.java    From CodeDefenders with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * The purpose of this method is to 'visit' all test methods.
 */
@Override
public void visit(MethodDeclaration n, Void arg) {
    // ensure that this method is only executed for the test file
    if (Objects.equals(fileType, TEST_FILE)) {
        if (Util.isValidTestMethod(n)) {
            currentMethod = n;
            testMethod = new TestMethod(currentMethod.getNameAsString());
            testMethod.setHasSmell(false); // default value is false
                                           // (i.e. no smell)
            super.visit(n, arg);

            /*
             * the method has a smell if there is more than threshold calls to
             * production methods (not considering the ones inside assertions!)
             */

            testMethod.setHasSmell(eagerCount > threshold);
            smellyElementList.add(testMethod);

            // reset values for next method
            currentMethod = null;
            eagerCount = 0;
            productionVariables = new ArrayList<>();
            calledMethods = new ArrayList<>();
        }
    } else { // collect a list of all public/protected members of the
             // production class
        for (Modifier modifier : n.getModifiers()) {
            if (modifier.name().toLowerCase().equals("public")
                    || modifier.name().toLowerCase().equals("protected")) {
                productionMethods.add(n);
            }
        }

    }
}