Inject the byte code required to call the {@code processCandidate} proxy
after class initialization.

@param classfileBuffer the source class file

@return the modified class file
767880
byte[] transformCandidate(byte[] classfileBuffer) {
        // reader --> serial version uid adder --> process candidate hook adapter --> tracing --> writer
        ClassReader reader = new ClassReader(classfileBuffer);
        ClassWriter writer = new ClassWriter(reader, ClassWriter.COMPUTE_MAXS);

        ClassVisitor visitor = writer;
        StringWriter stringWriter = null;
        if (tc.isDumpEnabled()) {
            stringWriter = new StringWriter();
            visitor = new CheckClassAdapter(visitor);
            visitor = new TraceClassVisitor(visitor, new PrintWriter(stringWriter));
        }
        visitor = new ClassAvailableHookClassAdapter(visitor);
        visitor = new SerialVersionUIDAdder(visitor);

        // Process the class
        reader.accept(visitor, 0);

        if (stringWriter != null && tc.isDumpEnabled()) {
            Tr.dump(tc, "Transformed class", stringWriter);
        }

        return writer.toByteArray();
    }
91250
protected InputStream getClassInputStream(String classInternalName) {
        if (classInternalName == null || "".equals(classInternalName)) {
            return null;
        }

        InputStream inputStream = null;
        try {
            for (File jarFile : jarFiles) {
                ZipFile zipFile = new ZipFile(jarFile);
                ZipEntry zipEntry = zipFile.getEntry(classInternalName + ".class");
                if (zipEntry != null) {
                    InputStream zis = zipFile.getInputStream(zipEntry);
                    byte[] bytecode = toByteArray(zis);
                    if (isStreamForClass(new ByteArrayInputStream(bytecode), classInternalName)) {
                        inputStream = new ByteArrayInputStream(bytecode);
                    }
                    zis.close();
                }
                zipFile.close();

                if (inputStream != null) {
                    return inputStream;
                }
            }

            String fileName = classInternalName + ".class";
            fileName = fileName.substring(fileName.lastIndexOf('/') + 1);
            for (File classFile : classFiles) {
                if (classFile.getName().equals(fileName)) {
                    FileInputStream fis = new FileInputStream(classFile);
                    byte[] bytecode = toByteArray(fis);
                    if (isStreamForClass(new ByteArrayInputStream(bytecode), classInternalName)) {
                        inputStream = new ByteArrayInputStream(bytecode);
                    }
                    fis.close();
                }
                if (inputStream != null) {
                    return inputStream;
                }
            }
        } catch (IOException ioe) {
            ioe.printStackTrace();
        }
        return null;
    }
182491
public static File jarFile(Class<?> clazz) throws IOException {
        return jarFile(classFileUrl(clazz), clazz.getName().replace('.', '/') + ".class");
    }
811656
public ByteBuffer getByteBuffer() throws InvalidRequestException
    {
        switch (type)
        {
            case STRING:
                return AsciiType.instance.fromString(text);
            case INTEGER:
                return IntegerType.instance.fromString(text);
            case UUID:
                // we specifically want the Lexical class here, not "UUIDType," because we're supposed to have
                // a uuid-shaped string here, and UUIDType also accepts integer or date strings (and turns them into version 1 uuids).
                return LexicalUUIDType.instance.fromString(text);
            case FLOAT:
              return FloatType.instance.fromString(text);
        }

        // FIXME: handle scenario that should never happen
        return null;
    }
92500
public void load(ByteArrayBuffer buffer)
    throws IOException
  {
    synchronized (this) {
      Source classPath = getClassPath();
    
      buffer.clear();

      int retry = 3;
      for (int i = 0; i < retry; i++) {
        long length = -1;
        
        try (InputStream is = classPath.inputStream()) {
          length = classPath.length();
          long lastModified = classPath.getLastModified();

          if (length < 0)
            throw new IOException("class loading failed because class file '" + classPath + "' does not have a positive length.  Possibly the file has been overwritten");

          buffer.setLength((int) length);

          int results = IoUtil.readAll(is, buffer.getBuffer(), 0, (int) length);

          if (results == length
              && length == classPath.length()
              && lastModified == classPath.getLastModified()) {
            return;
          }

          log.warning(L.l("{0}: class file length mismatch expected={1} received={2}.  The class file may have been modified concurrently.",
                this, length, results));
        }
      }
    }
  }
