001package ball.annotation.processing;
002/*-
003 * ##########################################################################
004 * Utilities
005 * $Id: SerializableProcessor.java 7486 2021-02-15 00:02:29Z 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 - 2021 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: 7486 $
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    static { PROTOTYPE.setAccessible(true); }
065
066    private final Set<String> set = new TreeSet<>();
067
068    @Override
069    protected void whenAnnotationProcessingFinished() {
070        javac.addTaskListener(new TaskListenerImpl());
071    }
072
073    @Override
074    protected void process(RoundEnvironment roundEnv, Element element) {
075        TypeElement type = (TypeElement) element;
076        VariableElement field =
077            fieldsIn(type.getEnclosedElements())
078            .stream()
079            .filter(t -> t.getSimpleName().contentEquals(PROTOTYPE.getName()))
080            .findFirst().orElse(null);
081
082        if (! (field != null
083               && field.getModifiers().containsAll(getModifiers(PROTOTYPE))
084               && isAssignableTo(PROTOTYPE.getType()).test(field))) {
085            set.add(elements.getBinaryName(type).toString());
086        }
087    }
088
089    @NoArgsConstructor @ToString
090    private class TaskListenerImpl extends AbstractTaskListener {
091        @Override
092        public void finished(TaskEvent event) {
093            switch (event.getKind()) {
094            case GENERATE:
095                ClassLoader loader = getClassPathClassLoader(fm);
096                Iterator<String> iterator = set.iterator();
097
098                while (iterator.hasNext()) {
099                    String name = iterator.next();
100
101                    try {
102                        Class<?> cls = Class.forName(name, true, loader);
103                        long uid =
104                            ObjectStreamClass.lookup(cls)
105                            .getSerialVersionUID();
106                        TypeElement type =
107                            elements.getTypeElement(cls.getCanonicalName());
108
109                        print(WARNING, type,
110                              "%s %s has no definition of %s\n%s = %dL;",
111                              getForSubclassesOf().getSimpleName(),
112                              type.getKind(), PROTOTYPE.getName(),
113                              declaration(PROTOTYPE), uid);
114
115                        iterator.remove();
116                    } catch (ClassNotFoundException exception) {
117                        continue;
118                    } catch (NoClassDefFoundError error) {
119                        continue;
120                    } catch (Throwable throwable) {
121                        continue;
122                    }
123                }
124                break;
125
126            default:
127                break;
128            }
129        }
130    }
131}