Search in sources :

Example 61 with CtClass

use of javassist.CtClass in project fakereplace by fakereplace.

the class WatcherReplacementTest method testInstrumentationReplacement.

@Test
public void testInstrumentationReplacement() throws Exception {
    WatcherRep re = new WatcherRep();
    int val0 = re.value();
    Assert.assertEquals("Test setup wrong", 0, val0);
    ClassPool pool = new ClassPool();
    pool.appendClassPath(new LoaderClassPath(getClass().getClassLoader()));
    CtClass nc = pool.get(WatcherRep1.class.getName());
    if (nc.isFrozen()) {
        nc.defrost();
    }
    nc.replaceClassName(WatcherRep1.class.getName(), WatcherRep.class.getName());
    nc.setName(WatcherRep.class.getName());
    byte[] data = nc.toBytecode();
    File file = new File(WatcherRep.class.getClassLoader().getResource(WatcherRep.class.getName().replace(".", "/") + ".class").getFile());
    System.out.println(file);
    try (FileOutputStream out = new FileOutputStream(file)) {
        out.write(data);
    }
    long start = System.currentTimeMillis();
    do {
        Thread.sleep(100);
        if (re.value() == 1) {
            break;
        }
    } while (start + 5000 > System.currentTimeMillis());
    Assert.assertEquals("WatcherRep was not replaced", 1, re.value());
    file.delete();
}
Also used : CtClass(javassist.CtClass) FileOutputStream(java.io.FileOutputStream) ClassPool(javassist.ClassPool) LoaderClassPath(javassist.LoaderClassPath) File(java.io.File) Test(org.junit.Test)

Example 62 with CtClass

use of javassist.CtClass in project compss by bsc-wdc.

the class JavaInvoker method externalExecution.

private Object externalExecution() throws JobExecutionException {
    // Invoke the requested method from the external platform
    // WARN: ExternalExecution is only supported for methods with PSCO as target object
    int n = method.getParameterAnnotations().length;
    ClassPool pool = ClassPool.getDefault();
    Class<?>[] cParams = method.getParameterTypes();
    CtClass[] ctParams = new CtClass[n];
    for (int i = 0; i < n; i++) {
        try {
            ctParams[i] = pool.getCtClass(((Class<?>) cParams[i]).getName());
        } catch (NotFoundException e) {
            throw new JobExecutionException(ERROR_CLASS_NOT_FOUND + " " + cParams[i].getName(), e);
        }
    }
    String descriptor;
    try {
        descriptor = method.getName() + Descriptor.ofMethod(pool.getCtClass(method.getReturnType().getName()), ctParams);
    } catch (NotFoundException e) {
        throw new JobExecutionException(ERROR_CLASS_NOT_FOUND + " " + method.getReturnType().getName(), e);
    }
    // Check and retrieve target PSCO Id
    String id = null;
    try {
        id = ((StubItf) target.getValue()).getID();
    } catch (Exception e) {
        throw new JobExecutionException(ERROR_EXTERNAL_NO_PSCO, e);
    }
    if (id == null) {
        throw new JobExecutionException(ERROR_EXTERNAL_NO_PSCO);
    }
    // Call Storage executeTask
    if (LOGGER.isDebugEnabled()) {
        LOGGER.info("External ExecuteTask " + method.getName() + " with target PSCO Id " + id + " in " + nw.getHostName());
    } else {
        LOGGER.info("External ExecuteTask " + method.getName());
    }
    if (NIOTracer.isActivated()) {
        NIOTracer.emitEvent(NIOTracer.Event.STORAGE_EXECUTETASK.getId(), NIOTracer.Event.STORAGE_EXECUTETASK.getType());
    }
    PSCOCallbackHandler callback = new PSCOCallbackHandler();
    try {
        String call_result = StorageItf.executeTask(id, descriptor, values, nw.getHostName(), callback);
        LOGGER.debug(call_result);
        // Wait for execution
        callback.waitForCompletion();
    } catch (StorageException e) {
        throw new JobExecutionException(ERROR_STORAGE_CALL, e);
    } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
        throw new JobExecutionException(ERROR_CALLBACK_INTERRUPTED, e);
    } finally {
        if (NIOTracer.isActivated()) {
            NIOTracer.emitEvent(NIOTracer.EVENT_END, NIOTracer.Event.STORAGE_EXECUTETASK.getType());
        }
    }
    // Process the return status
    CallbackEvent.EventType callStatus = callback.getStatus();
    if (!callStatus.equals(CallbackEvent.EventType.SUCCESS)) {
        throw new JobExecutionException(ERROR_EXTERNAL_EXECUTION);
    }
    // Process return value
    Object retValue = null;
    if (method.getReturnType().getName().compareTo(void.class.getName()) != 0) {
        try {
            retValue = callback.getResult();
        } catch (StorageException e) {
            LOGGER.warn(WARN_RET_VALUE_EXCEPTION, e);
            retValue = null;
        }
    }
    return retValue;
}
Also used : ClassPool(javassist.ClassPool) NotFoundException(javassist.NotFoundException) CallbackEvent(storage.CallbackEvent) JobExecutionException(es.bsc.compss.nio.exceptions.JobExecutionException) StorageException(storage.StorageException) NotFoundException(javassist.NotFoundException) CtClass(javassist.CtClass) JobExecutionException(es.bsc.compss.nio.exceptions.JobExecutionException) CtClass(javassist.CtClass) StorageException(storage.StorageException)