965396
@SuppressWarnings("unchecked")
   public static <T> T enhance(final ClassLoader loader, Object instance, ForgeProxy handler)
   {
      Assert.notNull(loader, "ClassLoader must not be null");
      Assert.notNull(handler, "ForgeProxy handler must not be null");

      if (instance == null)
         return null;

      Class<?> type = Proxies.unwrapProxyTypes(instance.getClass(), loader);

      Object result = null;

      Class<?> proxyType = getCachedProxyType(loader, type);
      if (proxyType == null)
      {
         Class<?>[] hierarchy = null;
         Class<?> superclass = null;

         hierarchy = ProxyTypeInspector.getCompatibleClassHierarchy(loader, type);
         if (hierarchy == null || hierarchy.length == 0)
            throw new IllegalArgumentException("Must specify at least one non-final type to enhance for Object: "
                     + instance + " of type " + instance.getClass());

         Class<?> first = hierarchy[0];
         if (!first.isInterface() && !isProxyType(first))
         {
            superclass = Proxies.unwrapProxyTypes(first, loader);
            hierarchy = Arrays.shiftLeft(hierarchy, new Class<?>[hierarchy.length - 1]);
         }
         else if (isProxyType(first))
            hierarchy = Arrays.shiftLeft(hierarchy, new Class<?>[hierarchy.length - 1]);

         int index = Arrays.indexOf(hierarchy, ProxyObject.class);
         if (index >= 0)
         {
            hierarchy = Arrays.removeElementAtIndex(hierarchy, index);
         }

         if (!Proxies.isProxyType(first) && !Arrays.contains(hierarchy, ForgeProxy.class))
            hierarchy = Arrays.append(hierarchy, ForgeProxy.class);

         ProxyFactory f = new ProxyFactory()
         {
            @Override
            protected ClassLoader getClassLoader()
            {
               return loader;
            }
         };

         f.setInterfaces(hierarchy);
         f.setSuperclass(superclass);
         f.setFilter(filter);

         proxyType = f.createClass();

         setCachedProxyType(loader, type, proxyType);
      }

      try
      {
         result = proxyType.getDeclaredConstructor().newInstance();
      }
      catch (InstantiationException e)
      {
         throw new IllegalStateException(
                  "Could not instantiate proxy for object [" + instance + "] of type [" + type
                           + "]. For optimal proxy compatibility, ensure " +
                           "that this type is an interface, or a class with a default constructor.",
                  e);
      }
      catch (NoSuchMethodException e)
      {
         throw new IllegalStateException(
                  "Could not instantiate proxy for object [" + instance + "] of type [" + type
                           + "] because there isn't a public default constructor. For optimal proxy compatibility, "
                           + "ensure that this type is an interface, or a class with a default constructor.",
                  e);
      }
      catch (IllegalAccessException | InvocationTargetException e)
      {
         throw new IllegalStateException(e);
      }

      if (result instanceof Proxy)
         ((Proxy) result).setHandler(handler);
      else if (result instanceof ProxyObject)
         ((ProxyObject) result).setHandler(handler);
      else
         throw new IllegalStateException("Could not set proxy handler [" + handler + "] for proxy object ["
                  + result + "] for instance object [" + instance + "] of type [" + instance.getClass() + "]");

      return (T) result;
   }
188857
private byte[] enhancement(ClassLoader classLoader, byte[] classfileBuffer) {

    ClassReader cr = new ClassReader(classfileBuffer);
    CLAwareClassWriter cw = new CLAwareClassWriter(FLAGS, classLoader);
    TypeQueryClassAdapter ca = new TypeQueryClassAdapter(cw, enhanceContext);

    try {

      cr.accept(ca, ClassReader.EXPAND_FRAMES);
      if (ca.isLog(9)) {
        ca.log("... completed");
      }
      return cw.toByteArray();

    } catch (AlreadyEnhancedException e) {
      if (ca.isLog(1)) {
        ca.log("already enhanced");
      }
      return null;

    } catch (NoEnhancementRequiredException e) {
      if (ca.isLog(9)) {
        ca.log("... skipping, no enhancement required");
      }
      return null;
    }
  }
