Skip to content

Commit

Permalink
Fix quick win from code beat (#170)
Browse files Browse the repository at this point in the history
  • Loading branch information
boretti committed May 22, 2018
1 parent e47220a commit 3075997
Show file tree
Hide file tree
Showing 10 changed files with 198 additions and 35 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -22,14 +22,15 @@
import java.lang.annotation.Annotation;
import java.util.Optional;

import javax.annotation.processing.ProcessingEnvironment;
import javax.lang.model.element.Element;

/**
* @author borettim
*
*/
public abstract class AbstractElementMirror<E extends Element, A extends Annotation, R extends AbstractRoundMirrorReferenceToProcessingEnv>
implements AbstractRoundMirrorSupport<R>, ElementHelper {
implements AbstractRoundMirrorSupport<R>, ElementHelper, ProcessingEnvironmentHelper {

protected final R roundMirror;
protected final E element;
Expand All @@ -39,7 +40,7 @@ public abstract class AbstractElementMirror<E extends Element, A extends Annotat
public AbstractElementMirror(Class<A> annotationType, R roundMirror, E element) {
this.roundMirror = roundMirror;
this.element = element;
this.doc = Optional.ofNullable(roundMirror.getProcessingEnv().getElementUtils().getDocComment(element));
this.doc = Optional.ofNullable(roundMirror.getElementUtils().getDocComment(element));
this.annotation = Optional.ofNullable(element.getAnnotation(annotationType));
}

Expand All @@ -64,6 +65,11 @@ public String getParamComment() {
return doc.map(AbstractElementMirror::extractParamCommentFromJavadoc).orElse(" * \n");
}

@Override
public ProcessingEnvironment getProcessingEnv() {
return getRoundMirror().getProcessingEnv();
}

private static String extractParamCommentFromJavadoc(String docComment) {
boolean insideParam = false;
StringBuilder sb = new StringBuilder(" * \n");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,8 @@
* @author borettim
*
*/
public abstract class AbstractRoundMirrorReferenceToProcessingEnv implements ElementHelper {
public abstract class AbstractRoundMirrorReferenceToProcessingEnv
implements ElementHelper, ProcessingEnvironmentHelper {

protected final RoundEnvironment roundEnv;
protected final ProcessingEnvironment processingEnv;
Expand All @@ -40,9 +41,10 @@ public abstract class AbstractRoundMirrorReferenceToProcessingEnv implements Ele
public AbstractRoundMirrorReferenceToProcessingEnv(RoundEnvironment roundEnv, ProcessingEnvironment processingEnv) {
this.roundEnv = roundEnv;
this.processingEnv = processingEnv;
this.objectTypeMirror = getProcessingEnv().getElementUtils().getTypeElement("java.lang.Object").asType();
this.objectTypeMirror = getElementUtils().getTypeElement("java.lang.Object").asType();
}

@Override
public ProcessingEnvironment getProcessingEnv() {
return processingEnv;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,8 @@
*/
package ch.powerunit.extensions.matchers.common;

import java.time.Instant;

/**
* These are some method to manipulate java.
*
Expand Down Expand Up @@ -59,4 +61,9 @@ public static String addPrefix(String prefix, String input) {
.withPrefixAndSuffix("\n", "\n").asString(input.split("\\R"));
}

public static String generateGeneratedAnnotation(Class<?> generatedBy, String comments) {
return "@javax.annotation.Generated(value=\"" + generatedBy.getName() + "\",date=\"" + Instant.now().toString()
+ "\"" + (comments == null ? "" : (",comments=" + toJavaSyntax(comments))) + ")";
}

}
Original file line number Diff line number Diff line change
@@ -1,14 +1,16 @@
package ch.powerunit.extensions.matchers.common;

import static ch.powerunit.extensions.matchers.common.CommonUtils.generateGeneratedAnnotation;

import java.io.PrintWriter;
import java.time.Instant;
import java.util.function.Supplier;
import java.util.stream.Stream;

import javax.annotation.processing.AbstractProcessor;

/**
* These are some method to generate factory methods.
*
* @author borettim
*
*/
Expand All @@ -22,19 +24,18 @@ public static void generateFactoryClass(PrintWriter wjfo, Class<? extends Abstra
wjfo.println();
wjfo.println(CommonConstants.DEFAULT_JAVADOC_FOR_FACTORY);

wjfo.println("@javax.annotation.Generated(value=\"" + processor.getName() + "\",date=\""
+ Instant.now().toString() + "\")");
wjfo.println(generateGeneratedAnnotation(processor,null));
wjfo.println("public interface " + className + " {");
wjfo.println();
wjfo.println(generateStaticDSL(className));
wjfo.println();
bodyProvider.get().forEach(wjfo::println);
wjfo.println("}");
}

public static String generateStaticDSL(String className) {
return new StringBuilder().append(" /**").append("\n")
.append(" * Use this static field to access all the DSL syntax, without be required to implements this interface.")
return new StringBuilder().append(" /**").append("\n").append(
" * Use this static field to access all the DSL syntax, without be required to implements this interface.")
.append("\n").append(" */").append("\n")
.append(" public static final " + className + " DSL = new " + className + "() {};").append("\n")
.append("\n").toString();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,11 @@ public final class FileObjectHelper {
private FileObjectHelper() {
}

@FunctionalInterface
public static interface FunctionrWithException<S, R> {
R apply(S input) throws Exception;
}

@FunctionalInterface
public static interface ConsumerWithException<S> {
void accept(S input) throws Exception;
Expand All @@ -49,17 +54,26 @@ public static interface FunctionWithException<T, R> {
R apply(T input) throws Exception;
}

public static <T extends FileObject, S extends Closeable> boolean processFileWithIOException(
public static <T extends FileObject, S extends Closeable, R> R processFileWithIOExceptionAndResult(
SupplierWithException<T> generateFileObject, FunctionWithException<T, S> openStream,
ConsumerWithException<S> actions, Consumer<Exception> exceptionHandler) {
FunctionrWithException<S, R> actions, Consumer<Exception> exceptionHandler) {
try {
try (S wjfo = openStream.apply(generateFileObject.get())) {
actions.accept(wjfo);
return actions.apply(wjfo);
}
} catch (Exception e) {
exceptionHandler.accept(e);
return false;
return null;
}
return true;
}

public static <T extends FileObject, S extends Closeable> boolean processFileWithIOException(
SupplierWithException<T> generateFileObject, FunctionWithException<T, S> openStream,
ConsumerWithException<S> actions, Consumer<Exception> exceptionHandler) {
Boolean result = processFileWithIOExceptionAndResult(generateFileObject, openStream, s -> {
actions.accept(s);
return true;
}, exceptionHandler);
return Boolean.TRUE.equals(result);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
/**
* Powerunit - A JDK1.8 test framework
* Copyright (C) 2014 Mathieu Boretti.
*
* This file is part of Powerunit
*
* Powerunit is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Powerunit is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Powerunit. If not, see <http://www.gnu.org/licenses/>.
*/
package ch.powerunit.extensions.matchers.common;

import java.util.Locale;
import java.util.Map;

import javax.annotation.processing.Filer;
import javax.annotation.processing.Messager;
import javax.annotation.processing.ProcessingEnvironment;
import javax.lang.model.SourceVersion;
import javax.lang.model.util.Elements;
import javax.lang.model.util.Types;

@FunctionalInterface
public interface ProcessingEnvironmentHelper {
ProcessingEnvironment getProcessingEnv();

default Map<String, String> getOptions() {
return getProcessingEnv().getOptions();
}

default Messager getMessager() {
return getProcessingEnv().getMessager();
}

default Filer getFiler() {
return getProcessingEnv().getFiler();
}

default Elements getElementUtils() {
return getProcessingEnv().getElementUtils();
}

default Types getTypeUtils() {
return getProcessingEnv().getTypeUtils();
}

default SourceVersion getSourceVersion() {
return getProcessingEnv().getSourceVersion();
}

default Locale getLocale() {
return getProcessingEnv().getLocale();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -20,12 +20,13 @@
package ch.powerunit.extensions.matchers.provideprocessor;

import static ch.powerunit.extensions.matchers.common.CommonUtils.addPrefix;
import static ch.powerunit.extensions.matchers.common.CommonUtils.generateGeneratedAnnotation;
import static ch.powerunit.extensions.matchers.common.FileObjectHelper.processFileWithIOExceptionAndResult;
import static ch.powerunit.extensions.matchers.provideprocessor.dsl.DSLMethod.of;
import static java.util.Collections.unmodifiableList;
import static java.util.stream.Collectors.toList;

import java.io.PrintWriter;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
Expand All @@ -38,8 +39,6 @@
import javax.lang.model.element.TypeElement;
import javax.tools.Diagnostic.Kind;

import ch.powerunit.extensions.matchers.common.CommonUtils;
import ch.powerunit.extensions.matchers.common.FileObjectHelper;
import ch.powerunit.extensions.matchers.provideprocessor.dsl.DSLMethod;

public class ProvidesMatchersAnnotatedElementMirror extends ProvidesMatchersAnnotatedElementMatcherMirror {
Expand All @@ -55,8 +54,8 @@ public ProvidesMatchersAnnotatedElementMirror(TypeElement typeElement, RoundMirr
tmp.add(this::generateParentDSLStarter);
if (hasParentInSameRound) {
tmp.add(this::generateParentValueDSLStarter);
if (((TypeElement) roundMirror.getProcessingEnv().getTypeUtils().asElement(element.getSuperclass()))
.getTypeParameters().isEmpty()) {
if (((TypeElement) roundMirror.getTypeUtils().asElement(element.getSuperclass())).getTypeParameters()
.isEmpty()) {
tmp.add(this::generateParentInSameRoundWithChaningDSLStarter);
}
}
Expand All @@ -70,20 +69,16 @@ public ProvidesMatchersAnnotatedElementMirror(TypeElement typeElement, RoundMirr
}

public Collection<DSLMethod> process() {
RoundMirror rm = roundMirror;
Element te = element;
String simpleName = getSimpleNameOfGeneratedClass();
Collection<DSLMethod> results = new ArrayList<>();
FileObjectHelper.processFileWithIOException(
() -> rm.getProcessingEnv().getFiler().createSourceFile(getFullyQualifiedNameOfGeneratedClass(), te),
return processFileWithIOExceptionAndResult(
() -> getFiler().createSourceFile(getFullyQualifiedNameOfGeneratedClass(), te),
jfo -> new PrintWriter(jfo.openWriter()), wjfo -> {
wjfo.println("package " + getPackageNameOfGeneratedClass() + ";");
wjfo.println();
wjfo.println(generateMainJavaDoc());
wjfo.println("@javax.annotation.Generated(value=\""
+ ProvidesMatchersAnnotationsProcessor.class.getName() + "\",date=\""
+ Instant.now().toString() + "\",comments="
+ CommonUtils.toJavaSyntax(annotation.get().comments()) + ")");
wjfo.println(generateGeneratedAnnotation(ProvidesMatchersAnnotationsProcessor.class,
annotation.get().comments()));
wjfo.println("public final class " + simpleName + " {");
wjfo.println();
wjfo.println(" private " + simpleName + "() {}");
Expand All @@ -97,10 +92,9 @@ public Collection<DSLMethod> process() {
Collection<DSLMethod> tmp = generateDSLStarter();
tmp.stream().map(m -> addPrefix(" ", m.asStaticImplementation())).forEach(wjfo::println);
wjfo.println("}");
results.addAll(tmp);
}, e -> rm.getProcessingEnv().getMessager().printMessage(Kind.ERROR,
return tmp;
}, e -> getMessager().printMessage(Kind.ERROR,
"Unable to create the file containing the target class because of " + e, te));
return results;
}

public Collection<DSLMethod> generateDSLStarter() {
Expand Down Expand Up @@ -180,8 +174,7 @@ public DSLMethod generatParentValueDSLStarter(String argumentForParentBuilder) {

public ProvidesMatchersAnnotatedElementMirror getParentMirror() {
RoundMirror rm = roundMirror;
return rm.getByName(getQualifiedName(
((TypeElement) rm.getProcessingEnv().getTypeUtils().asElement(element.getSuperclass()))));
return rm.getByName(getQualifiedName(((TypeElement) rm.getTypeUtils().asElement(element.getSuperclass()))));
}

public DSLMethod generateParentValueDSLStarter() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -133,8 +133,8 @@ public boolean isInSameRound(Element t) {
public AnnotationMirror getProvideMatchersAnnotation(Element e) {
TypeMirror pmtm = processingEnv.getElementUtils()
.getTypeElement("ch.powerunit.extensions.matchers.ProvideMatchers").asType();
return getProcessingEnv().getElementUtils().getAllAnnotationMirrors(e).stream()
.filter(a -> a.getAnnotationType().equals(pmtm)).findAny().orElse(null);
return getElementUtils().getAllAnnotationMirrors(e).stream().filter(a -> a.getAnnotationType().equals(pmtm))
.findAny().orElse(null);
}

public Collection<Supplier<DSLMethod>> getDSLMethodFor(ProvidesMatchersAnnotatedElementData target) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,4 +16,14 @@ public void testAddPrefix() {
assertThatBiFunction(CommonUtils::addPrefix, " ", "x").is("\n x\n");
assertThatBiFunction(CommonUtils::addPrefix, " ", "x\ny").is("\n x\n y\n");
}

@Test(fastFail = false)
public void testGenerateGeneratedAnnotation() {
assertThatBiFunction(CommonUtils::generateGeneratedAnnotation, Object.class, null)
.is(both(containsString("@javax.annotation.Generated(value=\"java.lang.Object\",date"))
.and(not(containsString("comments"))));
assertThatBiFunction(CommonUtils::generateGeneratedAnnotation, Object.class, "x")
.is(both(containsString("@javax.annotation.Generated(value=\"java.lang.Object\",date"))
.and(containsString("comments=\"x\"")));
}
}

0 comments on commit 3075997

Please sign in to comment.