Example 63 with CtClass

use of javassist.CtClass in project compss by bsc-wdc.

the class ITAppEditor method edit.

/**
 * Instruments the creation of streams and stream wrappers
 *
 * @param ne
 *            New expression
 */
@Override
public void edit(NewExpr ne) throws CannotCompileException {
    String fullName = ne.getClassName();
    boolean isInternal = fullName.startsWith(LoaderConstants.LOADER_INTERNAL_PREFIX);
    boolean isIO = fullName.startsWith(LoaderConstants.LOADER_IO_PREFIX);
    // Only edit non-internal calls
    if (!isInternal) {
        StringBuilder modifiedExpr = new StringBuilder();
        StringBuilder callPars = new StringBuilder();
        StringBuilder toSerialize = new StringBuilder();
        try {
            CtClass[] paramTypes = ne.getConstructor().getParameterTypes();
            if (paramTypes.length > 0) {
                int i = 1;
                for (CtClass parType : paramTypes) {
                    if (i > 1) {
                        callPars.append(',');
                    }
                    String parId = "$" + (i++);
                    if (parType.isPrimitive()) {
                        callPars.append(parId);
                    } else {
                        // Object (also array)
                        if (DEBUG) {
                            LOGGER.debug("Parameter " + (i - 1) + " of constructor " + ne.getConstructor() + " is an object, adding access");
                        }
                        String internalObject = itORVar + GET_INTERNAL_OBJECT + parId + ")";
                        modifiedExpr.insert(0, itORVar + NEW_OBJECT_ACCESS + parId + ");");
                        callPars.append(internalObject).append(" == null ? ").append(parId).append(" : ").append("(" + parType.getName() + ")").append(internalObject);
                        toSerialize.append(itORVar).append(SERIALIZE_LOCALLY).append(parId).append(");");
                    }
                }
            }
        } catch (NotFoundException e) {
            throw new CannotCompileException(e);
        }
        if (isIO) {
            String className = fullName.substring(8);
            modifiedExpr.append(inspectCreation(className, callPars));
        } else {
            modifiedExpr.append(PROCEED).append(callPars).append(");");
            modifiedExpr.append(toSerialize);
        }
        if (DEBUG) {
            LOGGER.debug("Replacing regular constructor call of class " + fullName + " by " + modifiedExpr.toString());
        }
        // Update new expression
        ne.replace(modifiedExpr.toString());
    }
}
Also used : CtClass(javassist.CtClass) NotFoundException(javassist.NotFoundException) CannotCompileException(javassist.CannotCompileException)

Example 64 with CtClass

use of javassist.CtClass in project compss by bsc-wdc.

the class AddOrchestration method main.

