use of javassist.CtConstructor in project OpenTripPlanner by opentripplanner.
the class ClassCustomizer method addDoubleField.
/**
* Adds a new field of type double to the customized class
*/
public void addDoubleField(String fieldName) {
// FIXME: this should support default values but does not
ClassFile classFile = ctClass.getClassFile();
ConstPool constPool = classFile.getConstPool();
try {
// add field
FieldInfo fieldInfo = new FieldInfo(constPool, fieldName, "D");
classFile.addField(fieldInfo);
CtConstructor ctor = CtNewConstructor.defaultConstructor(ctClass);
ctClass.addConstructor(ctor);
addDoubleSetter(classFile, fieldName);
addDoubleGetter(classFile, fieldName);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
use of javassist.CtConstructor in project compss by bsc-wdc.
the class JavaNestedInvoker method instrumentClass.
private static void instrumentClass(ClassPool cp, CtClass appClass, Class<?> annotItf, String itApiVar, String itSRVar, String itORVar, String itAppIdVar) throws ClassNotFoundException, NotFoundException, CannotCompileException {
Method[] remoteMethods = annotItf.getMethods();
CtMethod[] instrCandidates = appClass.getDeclaredMethods();
// Candidates to be instrumented if they are not remote
ITAppEditor itAppEditor;
itAppEditor = new ITAppEditor(remoteMethods, instrCandidates, itApiVar, itSRVar, itORVar, itAppIdVar, appClass);
/*
* Create Code Converter
*/
CodeConverter converter = new CodeConverter();
CtClass arrayWatcher = cp.get(LoaderConstants.CLASS_ARRAY_ACCESS_WATCHER);
CodeConverter.DefaultArrayAccessReplacementMethodNames names;
names = new CodeConverter.DefaultArrayAccessReplacementMethodNames();
converter.replaceArrayAccess(arrayWatcher, (CodeConverter.ArrayAccessReplacementMethodNames) names);
/*
* Find the methods declared in the application class that will be instrumented - Main - Constructors - Methods
* that are not in the remote list
*/
for (CtMethod m : instrCandidates) {
m.instrument(converter);
m.instrument(itAppEditor);
}
// Instrument constructors
for (CtConstructor c : appClass.getDeclaredConstructors()) {
c.instrument(converter);
c.instrument(itAppEditor);
}
}
use of javassist.CtConstructor in project japicmp-gradle-plugin by melix.
the class Violation method describe.
public static String describe(JApiCompatibility member) {
if (member instanceof JApiAnnotation) {
return "Annotation " + ((JApiAnnotation) member).getFullyQualifiedName();
}
if (member instanceof JApiAnnotationElement) {
return "Annotation element " + ((JApiAnnotationElement) member).getName();
}
if (member instanceof JApiConstructor) {
JApiConstructor method = (JApiConstructor) member;
Optional<CtConstructor> changedMethod = method.getNewConstructor();
if (!changedMethod.isPresent()) {
changedMethod = method.getOldConstructor();
}
return "Constructor " + (changedMethod.isPresent() ? changedMethod.get().getLongName() : method.getName());
}
if (member instanceof JApiMethod) {
JApiMethod method = (JApiMethod) member;
Optional<CtMethod> changedMethod = method.getNewMethod();
if (!changedMethod.isPresent()) {
changedMethod = method.getOldMethod();
}
return "Method " + (changedMethod.isPresent() ? changedMethod.get().getLongName() : method.getName());
}
if (member instanceof JApiField) {
return "Field " + ((JApiField) member).getName();
}
if (member instanceof JApiClass) {
return "Class " + ((JApiClass) member).getFullyQualifiedName();
}
if (member instanceof JApiSuperclass) {
Optional<JApiClass> jApiClass = ((JApiSuperclass) member).getJApiClass();
return "Superclass " + (jApiClass.isPresent() ? jApiClass.get() : "[removed]");
}
if (member instanceof JApiImplementedInterface) {
return "Implemented interface " + ((JApiImplementedInterface) member).getFullyQualifiedName();
}
return member.toString();
}
use of javassist.CtConstructor in project DRouter by didi.
the class RouterCollect method generate.
@Override
public void generate(File routerDir) throws Exception {
CtClass ctClass = pool.makeClass(getPackageName() + ".RouterLoader");
CtClass superClass = pool.get("com.didi.drouter.store.MetaLoader");
ctClass.setSuperclass(superClass);
StringBuilder builder = new StringBuilder();
builder.append("public void load(java.util.Map data) {\n");
for (CtClass routerCc : routerClass.values()) {
try {
StringBuilder interceptorClass = null;
StringBuilder interceptorName = null;
String uriValue = "";
String schemeValue = "";
String hostValue = "";
String pathValue = "";
Annotation annotation = null;
String type;
int thread = 0;
int priority = 0;
boolean hold = false;
if (routerCc.hasAnnotation(Router.class)) {
uriValue = ((Router) routerCc.getAnnotation(Router.class)).uri();
schemeValue = ((Router) routerCc.getAnnotation(Router.class)).scheme();
hostValue = ((Router) routerCc.getAnnotation(Router.class)).host();
pathValue = ((Router) routerCc.getAnnotation(Router.class)).path();
thread = ((Router) routerCc.getAnnotation(Router.class)).thread();
priority = ((Router) routerCc.getAnnotation(Router.class)).priority();
hold = ((Router) routerCc.getAnnotation(Router.class)).hold();
annotation = getAnnotation(routerCc, Router.class);
if (checkSuper(routerCc, "android.app.Activity")) {
type = "com.didi.drouter.store.RouterMeta.ACTIVITY";
} else if (checkSuper(routerCc, "android.support.v4.app.Fragment", "androidx.fragment.app.Fragment")) {
type = "com.didi.drouter.store.RouterMeta.FRAGMENT";
} else if (checkSuper(routerCc, "android.view.View")) {
type = "com.didi.drouter.store.RouterMeta.VIEW";
} else if (checkSuper(routerCc, "com.didi.drouter.router.IRouterHandler")) {
type = "com.didi.drouter.store.RouterMeta.HANDLER";
} else {
throw new Exception("@Router target class illegal, " + "support only Activity/Fragment/View/IRouterHandler");
}
} else {
pathValue = "/" + routerCc.getName().replace(".", "/");
type = "com.didi.drouter.store.RouterMeta.ACTIVITY";
}
if (isNonStaticInnerClass(routerCc)) {
throw new Exception("@Router can not use non static inner class");
}
if (!uriValue.isEmpty()) {
if (!schemeValue.isEmpty() || !hostValue.isEmpty() || !pathValue.isEmpty()) {
throw new Exception("@Router uri can be used alone");
}
schemeValue = parseScheme(uriValue);
hostValue = parseHost(uriValue);
pathValue = parsePath(uriValue);
}
if (schemeValue.contains("/") || hostValue.contains("/")) {
throw new Exception("@Router scheme and host can't use \"/\"");
}
// if (!isRegex(pathValue) && !pathValue.isEmpty() && !pathValue.startsWith("/")) {
// throw new Exception("@Router path must start with \"/\"");
// }
// because of Escape character, \ will drop one, \\\\->\\, \\->empty(can't be one)
schemeValue = schemeValue.replace("\\", "\\\\");
hostValue = hostValue.replace("\\", "\\\\");
pathValue = pathValue.replace("\\", "\\\\");
if (annotation != null) {
ArrayMemberValue interceptorClassArrayValue = (ArrayMemberValue) annotation.getMemberValue("interceptor");
if (interceptorClassArrayValue != null) {
interceptorClass = new StringBuilder();
interceptorClass.append("new Class[]{");
for (MemberValue mv : interceptorClassArrayValue.getValue()) {
final ClassMemberValue cmv = (ClassMemberValue) mv;
interceptorClass.append(cmv.getValue());
interceptorClass.append(".class,");
}
interceptorClass.deleteCharAt(interceptorClass.length() - 1);
interceptorClass.append("}");
}
ArrayMemberValue interceptorNameArrayValue = (ArrayMemberValue) annotation.getMemberValue("interceptorName");
if (interceptorNameArrayValue != null) {
interceptorName = new StringBuilder();
interceptorName.append("new String[]{");
for (MemberValue mv : interceptorNameArrayValue.getValue()) {
final StringMemberValue smv = (StringMemberValue) mv;
interceptorName.append("\"");
interceptorName.append(smv.getValue());
interceptorName.append("\",");
}
interceptorName.deleteCharAt(interceptorName.length() - 1);
interceptorName.append("}");
}
}
StringBuilder metaBuilder = new StringBuilder();
metaBuilder.append("com.didi.drouter.store.RouterMeta.build(");
metaBuilder.append(type);
metaBuilder.append(").assembleRouter(");
metaBuilder.append("\"").append(schemeValue).append("\"");
metaBuilder.append(",");
metaBuilder.append("\"").append(hostValue).append("\"");
metaBuilder.append(",");
metaBuilder.append("\"").append(pathValue).append("\"");
metaBuilder.append(",");
if ("com.didi.drouter.store.RouterMeta.ACTIVITY".equals(type)) {
if (!setting.isUseActivityRouterClass()) {
metaBuilder.append("\"").append(routerCc.getName()).append("\"");
} else {
metaBuilder.append(routerCc.getName()).append(".class");
}
} else {
metaBuilder.append(routerCc.getName()).append(".class");
}
metaBuilder.append(", ");
CtClass proxyCc = null;
try {
if (type.endsWith("HANDLER") || type.endsWith("FRAGMENT")) {
CtConstructor constructor = routerCc.getDeclaredConstructor(null);
if (constructor != null) {
CtClass proxyInterface = pool.get("com.didi.drouter.store.IRouterProxy");
proxyCc = pool.makeClass(PROXY + routerCc.getName().replace(".", "_"));
proxyCc.addInterface(proxyInterface);
String method1 = String.format("public java.lang.Object newInstance(android.content.Context context) {" + "{ return new %s();} }", routerCc.getName());
generatorClass(routerDir, proxyCc, method1, METHOD2);
}
} else if (type.endsWith("VIEW")) {
CtConstructor constructor = routerCc.getDeclaredConstructor(new CtClass[] { pool.get("android.content.Context") });
if (constructor != null) {
CtClass proxyInterface = pool.get("com.didi.drouter.store.IRouterProxy");
proxyCc = pool.makeClass(PROXY + routerCc.getName().replace(".", "_"));
proxyCc.addInterface(proxyInterface);
String method1 = String.format("public java.lang.Object newInstance(android.content.Context context) {" + "{ return new %s(context);} }", routerCc.getName());
generatorClass(routerDir, proxyCc, method1, METHOD2);
}
}
} catch (NotFoundException ignore) {
}
metaBuilder.append(proxyCc != null ? "new " + proxyCc.getName() + "()" : "null");
metaBuilder.append(", ");
metaBuilder.append(interceptorClass != null ? interceptorClass.toString() : "null");
metaBuilder.append(", ");
metaBuilder.append(interceptorName != null ? interceptorName.toString() : "null");
metaBuilder.append(", ");
metaBuilder.append(thread);
metaBuilder.append(", ");
metaBuilder.append(priority);
metaBuilder.append(", ");
metaBuilder.append(hold);
metaBuilder.append(")");
String uri = schemeValue + "@@" + hostValue + "$$" + pathValue;
if (!isPlaceholderLegal(schemeValue, hostValue, pathValue)) {
throw new Exception("\"" + uri + "\" on " + routerCc.getName() + "\ncan't use regex outside placeholder <>," + "\nand must be unique legal identifier inside placeholder <>");
}
boolean isAnyRegex = isRegex(schemeValue, hostValue, pathValue);
if (isAnyRegex) {
items.add(" put(\"" + uri + "\", " + metaBuilder + ", data); \n");
// builder.append(" put(\"").append(uri).append("\", ").append(metaBuilder).append(", data); \n");
} else {
items.add(" data.put(\"" + uri + "\", " + metaBuilder + "); \n");
// builder.append(" data.put(\"").append(uri).append("\", ").append(metaBuilder).append("); \n");
}
String duplicate = StoreUtil.insertUri(uri, routerCc);
if (duplicate != null) {
throw new Exception("\"" + uri + "\" on " + routerCc.getName() + "\nhas duplication of name with class: " + duplicate);
}
} catch (Exception e) {
e.printStackTrace();
throw new Exception("Class: === " + routerCc.getName() + " ===\nCause: " + e.getMessage());
}
}
Collections.sort(items);
for (String item : items) {
builder.append(item);
}
builder.append("}");
Logger.d("\nclass RouterLoader" + "\n" + builder.toString());
generatorClass(routerDir, ctClass, builder.toString());
}
use of javassist.CtConstructor in project knetbuilder by Rothamsted.
the class UniversalProxyTemplateBuilder method makeMethod.
@SuppressWarnings({})
private void makeMethod(final CtClass ct, final Class<?> parent, final String name, final Member member, boolean globalFunctionsMode, final Map<Class<?>, Object[]> cnvMap) throws CannotCompileException {
StringBufferWrap cm = new StringBufferWrap();
Class<?>[] parTypes = null;
boolean isVarArg = false;
Method method = null;
Map<Class<?>, Method> parnetMethodReturns = new HashMap<Class<?>, Method>();
if (parent != null) {
for (Method m : parent.getMethods()) {
if (m.getGenericParameterTypes().length == 0 && m.getReturnType() != null) {
parnetMethodReturns.put(m.getReturnType(), m);
}
}
}
Constructor constructor = null;
if (member instanceof Method) {
method = (Method) member;
isVarArg = method.isVarArgs();
if (globalFunctionsMode) {
cm.append(PUBLIC_STATIC, getWrappedName(method.getReturnType()), SPACE, name, BR_OPEN);
} else {
cm.append(PUBLIC, getWrappedName(method.getReturnType()), SPACE, name, BR_OPEN);
}
parTypes = method.getParameterTypes();
} else if (member instanceof Constructor) {
constructor = (Constructor) member;
isVarArg = constructor.isVarArgs();
cm.append(PUBLIC, SPACE, ct.getSimpleName(), BR_OPEN);
parTypes = ((Constructor) member).getParameterTypes();
}
StringBufferWrap args1 = new StringBufferWrap();
int functionArgCount = 0;
final ResolutionTreeParser apt = new ResolutionTreeParser(ct, parent);
if (cnvMap != null)
apt.setConvMethods(cnvMap);
String owner = OWNER;
if (Modifier.isStatic(member.getModifiers())) {
owner = member.getDeclaringClass().getCanonicalName();
} else if (isResolved(member.getDeclaringClass())) {
owner = apt.addInternalArg(owner, member.getDeclaringClass());
} else if (globalFunctionsMode && cnvMap != null && cnvMap.containsKey(member.getDeclaringClass())) {
apt.addConvinienceArg(owner, member.getDeclaringClass(), "cOwner", (Class<?>) cnvMap.get(member.getDeclaringClass())[0]);
} else {
owner = BS;
}
boolean throwsException = false;
List<StringBufferWrap> arrayUnwrappers = new LinkedList<StringBufferWrap>();
StringBufferWrap listMethodVersion = null;
StringBufferWrap listToArray = null;
if (isVarArg) {
listMethodVersion = new StringBufferWrap();
listToArray = new StringBufferWrap();
}
for (int i = 0; i < parTypes.length; i++) {
String argName = ARG + i;
String wrapperName = null;
String nameInsideMethod = null;
if (parTypes[i].isArray()) {
wrapperName = wrapperNameLookup.get(parTypes[i].getComponentType());
if (wrapperName != null) {
wrapperName = wrapperName + "[]";
nameInsideMethod = "arr_" + argName;
StringBufferWrap unwrapper = new StringBufferWrap();
unwrapper.append(getClassName(parTypes[i]), " ", nameInsideMethod, " = new ", parTypes[i].getComponentType().getCanonicalName(), "[", argName, ".length];\n");
unwrapper.append("for(int i = 0; i< ", argName, ".length; i++){\n", nameInsideMethod, "[i] = ", argName, "[i].unwrap();\n", "\n}");
arrayUnwrappers.add(unwrapper);
}
if (isVarArg && i == parTypes.length - 1) {
wrapperName = wrapperNameLookup.get(parTypes[i].getComponentType());
String nameInsideMethod1 = argName;
if (wrapperName != null) {
wrapperName = wrapperName + "[]";
nameInsideMethod1 = "arr_" + argName;
}
listToArray.append(getClassName(parTypes[i]), " ", nameInsideMethod1, " = new ", parTypes[i].getComponentType().getCanonicalName(), "[", argName, ".size()];\n");
listToArray.append("for(int i = 0; i< ", argName, ".size(); i++){\n", nameInsideMethod1, "[i] = (", parTypes[i].getComponentType().getCanonicalName(), ")", argName, "get(i).unwrap();\n", "\n}");
listMethodVersion.append(cm.toString(), "java.util.List", SPACE, argName);
}
} else {
wrapperName = wrapperNameLookup.get(parTypes[i]);
}
boolean implementConvinience = false;
if (isResolved(parTypes[i])) {
argName = apt.addInternalArg(argName, parTypes[i]);
throwsException = true;
} else if (cnvMap != null && cnvMap.containsKey(parTypes[i])) {
implementConvinience = true;
final Object[] obj = cnvMap.get(parTypes[i]);
apt.addConvinienceArg(argName, parTypes[i], "conv" + i, (Class<?>) obj[0]);
cm.append(synElementAt(functionArgCount) + getClassName((Class<?>) obj[0]) + SPACE + "conv" + i);
functionArgCount++;
} else if (wrapperName != null) {
cm.append(synElementAt(functionArgCount), wrapperName, SPACE, argName);
functionArgCount++;
} else {
cm.append(synElementAt(functionArgCount), getClassName(parTypes[i]), SPACE, argName);
functionArgCount++;
}
if (nameInsideMethod != null) {
argName = nameInsideMethod;
}
if (!isResolved(parTypes[i]) && wrapperName != null && !implementConvinience && !parTypes[i].isArray()) {
args1.append(synElementAt(i), BR_OPEN, getClassName(parTypes[i]), BR_CLOSE, WRP, argName, UNWRP_ARG);
} else {
args1.append(synElementAt(i), argName);
}
}
if (throwsException) {
cm.append(BR_CLOSE, FNEX, M_START);
cm.append(TRY_OPN, NL_TB);
} else {
cm.append(BR_CLOSE, M_START);
}
apt.addAppTreeResolution(cm);
for (StringBufferWrap unwrapper : arrayUnwrappers) {
cm.append(unwrapper.toString());
}
String cast = null;
try {
if (method != null) {
cast = wrapperNameLookup.get(method.getReturnType());
if (cast != null) {
cm.append(cast, " wrapped_result = new ", cast, "();");
Set<Class<?>> embedded = shadowTemplates.get(cast).getEmbeddedClasses();
if (embedded.size() > 0) {
for (Class<?> cls : embedded) {
Method m = parnetMethodReturns.get(cls);
if (m != null) {
cm.append("wrapped_result.setEmb", cls.getSimpleName(), "(this.baseObject.", m.getName(), "());");
} else if (shadowTemplates.get(wrapperNameLookup.get(parent)).getEmbeddedClasses().contains(cls)) {
cm.append("wrapped_result.setEmb", cls.getSimpleName(), "(this.getEmb", cls.getSimpleName(), "());");
}
}
}
cm.append("wrapped_result.wrap(", owner, DOT, method.getName(), BR_OPEN, args1.toString(), BR_CLOSE, BR_CLOSE, ";\n", RETURN, "wrapped_result", SC, CLS, NL_TB);
} else if (method.getReturnType().isArray() && method.getReturnType().getComponentType().equals(Object.class)) {
// || this.wrapperNameLookup.get(method.getReturnType().getComponentType().getName()) != null
// System.err.println(method.getDeclaringClass().getName()+" - "+method.getName());
// net.sourceforge.ondex.scripting.base.UniversalProxyTemplateBuilder.wrapArray();
cm.append(RETURN, " net.sourceforge.ondex.scripting.base.UniversalProxyTemplateBuilder.wrapArray(", owner, DOT, method.getName(), BR_OPEN, args1.toString(), "))", unwrapPrimitive(method.getReturnType()), ";}", NL_TB);
} else {
cm.append(RETURN, owner, DOT, method.getName(), BR_OPEN, args1.toString(), ")", unwrapPrimitive(method.getReturnType()), ";}", NL_TB);
}
if (throwsException) {
cm.append(TRY_CLS, QT, member.getName(), ERRMSG, BR_LN_M_END, NL_TB, CLS);
}
try {
CtMethod ctmethod = CtMethod.make(cm.toString(), ct);
if (isVarArg) {
if (globalFunctionsMode) {
ctmethod.getMethodInfo().setAccessFlags(137);
} else {
ctmethod.getMethodInfo().setAccessFlags(129);
}
}
ct.addMethod(ctmethod);
} catch (Exception e) {
if (!(e instanceof javassist.bytecode.DuplicateMemberException)) {
if (parent != null)
System.err.println(parent.getCanonicalName());
System.err.println(cm.toString());
e.printStackTrace();
}
}
} else {
cm.append(owner, " = new ", member.getDeclaringClass().getCanonicalName(), BR_OPEN, args1.toString(), BR_LN_M_END, NL_TB);
if (throwsException) {
cm.append(TRY_CLS, QT, member.getName(), ERRMSG, BR_LN_M_END, NL_TB, CLS);
}
try {
CtConstructor ctor = CtNewConstructor.make(cm.toString(), ct);
if (isVarArg) {
ctor.getMethodInfo().setAccessFlags(129);
}
ct.addConstructor(ctor);
} catch (Exception e) {
if (!(e instanceof javassist.bytecode.DuplicateMemberException)) {
e.printStackTrace();
}
}
}
} catch (final Exception e) {
e.printStackTrace();
// System.err.println(e.getMessage()+" -- "+cm.getString());
}
}
Aggregations