InternalClassTransformationImpl.java

Index Score
org.apache.tapestry.internal.services
Apache Tapestry 5

View: Reasons, Metrics, Source Code

These are the metrics that contribute to the Enerjy Score for this file, ranked by impact. So the metrics listed at the top influence the score to a greater extent that the metrics listed at the bottom.

MetricDescription
JAVA0034JAVA0034 Missing braces in if statement
EXITSProcedure exits
JAVA0251JAVA0251 Use '%n' for line breaks in printf/format for platform independence
LINE_COMMENTNumber of line comments
INTERFACE_COMPLEXITYInterface complexity
RETURNSNumber of return points from functions
LOCLines of code
WHITESPACENumber of whitespace lines
SIZESize of the file in bytes
LINESNumber of lines in the source file
LOGICAL_LINESNumber of statements
UNIQUE_OPERANDSNumber of unique operands
OPERANDSNumber of operands
CYCLOMATICCyclomatic complexity
PARAMSNumber of formal parameter declarations
PROGRAM_VOCABHalstead program vocabulary
PROGRAM_LENGTHHalstead program length
ELOCEffective lines of code
OPERATORSNumber of operators
FUNCTIONSNumber of function declarations
BLOCKSNumber of blocks
JAVA0020JAVA0020 Field name does not have required form
EXEC_COMMENTSComments in executable code
LOOPSNumber of loops
JAVA0108JAVA0108 Incorrect javadoc: no @param tag for 'parameter'
COMPARISONSNumber of comparison operators
DECL_COMMENTSComments in declarations
JAVA0130JAVA0130 Non-static method does not use instance fields
JAVA0035JAVA0035 Missing braces in for statement
JAVA0177JAVA0177 Variable declaration missing initializer
UNIQUE_OPERATORSNumber of unique operators
PROGRAM_VOLUMEHalstead program volume
JAVA0136JAVA0136 N methods defined in class (maximum: M)
JAVA0160JAVA0160 Method does not throw specified exception
JAVA0126JAVA0126 Method declares unchecked exception in throws
JAVA0100JAVA0100 Class contains N non-final fields (maximum: M)
NEST_DEPTHMaximum nesting depth
JAVA0110JAVA0110 Incorrect javadoc: no @return tag
JAVA0145JAVA0145 Tab character used in source file
// Copyright 2006, 2007 The Apache Software Foundation // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package org.apache.tapestry.internal.services; import javassist.*; import javassist.expr.ExprEditor; import javassist.expr.FieldAccess; import org.apache.tapestry.ComponentResources; import org.apache.tapestry.internal.InternalComponentResources; import org.apache.tapestry.internal.util.MultiKey; import org.apache.tapestry.ioc.internal.util.CollectionFactory; import static org.apache.tapestry.ioc.internal.util.CollectionFactory.*; import static org.apache.tapestry.ioc.internal.util.Defense.notBlank; import static org.apache.tapestry.ioc.internal.util.Defense.notNull; import org.apache.tapestry.ioc.internal.util.IdAllocator; import org.apache.tapestry.ioc.internal.util.InternalUtils; import org.apache.tapestry.model.ComponentModel; import org.apache.tapestry.runtime.Component; import org.apache.tapestry.services.FieldFilter; import org.apache.tapestry.services.MethodFilter; import org.apache.tapestry.services.TransformMethodSignature; import org.apache.tapestry.services.TransformUtils; import org.slf4j.Logger; import static java.lang.String.format; import java.lang.annotation.Annotation; import java.lang.reflect.Modifier; import java.util.*; /** * Implementation of the {@link org.apache.tapestry.internal.services.InternalClassTransformation} * interface. */ public final class InternalClassTransformationImpl implements InternalClassTransformation { private boolean _frozen; private final CtClass _ctClass; private final Logger _logger; private final InternalClassTransformation _parentTransformation; private ClassPool _classPool; private final IdAllocator _idAllocator; /** * Map, keyed on InjectKey, of field name. */ private final Map<MultiKey, String> _injectionCache = newMap(); /** * Map from a field to the annotation objects for that field. */ private Map<String, List<Annotation>> _fieldAnnotations = newMap(); /** * Used to identify fields that have been "claimed" by other annotations. */ private Map<String, Object> _claimedFields = newMap(); private Set<String> _addedFieldNames = newSet(); private Set<CtBehavior> _addedMethods = newSet(); // Cache of class annotations private List<Annotation> _classAnnotations; // Cache of method annotations private Map<CtMethod, List<Annotation>> _methodAnnotations = newMap(); private Map<CtMethod, TransformMethodSignature> _methodSignatures = newMap(); // Key is field name, value is expression used to replace read access private Map<String, String> _fieldReadTransforms; // Key is field name, value is expression used to replace read access private Map<String, String> _fieldWriteTransforms; private Set<String> _removedFieldNames; /** * Contains the assembled Javassist code for the class' default constructor. */ private StringBuilder _constructor = new StringBuilder(); private final List<ConstructorArg> _constructorArgs; private final ComponentModel _componentModel; private final String _resourcesFieldName; private final StringBuilder _description = new StringBuilder(); private Formatter _formatter = new Formatter(_description); private ClassLoader _loader; /** * This is a constructor for the root class, the class that directly contains the ComponentClass * annotation. */ public InternalClassTransformationImpl(CtClass ctClass, ClassLoader loader, Logger logger, ComponentModel componentModel) { _ctClass = ctClass; _classPool = _ctClass.getClassPool(); _loader = loader; _parentTransformation = null; _componentModel = componentModel; _idAllocator = new IdAllocator(); _logger = logger; preloadMemberNames(); _constructorArgs = newList(); _constructor.append("{\n"); addImplementedInterface(Component.class); _resourcesFieldName = addInjectedFieldUncached( InternalComponentResources.class, "resources", null); TransformMethodSignature sig = new TransformMethodSignature(Modifier.PUBLIC | Modifier.FINAL, ComponentResources.class.getName(), "getComponentResources", null, null); addMethod(sig, "return " + _resourcesFieldName + ";"); } public InternalClassTransformationImpl(CtClass ctClass, InternalClassTransformation parentTransformation, ClassLoader loader, Logger logger, ComponentModel componentModel) { _ctClass = ctClass; _classPool = _ctClass.getClassPool(); _loader = loader; _logger = logger; _parentTransformation = parentTransformation; _componentModel = componentModel; _resourcesFieldName = parentTransformation.getResourcesFieldName(); _idAllocator = parentTransformation.getIdAllocator(); preloadMemberNames(); verifyFields(); _constructorArgs = parentTransformation.getConstructorArgs(); int count = _constructorArgs.size(); // Build the call to the super-constructor. _constructor.append("{ super("); for (int i = 1; i <= count; i++) { if (i > 1) _constructor.append(", "); // $0 is implicitly self, so the 0-index ConstructorArg will be Javassisst // pseudeo-variable $1, and so forth. _constructor.append("$" + i); } _constructor.append(");\n"); // The "}" will be added later, inside } private void freeze() { _frozen = true; // Free up stuff we don't need after freezing. // Everything else should be final. _fieldAnnotations = null; _claimedFields = null; _addedFieldNames = null; _addedMethods = null; _classAnnotations = null; _methodAnnotations = null; _methodSignatures = null; _fieldReadTransforms = null; _fieldWriteTransforms = null; _removedFieldNames = null; _constructor = null; _formatter = null; _loader = null; // _ctClass = null; -- needed by toString() _classPool = null; } public String getResourcesFieldName() { return _resourcesFieldName; } /** * Loads the names of all declared fields and methods into the idAllocator. */ private void preloadMemberNames() { addMemberNames(_ctClass.getDeclaredFields()); addMemberNames(_ctClass.getDeclaredMethods()); } public void verifyFields() { List<String> names = newList(); for (CtField field : _ctClass.getDeclaredFields()) { String name = field.getName(); if (_addedFieldNames.contains(name)) continue; int modifiers = field.getModifiers(); // Fields must be either static or private. if (Modifier.isStatic(modifiers) || Modifier.isPrivate(modifiers)) continue; names.add(name); } if (!names.isEmpty()) { Collections.sort(names); _logger.error(ServicesMessages.nonPrivateFields(getClassName(), names)); } } private void addMemberNames(CtMember[] members) { for (CtMember member : members) { _idAllocator.allocateId(member.getName()); } } public <T extends Annotation> T getFieldAnnotation(String fieldName, Class<T> annotationClass) { failIfFrozen(); List<Annotation> annotations = findFieldAnnotations(fieldName); return findAnnotationInList(annotationClass, annotations); } public <T extends Annotation> T getMethodAnnotation(TransformMethodSignature signature, Class<T> annotationClass) { failIfFrozen(); CtMethod method = findMethod(signature); if (method == null) throw new IllegalArgumentException(ServicesMessages.noDeclaredMethod( _ctClass, signature)); List<Annotation> annotations = findMethodAnnotations(method); return findAnnotationInList(annotationClass, annotations); } /** * Searches an array of objects (that are really annotations instances) to find one that is of * the correct type, which is returned. * * @param <T> * @param annotationClass the annotation to search for * @param annotations the available annotations * @return the matching annotation instance, or null if not found */ private <T extends Annotation> T findAnnotationInList(Class<T> annotationClass, List<Annotation> annotations) { for (Object annotation : annotations) { if (annotationClass.isInstance(annotation)) return annotationClass.cast(annotation); } return null; } public <T extends Annotation> T getAnnotation(Class<T> annotationClass) { return findAnnotationInList(annotationClass, getClassAnnotations()); } private List<Annotation> findFieldAnnotations(String fieldName) { List<Annotation> annotations = _fieldAnnotations.get(fieldName); if (annotations == null) { annotations = findAnnotationsForField(fieldName); _fieldAnnotations.put(fieldName, annotations); } return annotations; } private List<Annotation> findMethodAnnotations(CtMethod method) { List<Annotation> annotations = _methodAnnotations.get(method); if (annotations == null) { annotations = extractAnnotations(method); _methodAnnotations.put(method, annotations); } return annotations; } private List<Annotation> findAnnotationsForField(String fieldName) { CtField field = findDeclaredCtField(fieldName); return extractAnnotations(field); } private List<Annotation> extractAnnotations(CtMember member) { try { List<Annotation> result = newList(); addAnnotationsToList(result, member.getAnnotations()); return result; } catch (ClassNotFoundException ex) { throw new RuntimeException(ex); } } private void addAnnotationsToList(List<Annotation> list, Object[] annotations) { for (Object o : annotations) { Annotation a = (Annotation) o; list.add(a); } } private CtField findDeclaredCtField(String fieldName) { try { return _ctClass.getDeclaredField(fieldName); } catch (NotFoundException ex) { throw new RuntimeException(ServicesMessages.missingDeclaredField(_ctClass, fieldName), ex); } } public String newMemberName(String suggested) { failIfFrozen(); String memberName = InternalUtils.createMemberName(notBlank(suggested, "suggested")); return _idAllocator.allocateId(memberName); } public String newMemberName(String prefix, String baseName) { return newMemberName(prefix + "_" + InternalUtils.stripMemberPrefix(baseName)); } public void addImplementedInterface(Class interfaceClass) { failIfFrozen(); String interfaceName = interfaceClass.getName(); try { CtClass ctInterface = _classPool.get(interfaceName); if (classImplementsInterface(ctInterface)) return; implementDefaultMethodsForInterface(ctInterface); _ctClass.addInterface(ctInterface); } catch (NotFoundException ex) { throw new RuntimeException(ex); } } /** * Adds default implementations for the methods defined by the interface (and all of its * super-interfaces). The implementations return null (or 0, or false, as appropriate to to the * method type). There are a number of degenerate cases that are not covered properly: these are * related to base interfaces that may be implemented by base classes. * * @param ctInterface * @throws NotFoundException */ private void implementDefaultMethodsForInterface(CtClass ctInterface) throws NotFoundException { // java.lang.Object is the parent interface of interfaces if (ctInterface.getName().equals(Object.class.getName())) return; for (CtMethod method : ctInterface.getDeclaredMethods()) { addDefaultImplementation(method); } for (CtClass parent : ctInterface.getInterfaces()) { implementDefaultMethodsForInterface(parent); } } private void addDefaultImplementation(CtMethod method) throws NotFoundException { // Javassist has an oddity for interfaces: methods "inherited" from java.lang.Object show // up as methods of the interface. We skip those and only consider the methods // that are abstract. if (!Modifier.isAbstract(method.getModifiers())) return; try { CtMethod newMethod = CtNewMethod.copy(method, _ctClass, null); // Methods from interfaces are always public. We definitely // need to change the modifiers of the method so that // it is not abstract. newMethod.setModifiers(Modifier.PUBLIC); // Javassist will provide a minimal implementation for us (return null, false, 0, // whatever). newMethod.setBody(null); _ctClass.addMethod(newMethod); TransformMethodSignature sig = getMethodSignature(newMethod); addMethodToDescription("add default", sig, "<default>"); } catch (CannotCompileException ex) { throw new RuntimeException(ServicesMessages.errorAddingMethod(_ctClass, method .getName(), ex), ex); } } /** * Check to see if the target class (or any of its super classes) implements the provided * interface. This is geared for simple interfaces (that don't extend other interfaces), thus if * the class (or a base class) implement interface Y that extends interface X, we may not return * true for interface X. */ private boolean classImplementsInterface(CtClass ctInterface) throws NotFoundException { for (CtClass current = _ctClass; current != null; current = current.getSuperclass()) { for (CtClass anInterface : current.getInterfaces()) { if (anInterface == ctInterface) return true; } } return false; } public void claimField(String fieldName, Object tag) { notBlank(fieldName, "fieldName"); notNull(tag, "tag"); failIfFrozen(); Object existing = _claimedFields.get(fieldName); if (existing != null) { String message = ServicesMessages.fieldAlreadyClaimed( fieldName, _ctClass, existing, tag); throw new RuntimeException(message); } // TODO: Ensure that fieldName is a known field? _claimedFields.put(fieldName, tag); } public void addMethod(TransformMethodSignature signature, String methodBody) { failIfFrozen(); CtClass returnType = findCtClass(signature.getReturnType()); CtClass[] parameters = buildCtClassList(signature.getParameterTypes()); CtClass[] exceptions = buildCtClassList(signature.getExceptionTypes()); String action = "add"; try { CtMethod existing = _ctClass.getDeclaredMethod(signature.getMethodName(), parameters); if (existing != null) { action = "replace"; _ctClass.removeMethod(existing); } } catch (NotFoundException ex) { // That's ok. Kind of sloppy to rely on a thrown exception; wish getDeclaredMethod() // would return null for // that case. Alternately, we could maintain a set of the method signatures of declared // or added methods. } try { CtMethod method = new CtMethod(returnType, signature.getMethodName(), parameters, _ctClass); // TODO: Check for duplicate method add method.setModifiers(signature.getModifiers()); method.setBody(methodBody); method.setExceptionTypes(exceptions); _ctClass.addMethod(method); _addedMethods.add(method); } catch (CannotCompileException ex) { throw new MethodCompileException(ServicesMessages.methodCompileError( signature, methodBody, ex), methodBody, ex); } catch (NotFoundException ex) { throw new RuntimeException(ex); } addMethodToDescription(action, signature, methodBody); } private CtClass[] buildCtClassList(String[] typeNames) { CtClass[] result = new CtClass[typeNames.length]; for (int i = 0; i < typeNames.length; i++) result[i] = findCtClass(typeNames[i]); return result; } private CtClass findCtClass(String type) { try { return _classPool.get(type); } catch (NotFoundException ex) { throw new RuntimeException(ex); } } public void extendMethod(TransformMethodSignature methodSignature, String methodBody) { failIfFrozen(); CtMethod method = findMethod(methodSignature); try { method.insertAfter(methodBody); } catch (CannotCompileException ex) { throw new MethodCompileException(ServicesMessages.methodCompileError( methodSignature, methodBody, ex), methodBody, ex); } addMethodToDescription("extend", methodSignature, methodBody); _addedMethods.add(method); } public void prefixMethod(TransformMethodSignature methodSignature, String methodBody) { failIfFrozen(); CtMethod method = findMethod(methodSignature); try { method.insertBefore(methodBody); } catch (CannotCompileException ex) { throw new MethodCompileException(ServicesMessages.methodCompileError( methodSignature, methodBody, ex), methodBody, ex); } addMethodToDescription("prefix", methodSignature, methodBody); _addedMethods.add(method); } private void addMethodToDescription(String operation, TransformMethodSignature methodSignature, String methodBody) { _formatter.format("%s method: %s %s %s(", operation, Modifier.toString(methodSignature .getModifiers()), methodSignature.getReturnType(), methodSignature.getMethodName()); String[] parameterTypes = methodSignature.getParameterTypes(); for (int i = 0; i < parameterTypes.length; i++) { if (i > 0) _description.append(", "); _formatter.format("%s $%d", parameterTypes[i], i + 1); } _description.append(")"); String[] exceptionTypes = methodSignature.getExceptionTypes(); for (int i = 0; i < exceptionTypes.length; i++) { if (i == 0) _description.append("\n throws "); else _description.append(", "); _description.append(exceptionTypes[i]); } _formatter.format("\n%s\n\n", methodBody); } private CtMethod findMethod(TransformMethodSignature methodSignature) { CtMethod method = findDeclaredMethod(methodSignature); if (method != null) return method; CtMethod result = addOverrideOfSuperclassMethod(methodSignature); if (result != null) return result; throw new IllegalArgumentException(ServicesMessages.noDeclaredMethod( _ctClass, methodSignature)); } private CtMethod findDeclaredMethod(TransformMethodSignature methodSignature) { for (CtMethod method : _ctClass.getDeclaredMethods()) { if (match(method, methodSignature)) return method; } return null; } private CtMethod addOverrideOfSuperclassMethod(TransformMethodSignature methodSignature) { try { for (CtClass current = _ctClass; current != null; current = current.getSuperclass()) { for (CtMethod method : current.getDeclaredMethods()) { if (match(method, methodSignature)) { // TODO: If the moethod is not overridable (i.e. private, or final)? // Perhaps we should limit it to just public methods. CtMethod newMethod = CtNewMethod.delegator(method, _ctClass); _ctClass.addMethod(newMethod); return newMethod; } } } } catch (NotFoundException ex) { throw new RuntimeException(ex); } catch (CannotCompileException ex) { throw new RuntimeException(ex); } // Not found in a super-class. return null; } private boolean match(CtMethod method, TransformMethodSignature sig) { if (!sig.getMethodName().equals(method.getName())) return false; CtClass[] paramTypes; try { paramTypes = method.getParameterTypes(); } catch (NotFoundException ex) { throw new RuntimeException(ex); } String[] sigTypes = sig.getParameterTypes(); int count = sigTypes.length; if (paramTypes.length != count) return false; for (int i = 0; i < count; i++) { String paramType = paramTypes[i].getName(); if (!paramType.equals(sigTypes[i])) return false; } // Ignore exceptions thrown and modifiers. // TODO: Validate a match on return type? return true; } public List<String> findFieldsWithAnnotation(final Class<? extends Annotation> annotationClass) { FieldFilter filter = new FieldFilter() { public boolean accept(String fieldName, String fieldType) { return getFieldAnnotation(fieldName, annotationClass) != null; } }; return findFields(filter); } public List<String> findFields(FieldFilter filter) { failIfFrozen(); List<String> result = newList(); try { for (CtField field : _ctClass.getDeclaredFields()) { if (!isInstanceField(field)) continue; String fieldName = field.getName(); if (_claimedFields.containsKey(fieldName)) continue; if (filter.accept(fieldName, field.getType().getName())) result.add(fieldName); } } catch (NotFoundException ex) { throw new RuntimeException(ex); } Collections.sort(result); return result; } public List<TransformMethodSignature> findMethodsWithAnnotation( Class<? extends Annotation> annotationClass) { failIfFrozen(); List<TransformMethodSignature> result = newList(); for (CtMethod method : _ctClass.getDeclaredMethods()) { List<Annotation> annotations = findMethodAnnotations(method); if (findAnnotationInList(annotationClass, annotations) != null) { TransformMethodSignature sig = getMethodSignature(method); result.add(sig); } } Collections.sort(result); return result; } public List<TransformMethodSignature> findMethods(MethodFilter filter) { notNull(filter, "filter"); List<TransformMethodSignature> result = newList(); for (CtMethod method : _ctClass.getDeclaredMethods()) { TransformMethodSignature sig = getMethodSignature(method); if (filter.accept(sig)) result.add(sig); } Collections.sort(result); return result; } private TransformMethodSignature getMethodSignature(CtMethod method) { TransformMethodSignature result = _methodSignatures.get(method); if (result == null) { try { String type = method.getReturnType().getName(); String[] parameters = toTypeNames(method.getParameterTypes()); String[] exceptions = toTypeNames(method.getExceptionTypes()); result = new TransformMethodSignature(method.getModifiers(), type, method.getName(), parameters, exceptions); _methodSignatures.put(method, result); } catch (NotFoundException ex) { throw new RuntimeException(ex); } } return result; } private String[] toTypeNames(CtClass[] types) { String[] result = new String[types.length]; for (int i = 0; i < types.length; i++) result[i] = types[i].getName(); return result; } public List<String> findUnclaimedFields() { failIfFrozen(); List<String> names = newList(); Set<String> skipped = newSet(); skipped.addAll(_claimedFields.keySet()); skipped.addAll(_addedFieldNames); if (_removedFieldNames != null) skipped.addAll(_removedFieldNames); for (CtField field : _ctClass.getDeclaredFields()) { if (!isInstanceField(field)) continue; String name = field.getName(); if (skipped.contains(name)) continue; // May need to add a filter to edit out explicitly added fields. names.add(name); } Collections.sort(names); return names; } private boolean isInstanceField(CtField field) { int modifiers = field.getModifiers(); return Modifier.isPrivate(modifiers) && !Modifier.isStatic(modifiers); } public String getFieldType(String fieldName) { failIfFrozen(); CtClass type = getFieldCtType(fieldName); return type.getName(); } public boolean isField(String fieldName) { failIfFrozen(); try { CtField field = _ctClass.getDeclaredField(fieldName); return isInstanceField(field); } catch (NotFoundException ex) { return false; } } public int getFieldModifiers(String fieldName) { failIfFrozen(); try { return _ctClass.getDeclaredField(fieldName).getModifiers(); } catch (NotFoundException ex) { throw new RuntimeException(ex); } } private CtClass getFieldCtType(String fieldName) { try { CtField field = _ctClass.getDeclaredField(fieldName); return field.getType(); } catch (NotFoundException ex) { throw new RuntimeException(ex); } } public String addField(int modifiers, String type, String suggestedName) { failIfFrozen(); String fieldName = newMemberName(suggestedName); try { CtClass ctType = convertNameToCtType(type); CtField field = new CtField(ctType, fieldName, _ctClass); field.setModifiers(modifiers); _ctClass.addField(field); } catch (NotFoundException ex) { throw new RuntimeException(ex); } catch (CannotCompileException ex) { throw new RuntimeException(ex); } _formatter .format("add field: %s %s %s;\n\n", Modifier.toString(modifiers), type, fieldName); _addedFieldNames.add(fieldName); return fieldName; } public String addInjectedField(Class type, String suggestedName, Object value) { notNull(type, "type"); failIfFrozen(); MultiKey key = new MultiKey(type, value); String fieldName = searchForPreviousInjection(key); if (fieldName != null) return fieldName; // TODO: Probably doesn't handle arrays and primitives. fieldName = addInjectedFieldUncached(type, suggestedName, value); // Remember the injection in-case this class, or a subclass, injects the value again. _injectionCache.put(key, fieldName); return fieldName; } /** * This is split out from {@link #addInjectedField(Class, String, Object)} to handle a special * case for the InternalComponentResources, which is null when "injected" (during the class * transformation) and is only determined when a component is actually instantiated. */ private String addInjectedFieldUncached(Class type, String suggestedName, Object value) { CtClass ctType; try { ctType = _classPool.get(type.getName()); } catch (NotFoundException ex) { throw new RuntimeException(ex); } String fieldName = addField( Modifier.PROTECTED | Modifier.FINAL, type.getName(), suggestedName); addInjectToConstructor(fieldName, ctType, value); return fieldName; } public String searchForPreviousInjection(MultiKey key) { String result = _injectionCache.get(key); if (result != null) return result; if (_parentTransformation != null) return _parentTransformation.searchForPreviousInjection(key); return null; } /** * Adds a parameter to the constructor for the class; the parameter is used to initialize the * value for a field. * * @param fieldName name of field to inject * @param fieldType Javassist type of the field (and corresponding parameter) * @param value the value to be injected (which will in unusual cases be null) */ private void addInjectToConstructor(String fieldName, CtClass fieldType, Object value) { _constructorArgs.add(new ConstructorArg(fieldType, value)); extendConstructor(format(" %s = $%d;", fieldName, _constructorArgs.size())); } public void injectField(String fieldName, Object value) { notNull(fieldName, "fieldName"); failIfFrozen(); CtClass type = getFieldCtType(fieldName); addInjectToConstructor(fieldName, type, value); makeReadOnly(fieldName); } private CtClass convertNameToCtType(String type) throws NotFoundException { return _classPool.get(type); } public void finish() { failIfFrozen(); performFieldTransformations(); addConstructor(); verifyFields(); freeze(); } private void addConstructor() { String initializer = _idAllocator.allocateId("initializer"); try { CtConstructor defaultConstructor = _ctClass.getConstructor("()V"); CtMethod initializerMethod = defaultConstructor.toMethod(initializer, _ctClass); _ctClass.addMethod(initializerMethod); } catch (Exception ex) { throw new RuntimeException(ex); } _formatter.format("convert default constructor: %s();\n\n", initializer); int count = _constructorArgs.size(); CtClass[] types = new CtClass[count]; for (int i = 0; i < count; i++) { ConstructorArg arg = _constructorArgs.get(i); types[i] = arg.getType(); } // Add a call to the initializer; the method converted fromt the classes default // constructor. _constructor.append(" "); _constructor.append(initializer); // This finally matches the "{" added inside the constructor _constructor.append("();\n\n}"); String constructorBody = _constructor.toString(); try { CtConstructor cons = CtNewConstructor.make(types, null, constructorBody, _ctClass); _ctClass.addConstructor(cons); } catch (CannotCompileException ex) { throw new RuntimeException(ex); } _formatter.format("add constructor: %s(", _ctClass.getName()); for (int i = 0; i < count; i++) { if (i > 0) _description.append(", "); _formatter.format("%s $%d", types[i].getName(), i + 1); } _formatter.format(")\n%s\n\n", constructorBody); } public Instantiator createInstantiator(Class componentClass) { String className = _ctClass.getName(); if (!className.equals(componentClass.getName())) throw new IllegalArgumentException(ServicesMessages.incorrectClassForInstantiator( className, componentClass)); Object[] parameters = new Object[_constructorArgs.size()]; // Skip the first constructor argument, it's always a placeholder // for the InternalComponentResources instance that's provided // later. for (int i = 1; i < _constructorArgs.size(); i++) { parameters[i] = _constructorArgs.get(i).getValue(); } return new ReflectiveInstantiator(_componentModel, componentClass, parameters); } private void failIfFrozen() { if (_frozen) throw new IllegalStateException("The ClassTransformation instance (for " + _ctClass.getName() + ") has completed all transformations and may not be further modified."); } private void failIfNotFrozen() { if (!_frozen) throw new IllegalStateException("The ClassTransformation instance (for " + _ctClass.getName() + ") has not yet completed all transformations."); } public IdAllocator getIdAllocator() { failIfNotFrozen(); return _idAllocator; } public List<ConstructorArg> getConstructorArgs() { failIfNotFrozen(); return CollectionFactory.newList(_constructorArgs); } public List<Annotation> getClassAnnotations() { failIfFrozen(); if (_classAnnotations == null) assembleClassAnnotations(); return _classAnnotations; } private void assembleClassAnnotations() { _classAnnotations = newList(); try { for (CtClass current = _ctClass; current != null; current = current.getSuperclass()) { addAnnotationsToList(_classAnnotations, current.getAnnotations()); } } catch (NotFoundException ex) { throw new RuntimeException(ex); } catch (ClassNotFoundException ex) { throw new RuntimeException(ex); } } @Override public String toString() { StringBuilder builder = new StringBuilder("InternalClassTransformation[\n"); try { Formatter formatter = new Formatter(builder); formatter.format( "%s %s extends %s", Modifier.toString(_ctClass.getModifiers()), _ctClass.getName(), _ctClass.getSuperclass().getName()); CtClass[] interfaces = _ctClass.getInterfaces(); for (int i = 0; i < interfaces.length; i++) { if (i == 0) builder.append("\n implements "); else builder.append(", "); builder.append(interfaces[i].getName()); } formatter.format("\n\n%s", _description.toString()); } catch (NotFoundException ex) { builder.append(ex); } builder.append("]"); return builder.toString(); } public void makeReadOnly(String fieldName) { String methodName = newMemberName("write", fieldName); String fieldType = getFieldType(fieldName); TransformMethodSignature sig = new TransformMethodSignature(Modifier.PRIVATE, "void", methodName, new String[] {fieldType}, null); String message = ServicesMessages.readOnlyField(_ctClass.getName(), fieldName); String body = format("throw new java.lang.RuntimeException(\"%s\");", message); addMethod(sig, body); replaceWriteAccess(fieldName, methodName); } public void removeField(String fieldName) { _formatter.format("remove field %s;\n\n", fieldName); // TODO: We could check that there's an existing field read and field write transform ... if (_removedFieldNames == null) _removedFieldNames = newSet(); _removedFieldNames.add(fieldName); } public void replaceReadAccess(String fieldName, String methodName) { // Explicitly reference $0 (aka "this") because of TAPESTRY-1511. // $0 is valid even inside a static method. String body = String.format("$_ = $0.%s();", methodName); if (_fieldReadTransforms == null) _fieldReadTransforms = newMap(); // TODO: Collisions? _fieldReadTransforms.put(fieldName, body); _formatter.format("replace read %s: %s();\n\n", fieldName, methodName); } public void replaceWriteAccess(String fieldName, String methodName) { // Explicitly reference $0 (aka "this") because of TAPESTRY-1511. // $0 is valid even inside a static method. String body = String.format("$0.%s($1);", methodName); if (_fieldWriteTransforms == null) _fieldWriteTransforms = newMap(); // TODO: Collisions? _fieldWriteTransforms.put(fieldName, body); _formatter.format("replace write %s: %s();\n\n", fieldName, methodName); } private void performFieldTransformations() { // If no field transformations have been requested, then we can save ourselves some // trouble! if (_fieldReadTransforms != null || _fieldWriteTransforms != null) replaceFieldAccess(); if (_removedFieldNames != null) { for (String fieldName : _removedFieldNames) { try { CtField field = _ctClass.getDeclaredField(fieldName); _ctClass.removeField(field); } catch (NotFoundException ex) { throw new RuntimeException(ex); } } } } static final int SYNTHETIC = 0x00001000; private void replaceFieldAccess() { // Provide empty maps here, to make the code in the inner class a tad // easier. if (_fieldReadTransforms == null) _fieldReadTransforms = newMap(); if (_fieldWriteTransforms == null) _fieldWriteTransforms = newMap(); ExprEditor editor = new ExprEditor() { @Override public void edit(FieldAccess access) throws CannotCompileException { // Ignore any methods to were added as part of the transformation. // If we reference the field there, we really mean the field. if (_addedMethods.contains(access.where())) return; Map<String, String> transformMap = access.isReader() ? _fieldReadTransforms : _fieldWriteTransforms; String body = transformMap.get(access.getFieldName()); if (body == null) return; access.replace(body); } }; try { _ctClass.instrument(editor); } catch (CannotCompileException ex) { throw new RuntimeException(ex); } } public Class toClass(String type) { failIfFrozen(); // No reason why this can't be allowed to work after freezing. String finalType = TransformUtils.getWrapperTypeName(type); try { return Class.forName(finalType, true, _loader); } catch (ClassNotFoundException ex) { throw new RuntimeException(ex); } } public String getClassName() { return _ctClass.getName(); } public Logger getLogger() { return _logger; } public void extendConstructor(String statement) { notNull(statement, "statement"); failIfFrozen(); _constructor.append(statement); _constructor.append("\n"); } public String getMethodIdentifier(TransformMethodSignature signature) { notNull(signature, "signature"); CtMethod method = findMethod(signature); int lineNumber = method.getMethodInfo2().getLineNumber(0); CtClass enclosingClass = method.getDeclaringClass(); String sourceFile = enclosingClass.getClassFile2().getSourceFile(); return format("%s.%s (at %s:%d)", enclosingClass.getName(), signature .getMediumDescription(), sourceFile, lineNumber); } }