801431
public static ByteBuf getByteBufFromReadableBuffer(ReadableBuffer buffer) {
    if (!sZeroCopyReceiveSupported) {
      return null;
    }
    try {
      if (buffer instanceof CompositeReadableBuffer) {
        Queue<ReadableBuffer> buffers = (Queue<ReadableBuffer>) sCompositeBuffers.get(buffer);
        if (buffers.size() == 1) {
          return getByteBufFromReadableBuffer(buffers.peek());
        } else {
          CompositeByteBuf buf = PooledByteBufAllocator.DEFAULT.compositeBuffer();
          for (ReadableBuffer readableBuffer : buffers) {
            ByteBuf subBuffer = getByteBufFromReadableBuffer(readableBuffer);
            if (subBuffer == null) {
              return null;
            }
            buf.addComponent(true, subBuffer);
          }
          return buf;
        }
      } else if (buffer.getClass().equals(sReadableByteBuf.getDeclaringClass())) {
        return (ByteBuf) sReadableByteBuf.get(buffer);
      }
    } catch (Exception e) {
      LOG.warn("Failed to get data buffer from stream: {}.", e.getMessage());
      return null;
    }
    return null;
  }
652849
@Override
    public void accept(ClassWriterOutputVisitor visitor) throws IOException {
        proxyBeanDefinitionWriter.accept(visitor);
        try (OutputStream out = visitor.visitClass(proxyFullName)) {
            out.write(classWriter.toByteArray());
            for (ExecutableMethodWriter method : proxiedMethods) {
                method.accept(visitor);
            }
        }
    }
1202431
@Override
    protected void generateEqualsMethod(ClassFile proxyClassType) {
        ClassMethod method = proxyClassType.addMethod(AccessFlag.PUBLIC, "equals", BytecodeUtils.BOOLEAN_CLASS_DESCRIPTOR, LJAVA_LANG_OBJECT);
        CodeAttribute b = method.getCodeAttribute();
        b.aload(1);
        b.instanceofInstruction(proxyClassType.getName());
        b.returnInstruction();
    }
1172580
protected ClassInjector createClassInjector() throws Exception {
        return new ResolvingInjector
            (mConfig.getContextSource().getContextType().getClassLoader(),
             new File[] {mCompiledDir},
             mConfig.getPackagePrefix(),
             false);
    }
353499
@SuppressWarnings("unchecked")
    private Class<? extends T> generateProxyClass() throws IOException {
        if (ViewProxy.class.isAssignableFrom(mBaseClass)) {
            return mBaseClass;
        }

        Class<? extends T> proxyClass = (Class) sGeneratedProxyClasses.get(mBaseClass);
        if (proxyClass != null &&
                (proxyClass.getClassLoader() == mParentClassLoader ||
                 proxyClass.getClassLoader().getParent() == mParentClassLoader)) {
            // Cache hit; return immediately.
            return proxyClass;
        }

        proxyClass = (Class<? extends T>) findProxyViewClass(mContext, mBaseClass.getName());
        if (proxyClass != null) {
            // This app ships with the build-time proxy.
            sGeneratedProxyClasses.put(mBaseClass, proxyClass);
            return proxyClass;
        }

        try {
            Class.forName("com.google.dexmaker.DexMaker");
            return DexProxyBuilder.generateProxyClass(mContext, mBaseClass);
        } catch (ClassNotFoundException e) {
            return null;
        }
    }
966729
@Override
    public Class<?> getProxyClass() {
        if (proxyClass != null) {
            return proxyClass;
        }
        try {
            if (StringUtils.isNotBlank(interfaceId)) {
                this.proxyClass = ClassUtils.forName(interfaceId);
                if (!proxyClass.isInterface()) {
                    throw ExceptionUtils.buildRuntime("service.interfaceId",
                        interfaceId, "interfaceId must set interface class, not implement class");
                }
            } else {
                throw ExceptionUtils.buildRuntime("service.interfaceId",
                    "null", "interfaceId must be not null");
            }
        } catch (SofaRpcRuntimeException e) {
            throw e;
        } catch (Throwable e) {
            throw new SofaRpcRuntimeException(e.getMessage(), e);
        }
        return proxyClass;
    }
