Examines {@link StackTraceElement}s to figure out which class invoked a method on {@link CDI}.
505719
protected String getCallingClassName() {
        boolean outerSubclassReached = false;
        for (StackTraceElement element : Thread.currentThread().getStackTrace()) {
            // the method call that leads to the first invocation of this class or its subclass is considered the caller
            if (!knownClassNames.contains(element.getClassName())) {
                if (outerSubclassReached) {
                    return element.getClassName();
                }
            } else {
                outerSubclassReached = true;
            }
        }
        throw BeanManagerLogger.LOG.unableToIdentifyBeanManager();
    }
587099
public static StackTraceElement getStackTraceElement(int i) {
		StackTraceElement[] stackTrace = getStackTrace();
		if (i < 0) {
			i += stackTrace.length;
		}
		return stackTrace[i];
	}
724534
public StackTraceElement getStackTraceElement(Throwable throwable, int n) {
    try {
      return (StackTraceElement) getElementMethod.invoke(javaLangAccess, throwable, n);
    } catch (InvocationTargetException e) {
      // The only case we should expect to see here normally is a wrapped IndexOutOfBoundsException.
      if (e.getCause() instanceof RuntimeException) {
        throw (RuntimeException) e.getCause();
      } else if (e.getCause() instanceof Error) {
        throw (Error) e.getCause();
      }
      // This should not be possible because the getStackTraceElement() method does not declare
      // any checked exceptions (though APIs may change over time).
      throw new RuntimeException(e.getCause());
    } catch (IllegalAccessException e) {
      // This should never happen because the method has been successfully invoked once already.
      throw new AssertionError(e);
    }
  }
951402
public void identifyClasses(final String pluginDirectory) throws Exception {
        methodInformation.clear();
        jarInformation.clear();
        try {
            new FileTraversal() {
                public void onDirectory(final File d) {
                }

                public void onFile(final File f) {
                    try {
                        // loads class files
                        if (f.getName().endsWith(".class")) {
                            // get the class name for this path
                            String className = f.getAbsolutePath();
                            className = className.replace(pluginDirectory, "");
                            className = getClassNameFromPath(className);

                            logger.info("Storing plugin information: {}, {}", className,
                                        f.getName());

                            ClassInformation classInfo = new ClassInformation();
                            classInfo.pluginPath = pluginDirectory;
                            classInformation.put(className, classInfo);
                        } else if (f.getName().endsWith(".jar")) {
                            // loads JAR packages
                            // open up jar and discover files
                            // look for anything with /proxy/ in it
                            // this may discover things we don't need but that is OK
                            try {
                                jarInformation.add(f.getAbsolutePath());
                                JarFile jarFile = new JarFile(f);
                                Enumeration<?> enumer = jarFile.entries();

                                // Use the Plugin-Name manifest entry to match with the provided pluginName
                                String pluginPackageName = jarFile.getManifest().getMainAttributes().getValue("plugin-package");
                                if (pluginPackageName == null) {
                                    return;
                                }

                                while (enumer.hasMoreElements()) {
                                    Object element = enumer.nextElement();
                                    String elementName = element.toString();

                                    if (!elementName.endsWith(".class")) {
                                        continue;
                                    }

                                    String className = getClassNameFromPath(elementName);
                                    if (className.contains(pluginPackageName)) {
                                        logger.info("Storing plugin information: {}, {}", className,
                                                    f.getAbsolutePath());

                                        ClassInformation classInfo = new ClassInformation();
                                        classInfo.pluginPath = f.getAbsolutePath();
                                        classInformation.put(className, classInfo);
                                    }
                                }
                            } catch (Exception e) {

                            }
                        }
                    } catch (Exception e) {
                        logger.warn("Exception caught: {}, {}", e.getMessage(), e.getCause());
                    }
                }
            }.traverse(new File(pluginDirectory));
        } catch (IOException e) {
            throw new Exception("Could not identify all plugins: " + e.getMessage());
        }
    }
673476
@Override
    public void trace( F0<Throwable> exception )
    {
        if ( compilerLogger.isDebugEnabled() )
        {
            compilerLogger.debug( exception.apply() );
        }
    }
927177
protected boolean isMethodInstrumentedByThisAdapter() {
        if (injectedTraceAnnotationVisitor == null) {
            return false;
        }

        List<String> visitedMethodAdapters = injectedTraceAnnotationVisitor.getMethodAdapters();
        return visitedMethodAdapters.contains(getClass().getName());
    }
995656
public static Method findDeclaredMethod(Class<?> cl, Method testMethod)
  {
    if (cl == null)
      return null;
    
    for (Method method : cl.getDeclaredMethods()) {
      if (isMatch(method, testMethod))
        return method;
    }
    
    return null;
  }
390081
protected static StackTraceElement[] parseStackTrace(String stacktrace) {
        try (BufferedReader reader = new BufferedReader(new StringReader(stacktrace))) {
            List<StackTraceElement> elements = new ArrayList<>();
            String line;
            // Example lines:
            // \tat io.apiman.gateway.engine.es.ESRegistry$1.completed(ESRegistry.java:79)
            // \tat org.apache.http.impl.nio.client.InternalIODispatch.onInputReady(InternalIODispatch.java:81)\r\n
            while ( (line = reader.readLine()) != null) {
                if (line.startsWith("\tat ")) { //$NON-NLS-1$
                    int openParenIdx = line.indexOf('(');
                    int closeParenIdx = line.indexOf(')');
                    String classAndMethod = line.substring(4, openParenIdx);
                    String fileAndLineNum = line.substring(openParenIdx + 1, closeParenIdx);
                    String className = classAndMethod.substring(0, classAndMethod.lastIndexOf('.'));
                    String methodName = classAndMethod.substring(classAndMethod.lastIndexOf('.') + 1);
                    String [] split = fileAndLineNum.split(":"); //$NON-NLS-1$
                    if (split.length == 1) {
                        elements.add(new StackTraceElement(className, methodName, fileAndLineNum, -1));
                    } else {
                        String fileName = split[0];
                        String lineNum = split[1];
                        elements.add(new StackTraceElement(className, methodName, fileName, new Integer(lineNum)));
                    }
                }
            }
            return elements.toArray(new StackTraceElement[elements.size()]);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
812168
public static boolean isGetterMethod(ClassContext classContext, Method method) {
        MethodGen methodGen = classContext.getMethodGen(method);
        if (methodGen == null) {
            return false;
        }
        InstructionList il = methodGen.getInstructionList();
        // System.out.println("Checking getter method: " + method.getName());
        if (il.getLength() > 60) {
            return false;
        }

        int count = 0;
        Iterator<InstructionHandle> it = il.iterator();
        while (it.hasNext()) {
            InstructionHandle ih = it.next();
            switch (ih.getInstruction().getOpcode()) {
            case Const.GETFIELD:
                count++;
                if (count > 1) {
                    return false;
                }
                break;
            case Const.PUTFIELD:
            case Const.BALOAD:
            case Const.CALOAD:
            case Const.DALOAD:
            case Const.FALOAD:
            case Const.IALOAD:
            case Const.LALOAD:
            case Const.SALOAD:
            case Const.AALOAD:
            case Const.BASTORE:
            case Const.CASTORE:
            case Const.DASTORE:
            case Const.FASTORE:
            case Const.IASTORE:
            case Const.LASTORE:
            case Const.SASTORE:
            case Const.AASTORE:
            case Const.PUTSTATIC:
                return false;
            case Const.INVOKESTATIC:
            case Const.INVOKEVIRTUAL:
            case Const.INVOKEINTERFACE:
            case Const.INVOKESPECIAL:
            case Const.GETSTATIC:
                // no-op

            }
        }
        // System.out.println("Found getter method: " + method.getName());
        return true;
    }
32309
Optional<ExecutableElement> findAccessibleNoArgumentInstanceMethod(TypeElement classElement, String methodName) {
        return ElementFilter.methodsIn(elementUtils.getAllMembers(classElement))
                .stream().filter(m -> m.getSimpleName().toString().equals(methodName) && !isPrivate(m) && !isStatic(m))
                .findFirst();
    }
852853
int getMethodIndex(ExecutableElement method)
    {
        TypeElement declaringClass = (TypeElement) method.getEnclosingElement();
        String fullyQualifiedname = declaringClass.getQualifiedName().toString();
        return getRefIndex(Methodref.class, fullyQualifiedname, method.getSimpleName().toString(), Descriptor.getDesriptor(method));
    }
1072545
@Override
    public void visitClass(ClassDescriptor classDescriptor) throws CheckedAnalysisException {

        // Just get the ClassContext from the analysis cache
        // and apply the detector to it.

        IAnalysisCache analysisCache = Global.getAnalysisCache();
        ClassContext classContext = analysisCache.getClassAnalysis(ClassContext.class, classDescriptor);
        Profiler profiler = analysisCache.getProfiler();
        profiler.start(detector.getClass());
        try {
            detector.visitClassContext(classContext);
        } finally {
            profiler.end(detector.getClass());
        }
    }
292847
private void computeStackTraceInformation(
        StackTraceFilter stackTraceFilter, Throwable stackTraceHolder, boolean isInline) {
        StackTraceElement filtered = stackTraceFilter.filterFirst(stackTraceHolder, isInline);

        // there are corner cases where exception can have a null or empty stack trace
        // for example, a custom exception can override getStackTrace() method
        if (filtered == null) {
            this.stackTraceLine = "-> at <<unknown line>>";
            this.sourceFile = "<unknown source file>";
        } else {
            this.stackTraceLine = "-> at " + filtered.toString();
            this.sourceFile = filtered.getFileName();
        }
    }
307144
private EJBInterceptorBinding findInterceptorBindingForMethod(final Method method)
    {
        final boolean isTraceOn = TraceComponent.isAnyTracingEnabled();
        if (isTraceOn && tc.isEntryEnabled())
        {
            Tr.entry(tc, "findInterceptorBindingForMethod: " + method.toString());
        }

        // Use style 4 binding if there is one for the method.
        String methodSignature = MethodAttribUtils.methodSignature(method);
        if (isTraceOn && tc.isDebugEnabled())
        {
            Tr.debug(tc, "lookup style 4 for method signature: " + methodSignature);
        }
        EJBInterceptorBinding binding = ivStyle4InterceptorBindingMap.get(methodSignature);

        // If no Style 4 binding, then see if there is a Style 3 binding.
        if (binding == null)
        {
            String methodName = method.getName();
            if (isTraceOn && tc.isDebugEnabled())
            {
                Tr.debug(tc, "lookup style 3 for method: " + methodName);
            }
            binding = ivStyle3InterceptorBindingMap.get(methodName);
        }

        if (isTraceOn && tc.isEntryEnabled())
        {
            if (binding != null)
            {
                Tr.exit(tc, "findInterceptorBindingForMethod found: ");
                binding.dump();
            }
            else
            {
                Tr.exit(tc, "findInterceptorBindingForMethod, interceptor-binding not found");
            }
        }
        return binding;
    }
415016
public String getMethodBytecode(final String methodName,
                                    final ClassReader classReader) {
        final Tracer visit = new Tracer( methodName );
        classReader.accept( visit, ClassReader.SKIP_DEBUG );
        return visit.getText();
    }
728467
@SuppressWarnings("unchecked")
    private boolean isMethodAlreadyInjectedAnnotationPresent(MethodNode methodNode) {
        AnnotationNode injectedTraceAnnotation = getAnnotation(INJECTED_TRACE_TYPE.getDescriptor(), methodNode.visibleAnnotations);
        AnnotationNode manualTraceAnnotation = getAnnotation(MANUAL_TRACE_TYPE.getDescriptor(), methodNode.visibleAnnotations);
        if (manualTraceAnnotation != null)
            return true;

        if (injectedTraceAnnotation != null) {
            InjectedTraceAnnotationVisitor itav = new InjectedTraceAnnotationVisitor();
            injectedTraceAnnotation.accept(itav);
            List<String> methodAdapters = itav.getMethodAdapters();
            if (methodAdapters.contains(LibertyTracingMethodAdapter.class.getName())) {
                return true;
            }
            if (methodAdapters.contains(WebSphereTrTracingMethodAdapter.class.getName())) {
                return true;
            }
            if (methodAdapters.contains(JSR47TracingMethodAdapter.class.getName())) {
                return true;
            }
        }
        return false;
    }
754072
private static StackTraceElementsFiller getStackTraceElementsFiller() {
		try {
			Method method = VMStack.class.getDeclaredMethod("fillStackTraceElements", Thread.class, StackTraceElement[].class);
			method.setAccessible(true);
			StackTraceElement[] trace = new StackTraceElement[STACK_TRACE_SIZE];
			method.invoke(null, Thread.currentThread(), trace);
			for (int i = 0; i < STACK_TRACE_SIZE; ++i) {
				StackTraceElement element = trace[i];
				if (element != null && AndroidRuntime.class.getName().equals(element.getClassName())
					&& "getStackTraceElementsFiller".equals(element.getMethodName())) {
					return new StackTraceElementsFiller(method, i);
				}
			}
			return new StackTraceElementsFiller(null, -1);
		} catch (NoClassDefFoundError error) {
			return new StackTraceElementsFiller(null, -1);
		} catch (Exception ex) {
			return new StackTraceElementsFiller(null, -1);
		}
	}