public static void main(String[] args) throws NotFoundException, NameNotFoundException, CannotCompileException, IOException {
    if (args.length < 2) {
        ErrorManager.fatal("Error: missing arguments for loader");
    }
    String className = args[0];
    String classPackage = getPackage(className);
    // Pool creation
    ClassPool pool = ClassPool.getDefault();
    if (classPackage != null && classPackage.trim().length() > 0) {
        pool.importPackage(classPackage);
    }
    // Extracting the class
    CtClass cc = pool.getCtClass(className);
    ClassFile ccFile = cc.getClassFile();
    ConstPool constpool = ccFile.getConstPool();
    for (int i = 1; i < args.length; i++) {
        String methodLabel = args[i];
        String methodName = getMethodName(methodLabel);
        CtClass[] params = getParamClasses(methodLabel, pool);
        CtMethod methodDescriptor = cc.getDeclaredMethod(methodName, params);
        AnnotationsAttribute attr = (AnnotationsAttribute) methodDescriptor.getMethodInfo().getAttribute(AnnotationsAttribute.visibleTag);
        if (attr == null) {
            // Create the annotation
            attr = new AnnotationsAttribute(constpool, AnnotationsAttribute.visibleTag);
        }
        Annotation annot = new Annotation(LoaderConstants.CLASS_ANNOTATIONS_ORCHESTRATION, constpool);
        attr.addAnnotation(annot);
        methodDescriptor.getMethodInfo().addAttribute(attr);
    }
    cc.writeFile();
// transform the ctClass to java class
/*
         * Class<?> dynamiqueBeanClass = cc.toClass();
         * 
         * //instanciating the updated class AddOrchestration ao = (AddOrchestration) dynamiqueBeanClass.newInstance();
         * 
         * try{ Method fooMethod = ao.getClass().getDeclaredMethod(methodName, new Class<?>[] { int.class }); //getting
         * the annotation Orchestration o = (Orchestration) fooMethod.getAnnotation(Orchestration.class);
         * System.out.println("METHOD: " + fooMethod); System.out.println("ANNOTATION: " + o); } catch(Exception e){
         * e.printStackTrace(); }
         */
}
Also used : CtClass(javassist.CtClass) ConstPool(javassist.bytecode.ConstPool) ClassFile(javassist.bytecode.ClassFile) AnnotationsAttribute(javassist.bytecode.AnnotationsAttribute) ClassPool(javassist.ClassPool) CtMethod(javassist.CtMethod) Annotation(javassist.bytecode.annotation.Annotation)

Example 65 with CtClass

use of javassist.CtClass in project motech by motech.

the class JavassistLoader method doWhenClassNotFound.

@Override
public void doWhenClassNotFound(String name) {
    CtClass ctClass = MotechClassPool.getDefault().getOrNull(name);
    if (null != ctClass) {
        try {
            ctClass.defrost();
            byte[] bytecode = ctClass.toBytecode();
            loadClass(new ClassData(name, bytecode));
        } catch (IOException | CannotCompileException ex) {
            throw new LoaderException("Unable to load class using Javassist: " + name, ex);
        }
    }
}
Also used : CtClass(javassist.CtClass) ClassData(org.motechproject.mds.domain.ClassData) LoaderException(org.motechproject.mds.exception.loader.LoaderException) IOException(java.io.IOException) CannotCompileException(javassist.CannotCompileException)

Aggregations

CtClass (javassist.CtClass)271 CtMethod (javassist.CtMethod)96 ClassPool (javassist.ClassPool)93 NotFoundException (javassist.NotFoundException)85 Test (org.junit.Test)63 CannotCompileException (javassist.CannotCompileException)62 CtField (javassist.CtField)53 IOException (java.io.IOException)35 CtConstructor (javassist.CtConstructor)26 Method (java.lang.reflect.Method)17 LoaderClassPath (javassist.LoaderClassPath)16 ClassFile (javassist.bytecode.ClassFile)14 ArrayList (java.util.ArrayList)13 ByteArrayInputStream (java.io.ByteArrayInputStream)12 AnnotationsAttribute (javassist.bytecode.AnnotationsAttribute)11 ConstPool (javassist.bytecode.ConstPool)11 File (java.io.File)8 FileNotFoundException (java.io.FileNotFoundException)8 Collectors (java.util.stream.Collectors)8 IllegalClassFormatException (java.lang.instrument.IllegalClassFormatException)7