Debian Codegraph @

src/main/java/com/jcabi/aspects/aj/ImmutabilityChecker.java

raw
1 /**
2 * Copyright (c) 2012-2017, jcabi.com
3 * All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
7 * are met: 1) Redistributions of source code must retain the above
8 * copyright notice, this list of conditions and the following
9 * disclaimer. 2) Redistributions in binary form must reproduce the above
10 * copyright notice, this list of conditions and the following
11 * disclaimer in the documentation and/or other materials provided
12 * with the distribution. 3) Neither the name of the jcabi.com nor
13 * the names of its contributors may be used to endorse or promote
14 * products derived from this software without specific prior written
15 * permission.
16 *
17 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
18 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT
19 * NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
20 * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
21 * THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
22 * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
23 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
24 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
25 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
26 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
27 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
28 * OF THE POSSIBILITY OF SUCH DAMAGE.
29 */
30 package com.jcabi.aspects.aj;
31
32 import com.jcabi.aspects.Immutable;
33 import com.jcabi.aspects.version.Version;
34 import com.jcabi.log.Logger;
35 import java.lang.reflect.Field;
36 import java.lang.reflect.Modifier;
37 import java.util.HashSet;
38 import java.util.Set;
39 import org.aspectj.lang.JoinPoint;
40 import org.aspectj.lang.annotation.After;
41 import org.aspectj.lang.annotation.Aspect;
42
43 /**
44 * Checks for class immutability.
45 *
46 * <p>The class is thread-safe.
47 *
48 * @author Yegor Bugayenko ([email protected])
49 * @version $Id: dd7be16f5f551933546416c4369e8cde37f39d1f $
50 * @since 0.7.8
51 */
52 @Aspect
53 public final class ImmutabilityChecker {
54
55 /**
56 * Already checked immutable classes.
57 */
58 private final transient Set<Class<?>> immutable = new HashSet<Class<?>>();
59
60 /**
61 * Catch instantiation and validate class.
62 *
63 * <p>Try NOT to change the signature of this method, in order to keep
64 * it backward compatible.
65 * @param point Joint point
66 */
67 @After("initialization((@com.jcabi.aspects.Immutable *).new(..))")
68 public void after(final JoinPoint point) {
69 final Class<?> type = point.getTarget().getClass();
70 try {
71 this.check(type);
72 } catch (final ImmutabilityChecker.Violation ex) {
73 throw new IllegalStateException(
74 String.format(
75 // @checkstyle LineLength (1 line)
76 "%s is not immutable, can't use it (jcabi-aspects %s/%s)",
77 type,
78 Version.CURRENT.projectVersion(),
79 Version.CURRENT.buildNumber()
80 ),
81 ex
82 );
83 }
84 }
85
86 /**
87 * This class is immutable?
88 * @param type The class to check
89 * @throws ImmutabilityChecker.Violation If it is mutable
90 */
91 private void check(final Class<?> type)
92 throws ImmutabilityChecker.Violation {
93 synchronized (this.immutable) {
94 if (!this.ignore(type)) {
95 if (type.isInterface()
96 && !type.isAnnotationPresent(Immutable.class)) {
97 throw new ImmutabilityChecker.Violation(
98 String.format(
99 "Interface '%s' is not annotated with @Immutable",
100 type.getName()
101 )
102 );
103 }
104 if (!type.isInterface()
105 && !Modifier.isFinal(type.getModifiers())) {
106 throw new Violation(
107 String.format(
108 "Class '%s' is not final",
109 type.getName()
110 )
111 );
112 }
113 try {
114 this.fields(type);
115 } catch (final ImmutabilityChecker.Violation ex) {
116 throw new ImmutabilityChecker.Violation(
117 String.format("Class '%s' is mutable", type.getName()),
118 ex
119 );
120 }
121 this.immutable.add(type);
122 Logger.debug(this, "#check(%s): immutability checked", type);
123 }
124 }
125 }
126
127 /**
128 * This class should be ignored and never checked any more?
129 * @param type The type to check
130 * @return TRUE if this class shouldn't be checked
131 */
132 private boolean ignore(final Class<?> type) {
133 // @checkstyle BooleanExpressionComplexity (5 lines)
134 return type.equals(Object.class)
135 || type.equals(String.class)
136 || type.isPrimitive()
137 || type.getName().startsWith("org.aspectj.runtime.reflect.")
138 || this.immutable.contains(type);
139 }
140
141 /**
142 * All its fields are safe?
143 * @param type Type to check
144 * @throws ImmutabilityChecker.Violation If it is mutable
145 */
146 private void fields(final Class<?> type)
147 throws ImmutabilityChecker.Violation {
148 final Field[] fields = type.getDeclaredFields();
149 for (int pos = 0; pos < fields.length; ++pos) {
150 final Field field = fields[pos];
151 if (Modifier.isStatic(field.getModifiers())) {
152 continue;
153 }
154 if (!Modifier.isFinal(field.getModifiers())) {
155 throw new ImmutabilityChecker.Violation(
156 String.format(
157 "field '%s' is not final in %s",
158 field, type.getName()
159 )
160 );
161 }
162 try {
163 if (field.getType().isArray()) {
164 this.checkArray(field);
165 }
166 } catch (final ImmutabilityChecker.Violation ex) {
167 throw new ImmutabilityChecker.Violation(
168 String.format(
169 "field '%s' is mutable",
170 field
171 ),
172 ex
173 );
174 }
175 }
176 }
177
178 /**
179 * This array field immutable?
180 * @param field The field to check
181 * @throws Violation If it is mutable.
182 */
183 private void checkArray(final Field field)
184 throws ImmutabilityChecker.Violation {
185 if (!field.isAnnotationPresent(Immutable.Array.class)) {
186 throw new ImmutabilityChecker.Violation(
187 String.format(
188 // @checkstyle LineLength (1 line)
189 "Field '%s' is an array and is not annotated with @Immutable.Array",
190 field.getName()
191 )
192 );
193 }
194 final Class<?> type = field.getType().getComponentType();
195 try {
196 this.check(type);
197 } catch (final ImmutabilityChecker.Violation ex) {
198 throw new ImmutabilityChecker.Violation(
199 String.format(
200 "Field array component type '%s' is mutable",
201 type.getName()
202 ),
203 ex
204 );
205 }
206 }
207
208 /**
209 * Immutability violation.
210 */
211 private static final class Violation extends Exception {
212 /**
213 * Serialization marker.
214 */
215 private static final long serialVersionUID = 1L;
216 /**
217 * Public ctor.
218 * @param msg Message
219 */
220 public Violation(final String msg) {
221 super(msg);
222 }
223 /**
224 * Public ctor.
225 * @param msg Message
226 * @param cause Cause of it
227 */
228 public Violation(final String msg, final Exception cause) {
229 super(msg, cause);
230 }
231 }
232
233 }