001package ball.annotation.processing;
002/*-
003 * ##########################################################################
004 * Utilities
005 * $Id: SerializableProcessor.java 6081 2020-06-02 02:58:25Z ball $
006 * $HeadURL: svn+ssh://svn.hcf.dev/var/spool/scm/repository.svn/ball-util/trunk/src/main/java/ball/annotation/processing/SerializableProcessor.java $
007 * %%
008 * Copyright (C) 2008 - 2020 Allen D. Ball
009 * %%
010 * Licensed under the Apache License, Version 2.0 (the "License");
011 * you may not use this file except in compliance with the License.
012 * You may obtain a copy of the License at
013 *
014 *      http://www.apache.org/licenses/LICENSE-2.0
015 *
016 * Unless required by applicable law or agreed to in writing, software
017 * distributed under the License is distributed on an "AS IS" BASIS,
018 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
019 * See the License for the specific language governing permissions and
020 * limitations under the License.
021 * ##########################################################################
022 */
023import ball.annotation.ServiceProviderFor;
024import ball.tools.javac.AbstractTaskListener;
025import com.sun.source.util.TaskEvent;
026import java.io.ObjectStreamClass;
027import java.io.Serializable;
028import java.lang.reflect.Field;
029import java.util.Iterator;
030import java.util.Set;
031import java.util.TreeSet;
032import javax.annotation.processing.Processor;
033import javax.annotation.processing.RoundEnvironment;
034import javax.lang.model.element.Element;
035import javax.lang.model.element.TypeElement;
036import javax.lang.model.element.VariableElement;
037import lombok.NoArgsConstructor;
038import lombok.ToString;
039
040import static javax.lang.model.element.ElementKind.CLASS;
041import static javax.lang.model.util.ElementFilter.fieldsIn;
042import static javax.tools.Diagnostic.Kind.WARNING;
043
044/**
045 * {@link Processor} implementation to check subclasses of
046 * {@link Serializable} to verify a {@code serialVersionUID} field has been
047 * defined.
048 *
049 * @author {@link.uri mailto:ball@hcf.dev Allen D. Ball}
050 * @version $Revision: 6081 $
051 */
052@ServiceProviderFor({ Processor.class })
053@ForElementKinds({ CLASS })
054@ForSubclassesOf(Serializable.class)
055@NoArgsConstructor @ToString
056public class SerializableProcessor extends AnnotatedNoAnnotationProcessor {
057    private static abstract class PROTOTYPE {
058        private static final long serialVersionUID = 0L;
059    }
060
061    private static final Field PROTOTYPE =
062        PROTOTYPE.class.getDeclaredFields()[0];
063
064    private final Set<String> set = new TreeSet<>();
065
066    @Override
067    protected void whenAnnotationProcessingFinished() {
068        javac.addTaskListener(new TaskListenerImpl());
069    }
070
071    @Override
072    protected void process(RoundEnvironment roundEnv, Element element) {
073        TypeElement type = (TypeElement) element;
074        VariableElement field =
075            fieldsIn(type.getEnclosedElements())
076            .stream()
077            .filter(t -> t.getSimpleName().contentEquals(PROTOTYPE.getName()))
078            .findFirst().orElse(null);
079
080        if (! (field != null
081               && field.getModifiers().containsAll(getModifiers(PROTOTYPE))
082               && isAssignableTo(PROTOTYPE.getType()).test(field))) {
083            set.add(elements.getBinaryName(type).toString());
084        }
085    }
086
087    @NoArgsConstructor @ToString
088    private class TaskListenerImpl extends AbstractTaskListener {
089        @Override
090        public void finished(TaskEvent event) {
091            switch (event.getKind()) {
092            case GENERATE:
093                ClassLoader loader = getClassPathClassLoader(fm);
094                Iterator<String> iterator = set.iterator();
095
096                while (iterator.hasNext()) {
097                    String name = iterator.next();
098
099                    try {
100                        Class<?> cls = Class.forName(name, true, loader);
101                        long uid =
102                            ObjectStreamClass.lookup(cls)
103                            .getSerialVersionUID();
104                        TypeElement type =
105                            elements.getTypeElement(cls.getCanonicalName());
106
107                        print(WARNING, type,
108                              "%s %s has no definition of %s\n%s = %dL;",
109                              getForSubclassesOf().getSimpleName(),
110                              type.getKind(), PROTOTYPE.getName(),
111                              declaration(PROTOTYPE), uid);
112
113                        iterator.remove();
114                    } catch (ClassNotFoundException exception) {
115                        continue;
116                    } catch (NoClassDefFoundError error) {
117                        continue;
118                    } catch (Throwable throwable) {
119                        continue;
120                    }
121                }
122                break;
123
124            default:
125                break;
126            }
127        }
128    }
129}