The table below shows all metrics for InternalClassTransformationImpl.java.

MetricValueDescription
BLOCKS164.00Number of blocks
BLOCK_COMMENT 0.00Number of block comment lines
COMMENTS128.00Comment lines
COMMENT_DENSITY 0.19Comment density
COMPARISONS70.00Number of comparison operators
CYCLOMATIC172.00Cyclomatic complexity
DECL_COMMENTS29.00Comments in declarations
DOC_COMMENT60.00Number of javadoc comment lines
ELOC668.00Effective lines of code
EXEC_COMMENTS31.00Comments in executable code
EXITS198.00Procedure exits
FUNCTIONS76.00Number of function declarations
HALSTEAD_DIFFICULTY 0.25Halstead difficulty
HALSTEAD_EFFORT 0.00Halstead effort
INTERFACE_COMPLEXITY220.00Interface complexity
JAVA0001 0.00JAVA0001 Package name does not contain only lower case letters
JAVA0002 0.00JAVA0002 Package name does not begin with a top level domain name or country code
JAVA0003 0.00JAVA0003 Minimize use of on-demand (.*) imports
JAVA0004 0.00JAVA0004 Unnecessary import from java.lang
JAVA0005 1.00JAVA0005 Imports not in specified order
JAVA0006 0.00JAVA0006 Empty finally block
JAVA0007 0.00JAVA0007 Should not declare public field
JAVA0008 0.00JAVA0008 Empty catch block
JAVA0009 0.00JAVA0009 Protected member in final class
JAVA0010 0.00JAVA0010 Non-instantiable class does not contain a non-private static member
JAVA0011 0.00JAVA0011 Abstract class does not contain an abstract method
JAVA0012 0.00JAVA0012 Non-constructor method with same name as declaring class
JAVA0013 0.00JAVA0013 Non-blank final field is not static
JAVA0014 0.00JAVA0014 Class with only static members has non-private constructor
JAVA0015 0.00JAVA0015 Package class contains public nested type
JAVA0016 0.00JAVA0016 Abstract class contains public constructor
JAVA0017 0.00JAVA0017 Class name does not have required form
JAVA0018 0.00JAVA0018 Method name does not have required form
JAVA0019 0.00JAVA0019 Interface name does not have required form
JAVA002015.00JAVA0020 Field name does not have required form
JAVA0021 0.00JAVA0021 Interface method name does not have required form
JAVA0022 0.00JAVA0022 Static final field name does not have required form
JAVA0023 0.00JAVA0023 Empty finalize method
JAVA0024 0.00JAVA0024 Empty class
JAVA0025 0.00JAVA0025 Method override is empty
JAVA0026 0.00JAVA0026 Finalize method with parameters
JAVA0029 0.00JAVA0029 Private method not used
JAVA0030 0.00JAVA0030 Private field not used
JAVA0031 0.00JAVA0031 Case statement not properly closed
JAVA0032 0.00JAVA0032 Switch statement missing default
JAVA0033 0.00JAVA0033 default: not last case in switch statement
JAVA003443.00JAVA0034 Missing braces in if statement
JAVA0035 2.00JAVA0035 Missing braces in for statement
JAVA0036 0.00JAVA0036 Missing braces in while statement
JAVA0038 0.00JAVA0038 Non-case label in switch statement
JAVA0039 0.00JAVA0039 Break statement with label
JAVA0040 0.00JAVA0040 Switch statement contains N cases (maximum: M)
JAVA0041 0.00JAVA0041 Nested synchronized block
JAVA0042 0.00JAVA0042 Empty synchronized statement
JAVA0043 0.00JAVA0043 Inner class does not use outer class
JAVA0044 0.00JAVA0044 Serializable class with no instance variables
JAVA0045 0.00JAVA0045 Serializable class with only transient fields
JAVA0046 0.00JAVA0046 Name of class not derived from Exception ends with 'Exception'
JAVA0047 0.00JAVA0047 Serializable class derives from invalid base class
JAVA0048 0.00JAVA0048 Name of class derived from Exception does not end with 'Exception'
JAVA0049 0.00JAVA0049 Nested block at depth N (maximum: M)
JAVA0050 0.00JAVA0050 Class derives from java.lang.Error
JAVA0051 0.00JAVA0051 Class derives from java.lang.RuntimeException
JAVA0052 0.00JAVA0052 Class derives from java.lang.Throwable
JAVA0053 0.00JAVA0053 Unused label
JAVA0054 0.00JAVA0054 Inheritance depth N exceeds maximum M
JAVA0055 0.00JAVA0055 Class should be interface
JAVA0056 0.00JAVA0056 Unnecessary abstract modifier for interface or annotation
JAVA0057 0.00JAVA0057 Unnecessary default constructor
JAVA0058 0.00JAVA0058 Constructor calls super()
JAVA0059 0.00JAVA0059 Method override only calls super()
JAVA0061 0.00JAVA0061 Inaccessible member in anonymous class
JAVA0062 0.00JAVA0062 Public class missing public member or protected constructor
JAVA0063 0.00JAVA0063 Identifier name should not contain '$'
JAVA0064 0.00JAVA0064 N variations of identifier name (maximum: M)
JAVA0065 0.00JAVA0065 Unnecessary final modifier for method in final class
JAVA0066 0.00JAVA0066 Unnecessary modifier for interface nested type
JAVA0067 0.00JAVA0067 Array descriptor on identifier name
JAVA0068 0.00JAVA0068 Modifiers not declared in recommended order
JAVA0071 0.00JAVA0071 Strings compared with ==
JAVA0073 0.00JAVA0073 Integer division in floating-point context
JAVA0074 0.00JAVA0074 Use of Object.notify()
JAVA0075 0.00JAVA0075 Method parameter hides field
JAVA0076 0.00JAVA0076 Use of magic number
JAVA0077 0.00JAVA0077 Private field not used in declaring class
JAVA0078 0.00JAVA0078 Floating point values compared with ==
JAVA0079 0.00JAVA0079 Use of instance to reference static member
JAVA0080 0.00JAVA0080 Import declaration not used
JAVA0081 0.00JAVA0081 Boolean literal in comparison
JAVA0082 0.00JAVA0082 Unnecessary widening cast
JAVA0083 0.00JAVA0083 Unnecessary instanceof test
JAVA0084 0.00JAVA0084 Should use compound assignment operator
JAVA0085 0.00JAVA0085 Use of sun.* class
JAVA0087 0.00JAVA0087 Use of Thread.sleep()
JAVA0089 0.00JAVA0089 Use of restricted package
JAVA0092 0.00JAVA0092 Use of restricted type
JAVA0093 0.00JAVA0093 Redundant assignment
JAVA0094 0.00JAVA0094 Field hides a superclass field
JAVA0095 0.00JAVA0095 Uninitialized private field
JAVA0096 0.00JAVA0096 Field in nested class hides outer field
JAVA0098 0.00JAVA0098 Minimize use of implicit field initializers
JAVA0100 1.00JAVA0100 Class contains N non-final fields (maximum: M)
JAVA0101 0.00JAVA0101 Unnecessary modifier for field in interface
JAVA0102 0.00JAVA0102 Last statement in finalize() not super.finalize()
JAVA0103 0.00JAVA0103 Explicit call to finalize()
JAVA0104 0.00JAVA0104 finalize() only calls super.finalize()
JAVA0105 0.00JAVA0105 Duplicate import declaration
JAVA0106 0.00JAVA0106 Unnecessary import from current package
JAVA0108 8.00JAVA0108 Incorrect javadoc: no @param tag for 'parameter'
JAVA0109 0.00JAVA0109 Incorrect javadoc: no parameter 'parameter'
JAVA0110 2.00JAVA0110 Incorrect javadoc: no @return tag
JAVA0111 0.00JAVA0111 Incorrect javadoc: @return tag for void method
JAVA0112 0.00JAVA0112 Incorrect javadoc: no exception 'exception' in throws
JAVA0113 1.00JAVA0113 Incorrect javadoc: no @author tag
JAVA0114 1.00JAVA0114 Incorrect javadoc: no @version tag
JAVA0115 1.00JAVA0115 Incorrect javadoc: no @throws or @exception tag for 'exception'
JAVA0116 0.00JAVA0116 Missing javadoc: field 'field'
JAVA0117 3.00JAVA0117 Missing javadoc: method 'method'
JAVA0118 0.00JAVA0118 Missing javadoc: type 'type'
JAVA0119 0.00JAVA0119 Control variable changed within body of for loop
JAVA0123 0.00JAVA0123 Use all three components of for loop
JAVA0125 0.00JAVA0125 Continue statement with label
JAVA0126 0.00JAVA0126 Method declares unchecked exception in throws
JAVA0128 0.00JAVA0128 Public constructor in non-public class
JAVA0130 5.00JAVA0130 Non-static method does not use instance fields
JAVA0131 0.00JAVA0131 Compatible method does not override base
JAVA0132 0.00JAVA0132 Method overload with compatible signature
JAVA0133 0.00JAVA0133 Non-synchronized method overrides synchronized method
JAVA0135 0.00JAVA0135 Only one of Object.equals and Object.hashCode defined: missing 'method'
JAVA0136 1.00JAVA0136 N methods defined in class (maximum: M)
JAVA0137 0.00JAVA0137 Non-abstract class missing constructor
JAVA0138 0.00JAVA0138 N parameters defined for method (maximum: M)
JAVA0139 0.00JAVA0139 Definition of main other than public static void main(java.lang.String[])
JAVA0141 0.00JAVA0141 Unnecessary modifier for method in interface
JAVA0143 0.00JAVA0143 Synchronized method
JAVA0144 0.00JAVA0144 Line exceeds maximum M characters
JAVA0145 0.00JAVA0145 Tab character used in source file
JAVA0150 0.00JAVA0150 java.lang.Error (or subclass) thrown
JAVA0153 0.00JAVA0153 Inefficient conversion of integer to string
JAVA0159 0.00JAVA0159 Inefficient conversion of string to integer
JAVA0160 1.00JAVA0160 Method does not throw specified exception
JAVA0161 0.00JAVA0161 Conditional wait() not in loop
JAVA0163 0.00JAVA0163 Empty statement
JAVA0165 0.00JAVA0165 Conflicting return statement in finally block
JAVA0166 1.00JAVA0166 Generic exception caught
JAVA0167 0.00JAVA0167 ThreadDeath not rethrown
JAVA0169 0.00JAVA0169 Unnecessary catch block: exception 'exception'
JAVA0170 0.00JAVA0170 Caught exception not derived from java.lang.Exception
JAVA0171 0.00JAVA0171 Unused local variable
JAVA0173 0.00JAVA0173 Unused method parameter
JAVA0174 0.00JAVA0174 Assigned local variable never used
JAVA0175 0.00JAVA0175 Successive assignment to variable
JAVA0176 0.00JAVA0176 Local variable name does not have required form
JAVA0177 2.00JAVA0177 Variable declaration missing initializer
JAVA0179 0.00JAVA0179 Local variable hides visible field
JAVA0233 0.00JAVA0233 Definition of serialVersionUID other than 'private static final long serialVersionUID'
JAVA0234 0.00JAVA0234 Class is Serializable but does not define serialVersionUID
JAVA0235 0.00JAVA0235 Class defines serialVersionUID but does not implement Serializable
JAVA0236 0.00JAVA0236 Attempt to clone an object which does not implement Cloneable
JAVA0237 0.00JAVA0237 Class implements Cloneable but does not have public clone method
JAVA0238 0.00JAVA0238 Clone method does not call super.clone()
JAVA0239 0.00JAVA0239 Class declares 'readObject' or 'writeObject' but does not implement Serializable
JAVA0240 0.00JAVA0240 Serializable class which declares readObject or writeObject but not both
JAVA0241 0.00JAVA0241 'readObject' or 'writeObject' should be declared private in Serializable class
JAVA0242 0.00JAVA0242 Transient field in non-Serializable class
JAVA0243 0.00JAVA0243 'readResolve' or 'writeReplace' should be declared private or protected
JAVA0244 0.00JAVA0244 Field or method name in subclass differs only by case from inherited field or method
JAVA0245 0.00JAVA0245 JUnit TestCase with non-trivial constructor
JAVA0246 0.00JAVA0246 JUnit assertXXX statement missing message parameter
JAVA0247 0.00JAVA0247 JUnit 'setUp()' and 'tearDown()' should call super method
JAVA0248 0.00JAVA0248 JUnit method 'setUp' or 'tearDown' with incorrect signature
JAVA0249 0.00JAVA0249 JUnit TestCase 'suite()' should be declared static
JAVA0250 0.00JAVA0250 JUnit TestCase declares testXXX method with incorrect signature
JAVA0251 8.00JAVA0251 Use '%n' for line breaks in printf/format for platform independence
JAVA0252 0.00JAVA0252 'enum' is a Java 1.5 reserved word
JAVA0253 0.00JAVA0253 Not all enum constants consumed in switch statement
JAVA0254 0.00JAVA0254 Use enhanced for loop construct instead of Iterator
JAVA0255 0.00JAVA0255 Result of method invocation not used
JAVA0256 0.00JAVA0256 Assignment of external collection/array to field
JAVA0257 0.00JAVA0257 Use of 'Constant Interface' anti-pattern
JAVA0258 0.00JAVA0258 Implement Iterable for foreach compatibility
JAVA0259 1.00JAVA0259 Return of collection/array field
JAVA0260 0.00JAVA0260 Use 'enum' instead of Enumerated Type pattern
JAVA0261 0.00JAVA0261 Use specialized Enum collection types
JAVA0262 0.00JAVA0262 Use of char in integer context
JAVA0263 0.00JAVA0263 Long literal ends with 'l' instead of 'L'
JAVA0264 0.00JAVA0264 Integer math in long context - check for overflow
JAVA0265 0.00JAVA0265 Use of Throwable.printStackTrace()
JAVA0266 0.00JAVA0266 Use of System.out
JAVA0267 0.00JAVA0267 Use of System.err
JAVA0269 0.00JAVA0269 Contents of StringBuffer never used
JAVA0270 0.00JAVA0270 Use Java 5.0 enhanced for loop construct to iterate over all elements in an array
JAVA0271 0.00JAVA0271 Minimize use of on-demand (.*) static imports
JAVA0272 0.00JAVA0272 Thread.run() called
JAVA0273 0.00JAVA0273 Non-final derivative of Thread calls start() in constructor
JAVA0274 0.00JAVA0274 Serializable class has a synchronized readObject()
JAVA0275 0.00JAVA0275 Serializable class has a synchronized writeObject() and no other synchronized methods
JAVA0276 0.00JAVA0276 Unnecessary use of String constructor
JAVA0277 0.00JAVA0277 Iterator.next() implementation does not throw NoSuchElementException
JAVA0278 0.00JAVA0278 Unnecessary use of Boolean constructor
JAVA0279 0.00JAVA0279 Serialization method readObject or readObjectNoData calls an overridable method
JAVA0280 0.00JAVA0280 IllegalMonitorStateException caught
JAVA0281 0.00JAVA0281 Iterator.next() not called in loop
JAVA0282 0.00JAVA0282 Call to Iterator.next() in loop which does not test Iterator.hasNext()
JAVA0283 0.00JAVA0283 Control variable not updated in loop body
JAVA0284 0.00JAVA0284 Explicit garbage collection
JAVA0285 0.00JAVA0285 Dereference of potentially null variable
JAVA0286 0.00JAVA0286 Dereference of null variable
JAVA0287 0.00JAVA0287 Unnecessary null check
JAVA0288 0.00JAVA0288 Inconsistent null check
JAVA0289 0.00null
LINES1505.00Number of lines in the source file
LINE_COMMENT68.00Number of line comments
LOC1000.00Lines of code
LOGICAL_LINES462.00Number of statements
LOOPS13.00Number of loops