399806
public TemporaryFileBuilder fromClasspathResource(final String pathToResource) {
        final Class<?> callerClass = getCallerClass();
        this.content = getResolver().resolve(pathToResource, callerClass);
        return this;
    }
362030
@Override
    public byte[] transform(ClassLoader loader,
                            String className,
                            Class<?> classBeingRedefined,
                            ProtectionDomain protectionDomain,
                            byte[] classfileBuffer) throws IllegalClassFormatException {
     	if (detailedTransformTrace && tc.isEntryEnabled())
            Tr.entry(this, tc, "transform", loader, className, classBeingRedefined, protectionDomain);

		    	
		if (!isJava8TraceEnabled)
			return null; //Look for special trace instrumentation force until JDK bug fully fixed.
		
		if (classBeingRedefined != null)
        	return null;

        byte[] newClassBytes = null;
        if (isTransformPossible(classfileBuffer)) {
            try {
                newClassBytes = transform(classfileBuffer);
            } catch (Throwable t) {
                Tr.error(tc, "INSTRUMENTATION_TRANSFORM_FAILED_FOR_CLASS_2", className, t);
            }
        }

        if (detailedTransformTrace && tc.isEntryEnabled())
            Tr.exit(this, tc, "transform", newClassBytes);
        return newClassBytes;
    }
1133604
public byte[] transform(ClassLoader loader,
                            String className,
                            Class<?> classBeingRedefined,
                            ProtectionDomain protectionDomain,
                            byte[] classfileBuffer) throws IllegalClassFormatException {

        // Don't modify our own package
        if (className.startsWith(Transformer.class.getPackage().getName().replaceAll("\\.", "/"))) {
            return null;
        }

        // Don't modify the java.util.logging classes
        if (className.startsWith("java/util/logging/")) {
            return null;
        }

        boolean include = false;
        for (String s : includesList) {
            if (className.startsWith(s) || s.equals("/")) {
                include = true;
                break;
            }
        }

        for (String s : excludesList) {
            if (className.startsWith(s) || s.equals("/")) {
                include = false;
                break;
            }
        }

        if (include == false) {
            return null;
        }

        String internalPackageName = className.replaceAll("/[^/]+$", "");
        PackageInfo packageInfo = getPackageInfo(internalPackageName);
        if (packageInfo == null && loader != null) {
            String packageInfoResourceName = internalPackageName + "/package-info.class";
            InputStream is = loader.getResourceAsStream(packageInfoResourceName);
            packageInfo = processPackageInfo(is);
            addPackageInfo(packageInfo);
        }

        try {
            return transform(new ByteArrayInputStream(classfileBuffer));
        } catch (Throwable t) {
            t.printStackTrace();
            return null;
        }
    }
1072297
@FFDCIgnore(Exception.class)
    protected void addStaticFilePatternMappings(RequestProcessor proxyReqProcessor) {
        String nextPattern;
        ExtensionProcessor fileExtensionProcessor = getDefaultExtensionProcessor(this, getConfiguration().getFileServingAttributes());

        List patternList = fileExtensionProcessor.getPatternList();
        Iterator patternIter = patternList.iterator();
        int globalPatternsCount = 0;
        while (patternIter.hasNext()) {
            nextPattern = (String) patternIter.next(); // PK18713
            try {
                if (proxyReqProcessor == null)
                    requestMapper.addMapping(nextPattern, fileExtensionProcessor); // PK18713
                else
                    requestMapper.addMapping(nextPattern, proxyReqProcessor);
            } catch (Exception e) {
                // Mapping clash. Log error
                // pk435011
                // LIBERTY: Fix for RTC defect 49695 -- The logging level should match the severity of the message.
                if (!!!"/*".equals(nextPattern)) {
                    logger.logp(Level.SEVERE, CLASS_NAME, "initializeStaticFileHandler", "error.adding.servlet.mapping.file.handler", nextPattern);
                } else {
                    globalPatternsCount++;
                }
            }
        }
        
        if (globalPatternsCount > 1) {
            logger.logp(Level.SEVERE, CLASS_NAME, "initializeStaticFileHandler", "error.adding.servlet.mapping.file.handler", "/*");
        }
    }