use of javassist.CtClass in project motech by motech.
the class EntityBuilderImpl method addProperty.
private void addProperty(CtClass declaring, String typeClassName, String propertyName, String defaultValue) {
try {
String name = uncapitalize(propertyName);
JavassistUtil.removeFieldIfExists(declaring, propertyName);
CtClass type = classPool.getOrNull(typeClassName);
CtField field = JavassistBuilder.createField(declaring, type, propertyName, null);
if (isBlank(defaultValue)) {
declaring.addField(field);
} else {
CtField.Initializer initializer = JavassistBuilder.createInitializer(typeClassName, defaultValue);
declaring.addField(field, initializer);
}
createGetter(declaring, name, field);
createSetter(declaring, name, field);
} catch (CannotCompileException e) {
throw new PropertyCreationException("Error while creating property " + propertyName, e);
}
}
use of javassist.CtClass in project motech by motech.
the class EntityInfrastructureBuilderImpl method getServiceCode.
private byte[] getServiceCode(String serviceClassName, String interfaceClassName, String className, EntityDto entity, SchemaHolder schemaHolder) {
try {
CtClass superClass = classPool.getCtClass(TransactionalMotechDataService.class.getName());
superClass.setGenericSignature(getGenericSignature(className));
CtClass serviceInterface = classPool.getCtClass(interfaceClassName);
CtClass serviceClass = createOrRetrieveClass(serviceClassName, superClass);
// add the interface if its not already there
if (!JavassistUtil.hasInterface(serviceClass, serviceInterface)) {
serviceClass.addInterface(serviceInterface);
}
List<CtMethod> methods = new ArrayList<>();
// a count method for the lookup
if (null != entity) {
List<LookupDto> lookups = schemaHolder.getLookups(entity);
for (LookupDto lookup : lookups) {
for (LookupType lookupType : LookupType.values()) {
LookupBuilder lookupBuilder = new LookupBuilder(entity, lookup, serviceClass, lookupType, schemaHolder);
methods.add(lookupBuilder.buildMethod());
}
}
}
// clear lookup methods before adding the new ones
removeExistingMethods(serviceClass);
for (CtMethod method : methods) {
serviceClass.addMethod(method);
}
return serviceClass.toBytecode();
} catch (NotFoundException | IOException | CannotCompileException e) {
throw new EntityInfrastructureException(serviceClassName, e);
}
}
use of javassist.CtClass in project motech by motech.
the class BaseInstanceIT method setUpEntity.
private void setUpEntity() throws Exception {
String entityClass = getEntityClassName();
entity = new EntityDto(entityClass);
entity.setRecordHistory(true);
entity = entityService.createEntity(entity);
entityService.addFields(entity, getEntityFields());
TrackingDto tracking = entityService.getAdvancedSettings(entity.getId(), true).getTracking();
tracking.setAllowCreateEvent(false);
tracking.setAllowUpdateEvent(false);
tracking.setAllowDeleteEvent(false);
entityService.updateTracking(entity.getId(), tracking);
SchemaHolder schemaHolder = entityService.getSchema();
mdsConstructor.constructEntities(schemaHolder);
PersistenceManagerFactory factory = getDataPersistenceManagerFactory();
if (null == factory.getMetadata(entityClass)) {
factory.registerMetadata(metadataHolder.getJdoMetadata());
}
CtClass ctClass = MotechClassPool.getDefault().get(getRepositoryClass());
MDSClassLoader.getInstance().safeDefineClass(getRepositoryClass(), ctClass.toBytecode());
ctClass = MotechClassPool.getDefault().get(getInterfaceClass());
MDSClassLoader.getInstance().safeDefineClass(getInterfaceClass(), ctClass.toBytecode());
ctClass = MotechClassPool.getDefault().get(getServiceClass());
MDSClassLoader.getInstance().safeDefineClass(getServiceClass(), ctClass.toBytecode());
}
use of javassist.CtClass in project javaparser by javaparser.
the class JavassistEnumDeclaration method solveMethod.
public SymbolReference<ResolvedMethodDeclaration> solveMethod(String name, List<ResolvedType> argumentsTypes, boolean staticOnly) {
List<ResolvedMethodDeclaration> candidates = new ArrayList<>();
Predicate<CtMethod> staticOnlyCheck = m -> !staticOnly || (staticOnly && Modifier.isStatic(m.getModifiers()));
for (CtMethod method : ctClass.getDeclaredMethods()) {
boolean isSynthetic = method.getMethodInfo().getAttribute(SyntheticAttribute.tag) != null;
boolean isNotBridge = (method.getMethodInfo().getAccessFlags() & AccessFlag.BRIDGE) == 0;
if (method.getName().equals(name) && !isSynthetic && isNotBridge && staticOnlyCheck.test(method)) {
candidates.add(new JavassistMethodDeclaration(method, typeSolver));
}
}
try {
CtClass superClass = ctClass.getSuperclass();
if (superClass != null) {
SymbolReference<ResolvedMethodDeclaration> ref = new JavassistClassDeclaration(superClass, typeSolver).solveMethod(name, argumentsTypes, staticOnly);
if (ref.isSolved()) {
candidates.add(ref.getCorrespondingDeclaration());
}
}
} catch (NotFoundException e) {
throw new RuntimeException(e);
}
return MethodResolutionLogic.findMostApplicable(candidates, name, argumentsTypes, typeSolver);
}
use of javassist.CtClass in project BroadleafCommerce by BroadleafCommerce.
the class AnnotationsCopyClassTransformer method transform.
@Override
public byte[] transform(ClassLoader loader, String className, Class<?> classBeingRedefined, ProtectionDomain protectionDomain, byte[] classfileBuffer) throws IllegalClassFormatException {
// Lambdas and anonymous methods in Java 8 do not have a class name defined and so no transformation should be done
if (className == null) {
return null;
}
String convertedClassName = className.replace('/', '.');
if (xformTemplates.containsKey(convertedClassName)) {
String xformKey = convertedClassName;
String[] xformVals = xformTemplates.get(xformKey).split(",");
logger.lifecycle(LifeCycleEvent.START, String.format("Transform - Copying annotations into [%s] from [%s]", xformKey, StringUtils.join(xformVals, ",")));
CtClass clazz = null;
try {
// Load the destination class and defrost it so it is eligible for modifications
ClassPool classPool = ClassPool.getDefault();
clazz = classPool.makeClass(new ByteArrayInputStream(classfileBuffer), false);
clazz.defrost();
for (String xformVal : xformVals) {
// Load the source class
String trimmed = xformVal.trim();
classPool.appendClassPath(new LoaderClassPath(Class.forName(trimmed).getClassLoader()));
CtClass template = classPool.get(trimmed);
// Copy over all declared annotations from fields from the template class
// Note that we do not copy over fields with the @NonCopiedField annotation
CtField[] fieldsToCopy = template.getDeclaredFields();
for (CtField field : fieldsToCopy) {
if (field.hasAnnotation(NonCopied.class)) {
logger.debug(String.format("Not copying annotation from field [%s]", field.getName()));
} else {
logger.debug(String.format("Copying annotation from field [%s]", field.getName()));
ConstPool constPool = clazz.getClassFile().getConstPool();
CtField fieldFromMainClass = clazz.getField(field.getName());
for (Object o : field.getFieldInfo().getAttributes()) {
if (o instanceof AnnotationsAttribute) {
AnnotationsAttribute templateAnnotations = (AnnotationsAttribute) o;
// have to make a copy of the annotations from the target
AnnotationsAttribute copied = (AnnotationsAttribute) templateAnnotations.copy(constPool, null);
// add all the copied annotations into the target class's field.
for (Object attribute : fieldFromMainClass.getFieldInfo().getAttributes()) {
if (attribute instanceof AnnotationsAttribute) {
for (Annotation annotation : copied.getAnnotations()) {
((AnnotationsAttribute) attribute).addAnnotation(annotation);
}
}
}
}
}
}
}
}
logger.lifecycle(LifeCycleEvent.END, String.format("Transform - Copying annotations into [%s] from [%s]", xformKey, StringUtils.join(xformVals, ",")));
return clazz.toBytecode();
} catch (Exception e) {
throw new RuntimeException("Unable to transform class", e);
} finally {
if (clazz != null) {
clazz.detach();
}
}
}
return null;
}
Aggregations