All Downloads are FREE. Search and download functionalities are using the official Maven repository.

net.serenitybdd.screenplay.QuestionSubject Maven / Gradle / Ivy

There is a newer version: 1.1.26-rc.1
Show newest version
package net.serenitybdd.screenplay;

import com.google.common.base.Optional;
import net.serenitybdd.screenplay.annotations.AnnotatedTitle;
import net.serenitybdd.screenplay.annotations.Subject;

import java.lang.reflect.Method;

import static net.thucydides.core.util.NameConverter.humanize;
import static org.apache.commons.lang3.StringUtils.lowerCase;

public class QuestionSubject {

    private final Class questionClass;
    private Question question;

    @SuppressWarnings("unchecked")
    public static  QuestionSubject fromClass(Class questionClass) {
        return new QuestionSubject(questionClass);
    }

    public QuestionSubject(Class questionClass) {
        this.questionClass = Uninstrumented.versionOf(questionClass);
    }

    public QuestionSubject andQuestion(Question question) {
        this.question = question;
        return this;
    }

    private Optional annotatedSubject() {
        if (annotationOnMethodOf(questionClass).isPresent()) {
            return Optional.of(annotationOnMethodOf(questionClass)).get();
        }
        if (questionClass.getAnnotation(Subject.class) != null) {
            //return Optional.of(questionClass.getAnnotation(Subject.class).value());
            return Optional.of(annotationOnClass(questionClass)).get();
        }
        return Optional.absent();
    }

    private Optional annotationOnMethodOf(Class questionClass) {
        try {
            Method answeredBy = questionClass.getMethod("answeredBy", Actor.class);
            if (answeredBy.getAnnotation(Subject.class) != null) {
                String annotatedTitle = answeredBy.getAnnotation(Subject.class).value();
                annotatedTitle = AnnotatedTitle.injectFieldsInto(annotatedTitle).using(question);
                return Optional.of(annotatedTitle);
            }
        } catch (NoSuchMethodException e) {
            return Optional.absent();
        }
        return Optional.absent();
    }

    private Optional annotationOnClass(Class questionClass) {
        if (questionClass.getAnnotation(Subject.class) != null) {
            String annotatedTitle = questionClass.getAnnotation(Subject.class).value();
            annotatedTitle = AnnotatedTitle.injectFieldsInto(annotatedTitle).using(question);
            return Optional.of(annotatedTitle);
        }
        return Optional.absent();
    }

    public String subject() {
        return annotatedSubject().or(lowerCase(humanize(questionClass.getSimpleName())));
    }

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy