code
stringlengths
73
34.1k
label
stringclasses
1 value
void endIfStarted(CodeAttribute b, ClassMethod method) { b.aload(getLocalVariableIndex(0)); b.dup(); final BranchEnd ifnotnull = b.ifnull(); b.checkcast(Stack.class); b.invokevirtual(Stack.class.getName(), END_INTERCEPTOR_CONTEXT_METHOD_NAME, EMPTY_PARENTHESES + VOID_CLASS_DESCRIPTOR); BranchEnd ifnull = b.gotoInstruction(); b.branchEnd(ifnotnull); b.pop(); // remove null Stack b.branchEnd(ifnull); }
java
@Override @SuppressFBWarnings(value = "UL_UNRELEASED_LOCK", justification = "False positive from FindBugs") public <T> T get(Contextual<T> contextual, CreationalContext<T> creationalContext) { if (!isActive()) { throw new ContextNotActiveException(); } checkContextInitialized(); final BeanStore beanStore = getBeanStore(); if (beanStore == null) { return null; } if (contextual == null) { throw ContextLogger.LOG.contextualIsNull(); } BeanIdentifier id = getId(contextual); ContextualInstance<T> beanInstance = beanStore.get(id); if (beanInstance != null) { return beanInstance.getInstance(); } else if (creationalContext != null) { LockedBean lock = null; try { if (multithreaded) { lock = beanStore.lock(id); beanInstance = beanStore.get(id); if (beanInstance != null) { return beanInstance.getInstance(); } } T instance = contextual.create(creationalContext); if (instance != null) { beanInstance = new SerializableContextualInstanceImpl<Contextual<T>, T>(contextual, instance, creationalContext, serviceRegistry.get(ContextualStore.class)); beanStore.put(id, beanInstance); } return instance; } finally { if (lock != null) { lock.unlock(); } } } else { return null; } }
java
protected void destroy() { ContextLogger.LOG.contextCleared(this); final BeanStore beanStore = getBeanStore(); if (beanStore == null) { throw ContextLogger.LOG.noBeanStoreAvailable(this); } for (BeanIdentifier id : beanStore) { destroyContextualInstance(beanStore.get(id)); } beanStore.clear(); }
java
public static <T> boolean addAll(Collection<T> target, Iterable<? extends T> iterable) { if (iterable instanceof Collection) { return target.addAll((Collection<? extends T>) iterable); } return Iterators.addAll(target, iterable.iterator()); }
java
@Override public <T> Producer<T> createProducer(final Bean<X> declaringBean, final Bean<T> bean, DisposalMethod<X, T> disposalMethod) { EnhancedAnnotatedField<T, X> enhancedField = getManager().getServices().get(MemberTransformer.class).loadEnhancedMember(field, getManager().getId()); return new ProducerFieldProducer<X, T>(enhancedField, disposalMethod) { @Override public AnnotatedField<X> getAnnotated() { return field; } @Override public BeanManagerImpl getBeanManager() { return getManager(); } @Override public Bean<X> getDeclaringBean() { return declaringBean; } @Override public Bean<T> getBean() { return bean; } }; }
java
protected WeldBeanDeploymentArchive createAdditionalBeanDeploymentArchive() { WeldBeanDeploymentArchive additionalBda = new WeldBeanDeploymentArchive(ADDITIONAL_BDA_ID, Collections.synchronizedSet(new HashSet<String>()), null); additionalBda.getServices().addAll(getServices().entrySet()); beanDeploymentArchives.add(additionalBda); setBeanDeploymentArchivesAccessibility(); return additionalBda; }
java
protected void setBeanDeploymentArchivesAccessibility() { for (WeldBeanDeploymentArchive beanDeploymentArchive : beanDeploymentArchives) { Set<WeldBeanDeploymentArchive> accessibleArchives = new HashSet<>(); for (WeldBeanDeploymentArchive candidate : beanDeploymentArchives) { if (candidate.equals(beanDeploymentArchive)) { continue; } accessibleArchives.add(candidate); } beanDeploymentArchive.setAccessibleBeanDeploymentArchives(accessibleArchives); } }
java
static Type parseType(String value, ResourceLoader resourceLoader) { value = value.trim(); // Wildcards if (value.equals(WILDCARD)) { return WildcardTypeImpl.defaultInstance(); } if (value.startsWith(WILDCARD_EXTENDS)) { Type upperBound = parseType(value.substring(WILDCARD_EXTENDS.length(), value.length()), resourceLoader); if (upperBound == null) { return null; } return WildcardTypeImpl.withUpperBound(upperBound); } if (value.startsWith(WILDCARD_SUPER)) { Type lowerBound = parseType(value.substring(WILDCARD_SUPER.length(), value.length()), resourceLoader); if (lowerBound == null) { return null; } return WildcardTypeImpl.withLowerBound(lowerBound); } // Array if (value.contains(ARRAY)) { Type componentType = parseType(value.substring(0, value.indexOf(ARRAY)), resourceLoader); if (componentType == null) { return null; } return new GenericArrayTypeImpl(componentType); } int chevLeft = value.indexOf(CHEVRONS_LEFT); String rawValue = chevLeft < 0 ? value : value.substring(0, chevLeft); Class<?> rawRequiredType = tryLoadClass(rawValue, resourceLoader); if (rawRequiredType == null) { return null; } if (rawRequiredType.getTypeParameters().length == 0) { return rawRequiredType; } // Parameterized type int chevRight = value.lastIndexOf(CHEVRONS_RIGHT); if (chevRight < 0) { return null; } List<String> parts = split(value.substring(chevLeft + 1, chevRight), ',', CHEVRONS_LEFT.charAt(0), CHEVRONS_RIGHT.charAt(0)); Type[] typeParameters = new Type[parts.size()]; for (int i = 0; i < typeParameters.length; i++) { Type typeParam = parseType(parts.get(i), resourceLoader); if (typeParam == null) { return null; } typeParameters[i] = typeParam; } return new ParameterizedTypeImpl(rawRequiredType, typeParameters); }
java
public static boolean isPortletEnvSupported() { if (enabled == null) { synchronized (PortletSupport.class) { if (enabled == null) { try { PortletSupport.class.getClassLoader().loadClass("javax.portlet.PortletContext"); enabled = true; } catch (Throwable ignored) { enabled = false; } } } } return enabled; }
java
public static BeanManager getBeanManager(Object ctx) { return (BeanManager) javax.portlet.PortletContext.class.cast(ctx).getAttribute(WeldServletLifecycle.BEAN_MANAGER_ATTRIBUTE_NAME); }
java
private <T> List<Class<?>> filter(List<Class<?>> enabledClasses, List<Class<?>> globallyEnabledClasses, LogMessageCallback logMessageCallback, BeanDeployment deployment) { for (Iterator<Class<?>> iterator = enabledClasses.iterator(); iterator.hasNext(); ) { Class<?> enabledClass = iterator.next(); if (globallyEnabledClasses.contains(enabledClass)) { logMessageCallback.log(enabledClass, deployment.getBeanDeploymentArchive().getId()); iterator.remove(); } } return enabledClasses; }
java
public F resolve(R resolvable, boolean cache) { R wrappedResolvable = wrap(resolvable); if (cache) { return resolved.getValue(wrappedResolvable); } else { return resolverFunction.apply(wrappedResolvable); } }
java
private Set<T> findMatching(R resolvable) { Set<T> result = new HashSet<T>(); for (T bean : getAllBeans(resolvable)) { if (matches(resolvable, bean)) { result.add(bean); } } return result; }
java
public <X> Set<DisposalMethod<X, ?>> resolveDisposalBeans(Set<Type> types, Set<Annotation> qualifiers, AbstractClassBean<X> declaringBean) { // We can always cache as this is only ever called by Weld where we avoid non-static inner classes for annotation literals Set<DisposalMethod<X, ?>> beans = cast(disposalMethodResolver.resolve(new ResolvableBuilder(manager).addTypes(types).addQualifiers(qualifiers).setDeclaringBean(declaringBean).create(), true)); resolvedDisposalBeans.addAll(beans); return Collections.unmodifiableSet(beans); }
java
private static <T> Set<Type> getSessionBeanTypes(EnhancedAnnotated<T, ?> annotated, EjbDescriptor<T> ejbDescriptor) { ImmutableSet.Builder<Type> types = ImmutableSet.builder(); // session beans Map<Class<?>, Type> typeMap = new LinkedHashMap<Class<?>, Type>(); HierarchyDiscovery beanClassDiscovery = HierarchyDiscovery.forNormalizedType(ejbDescriptor.getBeanClass()); for (BusinessInterfaceDescriptor<?> businessInterfaceDescriptor : ejbDescriptor.getLocalBusinessInterfaces()) { // first we need to resolve the local interface Type resolvedLocalInterface = beanClassDiscovery.resolveType(Types.getCanonicalType(businessInterfaceDescriptor.getInterface())); SessionBeanHierarchyDiscovery interfaceDiscovery = new SessionBeanHierarchyDiscovery(resolvedLocalInterface); if (beanClassDiscovery.getTypeMap().containsKey(businessInterfaceDescriptor.getInterface())) { // WELD-1675 Only add types also included in Annotated.getTypeClosure() for (Entry<Class<?>, Type> entry : interfaceDiscovery.getTypeMap().entrySet()) { if (annotated.getTypeClosure().contains(entry.getValue())) { typeMap.put(entry.getKey(), entry.getValue()); } } } else { // Session bean class does not implement the business interface and @javax.ejb.Local applied to the session bean class typeMap.putAll(interfaceDiscovery.getTypeMap()); } } if (annotated.isAnnotationPresent(Typed.class)) { types.addAll(Beans.getTypedTypes(typeMap, annotated.getJavaClass(), annotated.getAnnotation(Typed.class))); } else { typeMap.put(Object.class, Object.class); types.addAll(typeMap.values()); } return Beans.getLegalBeanTypes(types.build(), annotated); }
java
public static <T> SessionBean<T> of(BeanAttributes<T> attributes, InternalEjbDescriptor<T> ejbDescriptor, BeanManagerImpl beanManager, EnhancedAnnotatedType<T> type) { return new SessionBeanImpl<T>(attributes, type, ejbDescriptor, new StringBeanIdentifier(SessionBeans.createIdentifier(type, ejbDescriptor)), beanManager); }
java
protected void checkConflictingRoles() { if (getType().isAnnotationPresent(Interceptor.class)) { throw BeanLogger.LOG.ejbCannotBeInterceptor(getType()); } if (getType().isAnnotationPresent(Decorator.class)) { throw BeanLogger.LOG.ejbCannotBeDecorator(getType()); } }
java
protected void checkScopeAllowed() { if (ejbDescriptor.isStateless() && !isDependent()) { throw BeanLogger.LOG.scopeNotAllowedOnStatelessSessionBean(getScope(), getType()); } if (ejbDescriptor.isSingleton() && !(isDependent() || getScope().equals(ApplicationScoped.class))) { throw BeanLogger.LOG.scopeNotAllowedOnSingletonBean(getScope(), getType()); } }
java
protected void checkObserverMethods() { Collection<EnhancedAnnotatedMethod<?, ? super T>> observerMethods = BeanMethods.getObserverMethods(this.getEnhancedAnnotated()); Collection<EnhancedAnnotatedMethod<?, ? super T>> asyncObserverMethods = BeanMethods.getAsyncObserverMethods(this.getEnhancedAnnotated()); checkObserverMethods(observerMethods); checkObserverMethods(asyncObserverMethods); }
java
public static <T> NewManagedBean<T> of(BeanAttributes<T> attributes, EnhancedAnnotatedType<T> clazz, BeanManagerImpl beanManager) { return new NewManagedBean<T>(attributes, clazz, new StringBeanIdentifier(BeanIdentifiers.forNewManagedBean(clazz)), beanManager); }
java
@Override public Object invoke(Object self, Method method, Method proceed, Object[] args) throws Throwable { if ("destroy".equals(method.getName()) && Marker.isMarker(0, method, args)) { if (bean.getEjbDescriptor().isStateful()) { if (!reference.isRemoved()) { reference.remove(); } } return null; } if (!bean.isClientCanCallRemoveMethods() && isRemoveMethod(method)) { throw BeanLogger.LOG.invalidRemoveMethodInvocation(method); } Class<?> businessInterface = getBusinessInterface(method); if (reference.isRemoved() && isToStringMethod(method)) { return businessInterface.getName() + " [REMOVED]"; } Object proxiedInstance = reference.getBusinessObject(businessInterface); if (!Modifier.isPublic(method.getModifiers())) { throw new EJBException("Not a business method " + method.toString() +". Do not call non-public methods on EJB's."); } Object returnValue = Reflections.invokeAndUnwrap(proxiedInstance, method, args); BeanLogger.LOG.callProxiedMethod(method, proxiedInstance, args, returnValue); return returnValue; }
java
private <T> void deferNotification(T event, final EventMetadata metadata, final ObserverMethod<? super T> observer, final List<DeferredEventNotification<?>> notifications) { TransactionPhase transactionPhase = observer.getTransactionPhase(); boolean before = transactionPhase.equals(TransactionPhase.BEFORE_COMPLETION); Status status = Status.valueOf(transactionPhase); notifications.add(new DeferredEventNotification<T>(contextId, event, metadata, observer, currentEventMetadata, status, before)); }
java
public void build(Set<Bean<?>> beans) { if (isBuilt()) { throw new IllegalStateException("BeanIdentifier index is already built!"); } if (beans.isEmpty()) { index = new BeanIdentifier[0]; reverseIndex = Collections.emptyMap(); indexHash = 0; indexBuilt.set(true); return; } List<BeanIdentifier> tempIndex = new ArrayList<BeanIdentifier>(beans.size()); for (Bean<?> bean : beans) { if (bean instanceof CommonBean<?>) { tempIndex.add(((CommonBean<?>) bean).getIdentifier()); } else if (bean instanceof PassivationCapable) { tempIndex.add(new StringBeanIdentifier(((PassivationCapable) bean).getId())); } } Collections.sort(tempIndex, new Comparator<BeanIdentifier>() { @Override public int compare(BeanIdentifier o1, BeanIdentifier o2) { return o1.asString().compareTo(o2.asString()); } }); index = tempIndex.toArray(new BeanIdentifier[tempIndex.size()]); ImmutableMap.Builder<BeanIdentifier, Integer> builder = ImmutableMap.builder(); for (int i = 0; i < index.length; i++) { builder.put(index[i], i); } reverseIndex = builder.build(); indexHash = Arrays.hashCode(index); if(BootstrapLogger.LOG.isDebugEnabled()) { BootstrapLogger.LOG.beanIdentifierIndexBuilt(getDebugInfo()); } indexBuilt.set(true); }
java
public static <T> FastEvent<T> of(Class<T> type, BeanManagerImpl manager, ObserverNotifier notifier, Annotation... qualifiers) { ResolvedObservers<T> resolvedObserverMethods = notifier.<T> resolveObserverMethods(type, qualifiers); if (resolvedObserverMethods.isMetadataRequired()) { EventMetadata metadata = new EventMetadataImpl(type, null, qualifiers); CurrentEventMetadata metadataService = manager.getServices().get(CurrentEventMetadata.class); return new FastEventWithMetadataPropagation<T>(resolvedObserverMethods, metadata, metadataService); } else { return new FastEvent<T>(resolvedObserverMethods); } }
java
public static <T> List<T> copyOf(T[] elements) { Preconditions.checkNotNull(elements); return ofInternal(elements.clone()); }
java
public static <T> List<T> copyOf(Collection<T> source) { Preconditions.checkNotNull(source); if (source instanceof ImmutableList<?>) { return (ImmutableList<T>) source; } if (source.isEmpty()) { return Collections.emptyList(); } return ofInternal(source.toArray()); }
java
public static Set<Annotation> filterInterceptorBindings(BeanManagerImpl beanManager, Collection<Annotation> annotations) { Set<Annotation> interceptorBindings = new InterceptorBindingSet(beanManager); for (Annotation annotation : annotations) { if (beanManager.isInterceptorBinding(annotation.annotationType())) { interceptorBindings.add(annotation); } } return interceptorBindings; }
java
public static Set<Annotation> flattenInterceptorBindings(EnhancedAnnotatedType<?> clazz, BeanManagerImpl beanManager, Collection<Annotation> annotations, boolean addTopLevelInterceptorBindings, boolean addInheritedInterceptorBindings) { Set<Annotation> flattenInterceptorBindings = new InterceptorBindingSet(beanManager); MetaAnnotationStore metaAnnotationStore = beanManager.getServices().get(MetaAnnotationStore.class); if (addTopLevelInterceptorBindings) { addInterceptorBindings(clazz, annotations, flattenInterceptorBindings, metaAnnotationStore); } if (addInheritedInterceptorBindings) { for (Annotation annotation : annotations) { addInheritedInterceptorBindings(clazz, annotation.annotationType(), metaAnnotationStore, flattenInterceptorBindings); } } return flattenInterceptorBindings; }
java
protected void validateRIBean(CommonBean<?> bean, BeanManagerImpl beanManager, Collection<CommonBean<?>> specializedBeans) { validateGeneralBean(bean, beanManager); if (bean instanceof NewBean) { return; } if (bean instanceof DecorableBean) { validateDecorators(beanManager, (DecorableBean<?>) bean); } if ((bean instanceof AbstractClassBean<?>)) { AbstractClassBean<?> classBean = (AbstractClassBean<?>) bean; // validate CDI-defined interceptors if (classBean.hasInterceptors()) { validateInterceptors(beanManager, classBean); } } // for each producer bean validate its disposer method if (bean instanceof AbstractProducerBean<?, ?, ?>) { AbstractProducerBean<?, ?, ?> producerBean = Reflections.<AbstractProducerBean<?, ?, ?>> cast(bean); if (producerBean.getProducer() instanceof AbstractMemberProducer<?, ?>) { AbstractMemberProducer<?, ?> producer = Reflections.<AbstractMemberProducer<?, ?>> cast(producerBean .getProducer()); if (producer.getDisposalMethod() != null) { for (InjectionPoint ip : producer.getDisposalMethod().getInjectionPoints()) { // pass the producer bean instead of the disposal method bean validateInjectionPointForDefinitionErrors(ip, null, beanManager); validateMetadataInjectionPoint(ip, null, ValidatorLogger.INJECTION_INTO_DISPOSER_METHOD); validateEventMetadataInjectionPoint(ip); validateInjectionPointForDeploymentProblems(ip, null, beanManager); } } } } }
java
public void validateInjectionPoint(InjectionPoint ij, BeanManagerImpl beanManager) { validateInjectionPointForDefinitionErrors(ij, ij.getBean(), beanManager); validateMetadataInjectionPoint(ij, ij.getBean(), ValidatorLogger.INJECTION_INTO_NON_BEAN); validateEventMetadataInjectionPoint(ij); validateInjectionPointForDeploymentProblems(ij, ij.getBean(), beanManager); }
java
private static void validatePseudoScopedBean(Bean<?> bean, BeanManagerImpl beanManager) { if (bean.getInjectionPoints().isEmpty()) { // Skip validation if there are no injection points (e.g. for classes which are not intended to be used as beans) return; } reallyValidatePseudoScopedBean(bean, beanManager, new LinkedHashSet<Object>(), new HashSet<Bean<?>>()); }
java
private static void reallyValidatePseudoScopedBean(Bean<?> bean, BeanManagerImpl beanManager, Set<Object> dependencyPath, Set<Bean<?>> validatedBeans) { // see if we have already seen this bean in the dependency path if (dependencyPath.contains(bean)) { // create a list that shows the path to the bean List<Object> realDependencyPath = new ArrayList<Object>(dependencyPath); realDependencyPath.add(bean); throw ValidatorLogger.LOG.pseudoScopedBeanHasCircularReferences(WeldCollections.toMultiRowString(realDependencyPath)); } if (validatedBeans.contains(bean)) { return; } dependencyPath.add(bean); for (InjectionPoint injectionPoint : bean.getInjectionPoints()) { if (!injectionPoint.isDelegate()) { dependencyPath.add(injectionPoint); validatePseudoScopedInjectionPoint(injectionPoint, beanManager, dependencyPath, validatedBeans); dependencyPath.remove(injectionPoint); } } if (bean instanceof DecorableBean<?>) { final List<Decorator<?>> decorators = Reflections.<DecorableBean<?>>cast(bean).getDecorators(); if (!decorators.isEmpty()) { for (final Decorator<?> decorator : decorators) { reallyValidatePseudoScopedBean(decorator, beanManager, dependencyPath, validatedBeans); } } } if (bean instanceof AbstractProducerBean<?, ?, ?> && !(bean instanceof EEResourceProducerField<?, ?>)) { AbstractProducerBean<?, ?, ?> producer = (AbstractProducerBean<?, ?, ?>) bean; if (!beanManager.isNormalScope(producer.getDeclaringBean().getScope()) && !producer.getAnnotated().isStatic()) { reallyValidatePseudoScopedBean(producer.getDeclaringBean(), beanManager, dependencyPath, validatedBeans); } } validatedBeans.add(bean); dependencyPath.remove(bean); }
java
public static InterceptionContext forConstructorInterception(InterceptionModel interceptionModel, CreationalContext<?> ctx, BeanManagerImpl manager, SlimAnnotatedType<?> type) { return of(interceptionModel, ctx, manager, null, type); }
java
private Set<QualifierInstance> getRequiredQualifiers(EnhancedAnnotatedParameter<?, ? super X> enhancedDisposedParameter) { Set<Annotation> disposedParameterQualifiers = enhancedDisposedParameter.getMetaAnnotations(Qualifier.class); if (disposedParameterQualifiers.isEmpty()) { disposedParameterQualifiers = Collections.<Annotation> singleton(Default.Literal.INSTANCE); } return beanManager.getServices().get(MetaAnnotationStore.class).getQualifierInstances(disposedParameterQualifiers); }
java
public static Type[] getActualTypeArguments(Class<?> clazz) { Type type = Types.getCanonicalType(clazz); if (type instanceof ParameterizedType) { return ((ParameterizedType) type).getActualTypeArguments(); } else { return EMPTY_TYPES; } }
java
public static Type[] getActualTypeArguments(Type type) { Type resolvedType = Types.getCanonicalType(type); if (resolvedType instanceof ParameterizedType) { return ((ParameterizedType) resolvedType).getActualTypeArguments(); } else { return EMPTY_TYPES; } }
java
public static <T> Class<T> loadClass(String className, ResourceLoader resourceLoader) { try { return cast(resourceLoader.classForName(className)); } catch (ResourceLoadingException e) { return null; } catch (SecurityException e) { return null; } }
java
public static Method findDeclaredMethodByName(Class<?> clazz, String methodName) { for (Method method : AccessController.doPrivileged(new GetDeclaredMethodsAction(clazz))) { if (methodName.equals(method.getName())) { return method; } } return null; }
java
public static void main(String[] args) { try { new StartMain(args).go(); } catch(Throwable t) { WeldSELogger.LOG.error("Application exited with an exception", t); System.exit(1); } }
java
public void release(Contextual<T> contextual, T instance) { synchronized (dependentInstances) { for (ContextualInstance<?> dependentInstance : dependentInstances) { // do not destroy contextual again, since it's just being destroyed if (contextual == null || !(dependentInstance.getContextual().equals(contextual))) { destroy(dependentInstance); } } } if (resourceReferences != null) { for (ResourceReference<?> reference : resourceReferences) { reference.release(); } } }
java
public boolean destroyDependentInstance(T instance) { synchronized (dependentInstances) { for (Iterator<ContextualInstance<?>> iterator = dependentInstances.iterator(); iterator.hasNext();) { ContextualInstance<?> contextualInstance = iterator.next(); if (contextualInstance.getInstance() == instance) { iterator.remove(); destroy(contextualInstance); return true; } } } return false; }
java
protected T checkReturnValue(T instance) { if (instance == null && !isDependent()) { throw BeanLogger.LOG.nullNotAllowedFromProducer(getProducer(), Formats.formatAsStackTraceElement(getAnnotated().getJavaMember())); } if (instance == null) { InjectionPoint injectionPoint = beanManager.getServices().get(CurrentInjectionPoint.class).peek(); if (injectionPoint != null) { Class<?> injectionPointRawType = Reflections.getRawType(injectionPoint.getType()); if (injectionPointRawType.isPrimitive()) { return cast(Defaults.getJlsDefaultValue(injectionPointRawType)); } } } if (instance != null && !(instance instanceof Serializable)) { if (beanManager.isPassivatingScope(getScope())) { throw BeanLogger.LOG.nonSerializableProductError(getProducer(), Formats.formatAsStackTraceElement(getAnnotated().getJavaMember())); } InjectionPoint injectionPoint = beanManager.getServices().get(CurrentInjectionPoint.class).peek(); if (injectionPoint != null && injectionPoint.getBean() != null && Beans.isPassivatingScope(injectionPoint.getBean(), beanManager)) { // Transient field is passivation capable injection point if (!(injectionPoint.getMember() instanceof Field) || !injectionPoint.isTransient()) { throw BeanLogger.LOG.unserializableProductInjectionError(this, Formats.formatAsStackTraceElement(getAnnotated().getJavaMember()), injectionPoint, Formats.formatAsStackTraceElement(injectionPoint.getMember())); } } } return instance; }
java
public static <K, V> Map<K, V> copyOf(Map<K, V> map) { Preconditions.checkNotNull(map); return ImmutableMap.<K, V> builder().putAll(map).build(); }
java
public static <K, V> Map<K, V> of(K key, V value) { return new ImmutableMapEntry<K, V>(key, value); }
java
public static String formatAsStackTraceElement(InjectionPoint ij) { Member member; if (ij.getAnnotated() instanceof AnnotatedField) { AnnotatedField<?> annotatedField = (AnnotatedField<?>) ij.getAnnotated(); member = annotatedField.getJavaMember(); } else if (ij.getAnnotated() instanceof AnnotatedParameter<?>) { AnnotatedParameter<?> annotatedParameter = (AnnotatedParameter<?>) ij.getAnnotated(); member = annotatedParameter.getDeclaringCallable().getJavaMember(); } else { // Not throwing an exception, because this method is invoked when an exception is already being thrown. // Throwing an exception here would hide the original exception. return "-"; } return formatAsStackTraceElement(member); }
java
public static int getLineNumber(Member member) { if (!(member instanceof Method || member instanceof Constructor)) { // We are not able to get this info for fields return 0; } // BCEL is an optional dependency, if we cannot load it, simply return 0 if (!Reflections.isClassLoadable(BCEL_CLASS, WeldClassLoaderResourceLoader.INSTANCE)) { return 0; } String classFile = member.getDeclaringClass().getName().replace('.', '/'); ClassLoaderResourceLoader classFileResourceLoader = new ClassLoaderResourceLoader(member.getDeclaringClass().getClassLoader()); InputStream in = null; try { URL classFileUrl = classFileResourceLoader.getResource(classFile + ".class"); if (classFileUrl == null) { // The class file is not available return 0; } in = classFileUrl.openStream(); ClassParser cp = new ClassParser(in, classFile); JavaClass javaClass = cp.parse(); // First get all declared methods and constructors // Note that in bytecode constructor is translated into a method org.apache.bcel.classfile.Method[] methods = javaClass.getMethods(); org.apache.bcel.classfile.Method match = null; String signature; String name; if (member instanceof Method) { signature = DescriptorUtils.methodDescriptor((Method) member); name = member.getName(); } else if (member instanceof Constructor) { signature = DescriptorUtils.makeDescriptor((Constructor<?>) member); name = INIT_METHOD_NAME; } else { return 0; } for (org.apache.bcel.classfile.Method method : methods) { // Matching method must have the same name, modifiers and signature if (method.getName().equals(name) && member.getModifiers() == method.getModifiers() && method.getSignature().equals(signature)) { match = method; } } if (match != null) { // If a method is found, try to obtain the optional LineNumberTable attribute LineNumberTable lineNumberTable = match.getLineNumberTable(); if (lineNumberTable != null) { int line = lineNumberTable.getSourceLine(0); return line == -1 ? 0 : line; } } // No suitable method found return 0; } catch (Throwable t) { return 0; } finally { if (in != null) { try { in.close(); } catch (Exception e) { return 0; } } } }
java
private static List<String> parseModifiers(int modifiers) { List<String> result = new ArrayList<String>(); if (Modifier.isPrivate(modifiers)) { result.add("private"); } if (Modifier.isProtected(modifiers)) { result.add("protected"); } if (Modifier.isPublic(modifiers)) { result.add("public"); } if (Modifier.isAbstract(modifiers)) { result.add("abstract"); } if (Modifier.isFinal(modifiers)) { result.add("final"); } if (Modifier.isNative(modifiers)) { result.add("native"); } if (Modifier.isStatic(modifiers)) { result.add("static"); } if (Modifier.isStrict(modifiers)) { result.add("strict"); } if (Modifier.isSynchronized(modifiers)) { result.add("synchronized"); } if (Modifier.isTransient(modifiers)) { result.add("transient"); } if (Modifier.isVolatile(modifiers)) { result.add("volatile"); } if (Modifier.isInterface(modifiers)) { result.add("interface"); } return result; }
java
private boolean initCheckTypeModifiers() { Class<?> classInfoclass = Reflections.loadClass(CLASSINFO_CLASS_NAME, new ClassLoaderResourceLoader(classFileServices.getClass().getClassLoader())); if (classInfoclass != null) { try { Method setFlags = AccessController.doPrivileged(GetDeclaredMethodAction.of(classInfoclass, "setFlags", short.class)); return setFlags != null; } catch (Exception exceptionIgnored) { BootstrapLogger.LOG.usingOldJandexVersion(); return false; } } else { return true; } }
java
public static <X, T> ProducerMethod<X, T> of(BeanAttributes<T> attributes, EnhancedAnnotatedMethod<T, ? super X> method, AbstractClassBean<X> declaringBean, DisposalMethod<X, ?> disposalMethod, BeanManagerImpl beanManager, ServiceRegistry services) { return new ProducerMethod<X, T>(createId(attributes, method, declaringBean), attributes, method, declaringBean, disposalMethod, beanManager, services); }
java
public static void addLoadInstruction(CodeAttribute code, String type, int variable) { char tp = type.charAt(0); if (tp != 'L' && tp != '[') { // we have a primitive type switch (tp) { case 'J': code.lload(variable); break; case 'D': code.dload(variable); break; case 'F': code.fload(variable); break; default: code.iload(variable); } } else { code.aload(variable); } }
java
public static void pushClassType(CodeAttribute b, String classType) { if (classType.length() != 1) { if (classType.startsWith("L") && classType.endsWith(";")) { classType = classType.substring(1, classType.length() - 1); } b.loadClass(classType); } else { char type = classType.charAt(0); switch (type) { case 'I': b.getstatic(Integer.class.getName(), TYPE, LJAVA_LANG_CLASS); break; case 'J': b.getstatic(Long.class.getName(), TYPE, LJAVA_LANG_CLASS); break; case 'S': b.getstatic(Short.class.getName(), TYPE, LJAVA_LANG_CLASS); break; case 'F': b.getstatic(Float.class.getName(), TYPE, LJAVA_LANG_CLASS); break; case 'D': b.getstatic(Double.class.getName(), TYPE, LJAVA_LANG_CLASS); break; case 'B': b.getstatic(Byte.class.getName(), TYPE, LJAVA_LANG_CLASS); break; case 'C': b.getstatic(Character.class.getName(), TYPE, LJAVA_LANG_CLASS); break; case 'Z': b.getstatic(Boolean.class.getName(), TYPE, LJAVA_LANG_CLASS); break; default: throw new RuntimeException("Cannot handle primitive type: " + type); } } }
java
private void checkBindings(EnhancedAnnotation<T> annotatedAnnotation) { Set<Annotation> bindings = annotatedAnnotation.getMetaAnnotations(Qualifier.class); if (bindings.size() > 0) { for (Annotation annotation : bindings) { if (!annotation.annotationType().equals(Named.class)) { throw MetadataLogger.LOG.qualifierOnStereotype(annotatedAnnotation); } } } }
java
private void initBeanNameDefaulted(EnhancedAnnotation<T> annotatedAnnotation) { if (annotatedAnnotation.isAnnotationPresent(Named.class)) { if (!"".equals(annotatedAnnotation.getAnnotation(Named.class).value())) { throw MetadataLogger.LOG.valueOnNamedStereotype(annotatedAnnotation); } beanNameDefaulted = true; } }
java
private void initDefaultScopeType(EnhancedAnnotation<T> annotatedAnnotation) { Set<Annotation> scopeTypes = new HashSet<Annotation>(); scopeTypes.addAll(annotatedAnnotation.getMetaAnnotations(Scope.class)); scopeTypes.addAll(annotatedAnnotation.getMetaAnnotations(NormalScope.class)); if (scopeTypes.size() > 1) { throw MetadataLogger.LOG.multipleScopes(annotatedAnnotation); } else if (scopeTypes.size() == 1) { this.defaultScopeType = scopeTypes.iterator().next(); } }
java
public static Type boxedType(Type type) { if (type instanceof Class<?>) { return boxedClass((Class<?>) type); } else { return type; } }
java
public static Type getCanonicalType(Class<?> clazz) { if (clazz.isArray()) { Class<?> componentType = clazz.getComponentType(); Type resolvedComponentType = getCanonicalType(componentType); if (componentType != resolvedComponentType) { // identity check intentional // a different identity means that we actually replaced the component Class with a ParameterizedType return new GenericArrayTypeImpl(resolvedComponentType); } } if (clazz.getTypeParameters().length > 0) { Type[] actualTypeParameters = clazz.getTypeParameters(); return new ParameterizedTypeImpl(clazz, actualTypeParameters, clazz.getDeclaringClass()); } return clazz; }
java
public static boolean isArray(Type type) { return (type instanceof GenericArrayType) || (type instanceof Class<?> && ((Class<?>) type).isArray()); }
java
public static Type getArrayComponentType(Type type) { if (type instanceof GenericArrayType) { return GenericArrayType.class.cast(type).getGenericComponentType(); } if (type instanceof Class<?>) { Class<?> clazz = (Class<?>) type; if (clazz.isArray()) { return clazz.getComponentType(); } } throw new IllegalArgumentException("Not an array type " + type); }
java
public static boolean isArrayOfUnboundedTypeVariablesOrObjects(Type[] types) { for (Type type : types) { if (Object.class.equals(type)) { continue; } if (type instanceof TypeVariable<?>) { Type[] bounds = ((TypeVariable<?>) type).getBounds(); if (bounds == null || bounds.length == 0 || (bounds.length == 1 && Object.class.equals(bounds[0]))) { continue; } } return false; } return true; }
java
public <T> T get(Contextual<T> contextual, CreationalContext<T> creationalContext) { if (!isActive()) { throw new ContextNotActiveException(); } if (creationalContext != null) { T instance = contextual.create(creationalContext); if (creationalContext instanceof WeldCreationalContext<?>) { addDependentInstance(instance, contextual, (WeldCreationalContext<T>) creationalContext); } return instance; } else { return null; } }
java
public void createEnablement() { GlobalEnablementBuilder builder = beanManager.getServices().get(GlobalEnablementBuilder.class); ModuleEnablement enablement = builder.createModuleEnablement(this); beanManager.setEnabled(enablement); if (BootstrapLogger.LOG.isDebugEnabled()) { BootstrapLogger.LOG.enabledAlternatives(this.beanManager, WeldCollections.toMultiRowString(enablement.getAllAlternatives())); BootstrapLogger.LOG.enabledDecorators(this.beanManager, WeldCollections.toMultiRowString(enablement.getDecorators())); BootstrapLogger.LOG.enabledInterceptors(this.beanManager, WeldCollections.toMultiRowString(enablement.getInterceptors())); } }
java
public static <T> DecoratorImpl<T> of(BeanAttributes<T> attributes, EnhancedAnnotatedType<T> clazz, BeanManagerImpl beanManager) { return new DecoratorImpl<T>(attributes, clazz, beanManager); }
java
protected void merge(Set<Annotation> stereotypeAnnotations) { final MetaAnnotationStore store = manager.getServices().get(MetaAnnotationStore.class); for (Annotation stereotypeAnnotation : stereotypeAnnotations) { // Retrieve and merge all metadata from stereotypes StereotypeModel<?> stereotype = store.getStereotype(stereotypeAnnotation.annotationType()); if (stereotype == null) { throw MetadataLogger.LOG.stereotypeNotRegistered(stereotypeAnnotation); } if (stereotype.isAlternative()) { alternative = true; } if (stereotype.getDefaultScopeType() != null) { possibleScopeTypes.add(stereotype.getDefaultScopeType()); } if (stereotype.isBeanNameDefaulted()) { beanNameDefaulted = true; } this.stereotypes.add(stereotypeAnnotation.annotationType()); // Merge in inherited stereotypes merge(stereotype.getInheritedStereotypes()); } }
java
@Override public void run() { try { threadContext.activate(); // run the original thread runnable.run(); } finally { threadContext.invalidate(); threadContext.deactivate(); } }
java
protected AbstractBeanDeployer<E> deploySpecialized() { // ensure that all decorators are initialized before initializing // the rest of the beans for (DecoratorImpl<?> bean : getEnvironment().getDecorators()) { bean.initialize(getEnvironment()); containerLifecycleEvents.fireProcessBean(getManager(), bean); manager.addDecorator(bean); BootstrapLogger.LOG.foundDecorator(bean); } for (InterceptorImpl<?> bean : getEnvironment().getInterceptors()) { bean.initialize(getEnvironment()); containerLifecycleEvents.fireProcessBean(getManager(), bean); manager.addInterceptor(bean); BootstrapLogger.LOG.foundInterceptor(bean); } return this; }
java
public static void validateObserverMethod(ObserverMethod<?> observerMethod, BeanManager beanManager, ObserverMethod<?> originalObserverMethod) { Set<Annotation> qualifiers = observerMethod.getObservedQualifiers(); if (observerMethod.getBeanClass() == null) { throw EventLogger.LOG.observerMethodsMethodReturnsNull("getBeanClass", observerMethod); } if (observerMethod.getObservedType() == null) { throw EventLogger.LOG.observerMethodsMethodReturnsNull("getObservedType", observerMethod); } Bindings.validateQualifiers(qualifiers, beanManager, observerMethod, "ObserverMethod.getObservedQualifiers"); if (observerMethod.getReception() == null) { throw EventLogger.LOG.observerMethodsMethodReturnsNull("getReception", observerMethod); } if (observerMethod.getTransactionPhase() == null) { throw EventLogger.LOG.observerMethodsMethodReturnsNull("getTransactionPhase", observerMethod); } if (originalObserverMethod != null && (!observerMethod.getBeanClass().equals(originalObserverMethod.getBeanClass()))) { throw EventLogger.LOG.beanClassMismatch(originalObserverMethod, observerMethod); } if (!(observerMethod instanceof SyntheticObserverMethod) && !hasNotifyOverriden(observerMethod.getClass(), observerMethod)) { throw EventLogger.LOG.notifyMethodNotImplemented(observerMethod); } }
java
private static boolean isAssignableFrom(WildcardType type1, Type type2) { if (!isAssignableFrom(type1.getUpperBounds()[0], type2)) { return false; } if (type1.getLowerBounds().length > 0 && !isAssignableFrom(type2, type1.getLowerBounds()[0])) { return false; } return true; }
java
public static CombinedInterceptorAndDecoratorStackMethodHandler peekIfNotEmpty() { Stack stack = interceptionContexts.get(); if (stack == null) { return null; } return stack.peek(); }
java
public static Stack getStack() { Stack stack = interceptionContexts.get(); if (stack == null) { stack = new Stack(interceptionContexts); interceptionContexts.set(stack); } return stack; }
java
public static boolean isTypesProxyable(Iterable<? extends Type> types, ServiceRegistry services) { return getUnproxyableTypesException(types, services) == null; }
java
public static <T> boolean addAll(Collection<T> target, Iterator<? extends T> iterator) { Preconditions.checkArgumentNotNull(target, "target"); boolean modified = false; while (iterator.hasNext()) { modified |= target.add(iterator.next()); } return modified; }
java
public static <T> Iterator<T> concat(Iterator<? extends Iterator<? extends T>> iterators) { Preconditions.checkArgumentNotNull(iterators, "iterators"); return new CombinedIterator<T>(iterators); }
java
HtmlTag attr(String name, String value) { if (attrs == null) { attrs = new HashMap<>(); } attrs.put(name, value); return this; }
java
public void clearAnnotationData(Class<? extends Annotation> annotationClass) { stereotypes.invalidate(annotationClass); scopes.invalidate(annotationClass); qualifiers.invalidate(annotationClass); interceptorBindings.invalidate(annotationClass); }
java
public static <K, V> Map<K, V> immutableMapView(Map<K, V> map) { if (map instanceof ImmutableMap<?, ?>) { return map; } return Collections.unmodifiableMap(map); }
java
protected void checkProducerMethod(EnhancedAnnotatedMethod<T, ? super X> method) { if (method.getEnhancedParameters(Observes.class).size() > 0) { throw BeanLogger.LOG.inconsistentAnnotationsOnMethod(PRODUCER_ANNOTATION, "@Observes", this.method, Formats.formatAsStackTraceElement(method.getJavaMember())); } else if (method.getEnhancedParameters(ObservesAsync.class).size() > 0) { throw BeanLogger.LOG.inconsistentAnnotationsOnMethod(PRODUCER_ANNOTATION, "@ObservesAsync", this.method, Formats.formatAsStackTraceElement(method.getJavaMember())); } else if (method.getEnhancedParameters(Disposes.class).size() > 0) { throw BeanLogger.LOG.inconsistentAnnotationsOnMethod(PRODUCER_ANNOTATION, "@Disposes", this.method, Formats.formatAsStackTraceElement(method.getJavaMember())); } else if (getDeclaringBean() instanceof SessionBean<?> && !Modifier.isStatic(method.slim().getJavaMember().getModifiers())) { boolean methodDeclaredOnTypes = false; for (Type type : getDeclaringBean().getTypes()) { Class<?> clazz = Reflections.getRawType(type); try { AccessController.doPrivileged(new GetMethodAction(clazz, method.getName(), method.getParameterTypesAsArray())); methodDeclaredOnTypes = true; break; } catch (PrivilegedActionException ignored) { } } if (!methodDeclaredOnTypes) { throw BeanLogger.LOG.methodNotBusinessMethod("Producer", this, getDeclaringBean(), Formats.formatAsStackTraceElement(method.getJavaMember())); } } }
java
ProtectionDomain getProtectionDomainForProxy(ProtectionDomain domain) { if (domain.getCodeSource() == null) { // no codesource to cache on return create(domain); } ProtectionDomain proxyProtectionDomain = proxyProtectionDomains.get(domain.getCodeSource()); if (proxyProtectionDomain == null) { // as this is not atomic create() may be called multiple times for the same domain // we ignore that proxyProtectionDomain = create(domain); ProtectionDomain existing = proxyProtectionDomains.putIfAbsent(domain.getCodeSource(), proxyProtectionDomain); if (existing != null) { proxyProtectionDomain = existing; } } return proxyProtectionDomain; }
java
public static <A extends Annotation> EnhancedAnnotation<A> create(SlimAnnotatedType<A> annotatedType, ClassTransformer classTransformer) { Class<A> annotationType = annotatedType.getJavaClass(); Map<Class<? extends Annotation>, Annotation> annotationMap = new HashMap<Class<? extends Annotation>, Annotation>(); annotationMap.putAll(buildAnnotationMap(annotatedType.getAnnotations())); annotationMap.putAll(buildAnnotationMap(classTransformer.getTypeStore().get(annotationType))); // Annotations and declared annotations are the same for annotation type return new EnhancedAnnotationImpl<A>(annotatedType, annotationMap, annotationMap, classTransformer); }
java
protected void init(EnhancedAnnotation<T> annotatedAnnotation) { initType(annotatedAnnotation); initValid(annotatedAnnotation); check(annotatedAnnotation); }
java
protected void initValid(EnhancedAnnotation<T> annotatedAnnotation) { this.valid = false; for (Class<? extends Annotation> annotationType : getMetaAnnotationTypes()) { if (annotatedAnnotation.isAnnotationPresent(annotationType)) { this.valid = true; } } }
java
private void installFastProcessAnnotatedTypeResolver(ServiceRegistry services) { ClassFileServices classFileServices = services.get(ClassFileServices.class); if (classFileServices != null) { final GlobalObserverNotifierService observers = services.get(GlobalObserverNotifierService.class); try { final FastProcessAnnotatedTypeResolver resolver = new FastProcessAnnotatedTypeResolver(observers.getAllObserverMethods()); services.add(FastProcessAnnotatedTypeResolver.class, resolver); } catch (UnsupportedObserverMethodException e) { BootstrapLogger.LOG.notUsingFastResolver(e.getObserver()); return; } } }
java
public String load() { this.paginator = new Paginator(); this.codes = null; // Perform a search this.codes = codeFragmentManager.searchCodeFragments(this.codeFragmentPrototype, this.page, this.paginator); return "history"; }
java
public <T> InternalEjbDescriptor<T> get(String beanName) { return cast(ejbByName.get(beanName)); }
java
private <T> void add(EjbDescriptor<T> ejbDescriptor) { InternalEjbDescriptor<T> internalEjbDescriptor = InternalEjbDescriptor.of(ejbDescriptor); ejbByName.put(ejbDescriptor.getEjbName(), internalEjbDescriptor); ejbByClass.put(ejbDescriptor.getBeanClass(), internalEjbDescriptor.getEjbName()); }
java
private void fireEventForNonWebModules(Type eventType, Object event, Annotation... qualifiers) { try { BeanDeploymentModules modules = deploymentManager.getServices().get(BeanDeploymentModules.class); if (modules != null) { // fire event for non-web modules // web modules are handled by HttpContextLifecycle for (BeanDeploymentModule module : modules) { if (!module.isWebModule()) { module.fireEvent(eventType, event, qualifiers); } } } } catch (Exception ignored) { } }
java
public static void initialize(BeanManagerImpl deploymentManager, ServiceRegistry deploymentServices) { Container instance = new Container(RegistrySingletonProvider.STATIC_INSTANCE, deploymentManager, deploymentServices); Container.instance.set(RegistrySingletonProvider.STATIC_INSTANCE, instance); }
java
public void cleanup() { managers.clear(); for (BeanManagerImpl beanManager : beanDeploymentArchives.values()) { beanManager.cleanup(); } beanDeploymentArchives.clear(); deploymentServices.cleanup(); deploymentManager.cleanup(); instance.clear(contextId); }
java
public void putBeanDeployments(BeanDeploymentArchiveMapping bdaMapping) { for (Entry<BeanDeploymentArchive, BeanManagerImpl> entry : bdaMapping.getBdaToBeanManagerMap().entrySet()) { beanDeploymentArchives.put(entry.getKey(), entry.getValue()); addBeanManager(entry.getValue()); } }
java
private <Y> void checkObserverMethod(EnhancedAnnotatedMethod<T, Y> annotated) { // Make sure exactly one and only one parameter is annotated with Observes or ObservesAsync List<EnhancedAnnotatedParameter<?, Y>> eventObjects = annotated.getEnhancedParameters(Observes.class); eventObjects.addAll(annotated.getEnhancedParameters(ObservesAsync.class)); if (this.reception.equals(Reception.IF_EXISTS) && declaringBean.getScope().equals(Dependent.class)) { throw EventLogger.LOG.invalidScopedConditionalObserver(this, Formats.formatAsStackTraceElement(annotated.getJavaMember())); } if (eventObjects.size() > 1) { throw EventLogger.LOG.multipleEventParameters(this, Formats.formatAsStackTraceElement(annotated.getJavaMember())); } EnhancedAnnotatedParameter<?, Y> eventParameter = eventObjects.iterator().next(); checkRequiredTypeAnnotations(eventParameter); // Check for parameters annotated with @Disposes List<?> disposeParams = annotated.getEnhancedParameters(Disposes.class); if (disposeParams.size() > 0) { throw EventLogger.LOG.invalidDisposesParameter(this, Formats.formatAsStackTraceElement(annotated.getJavaMember())); } // Check annotations on the method to make sure this is not a producer // method, initializer method, or destructor method. if (this.observerMethod.getAnnotated().isAnnotationPresent(Produces.class)) { throw EventLogger.LOG.invalidProducer(this, Formats.formatAsStackTraceElement(annotated.getJavaMember())); } if (this.observerMethod.getAnnotated().isAnnotationPresent(Inject.class)) { throw EventLogger.LOG.invalidInitializer(this, Formats.formatAsStackTraceElement(annotated.getJavaMember())); } boolean containerLifecycleObserverMethod = Observers.isContainerLifecycleObserverMethod(this); for (EnhancedAnnotatedParameter<?, ?> parameter : annotated.getEnhancedParameters()) { // if this is an observer method for container lifecycle event, it must not inject anything besides BeanManager if (containerLifecycleObserverMethod && !parameter.isAnnotationPresent(Observes.class) && !parameter.isAnnotationPresent(ObservesAsync.class) && !BeanManager.class.equals(parameter.getBaseType())) { throw EventLogger.LOG.invalidInjectionPoint(this, Formats.formatAsStackTraceElement(annotated.getJavaMember())); } } }
java
protected void sendEvent(final T event) { if (isStatic) { sendEvent(event, null, null); } else { CreationalContext<X> creationalContext = null; try { Object receiver = getReceiverIfExists(null); if (receiver == null && reception != Reception.IF_EXISTS) { // creational context is created only if we need it for obtaining receiver // ObserverInvocationStrategy takes care of creating CC for parameters, if needed creationalContext = beanManager.createCreationalContext(declaringBean); receiver = getReceiverIfExists(creationalContext); } if (receiver != null) { sendEvent(event, receiver, creationalContext); } } finally { if (creationalContext != null) { creationalContext.release(); } } } }
java
public static void endRequest() { final List<RequestScopedItem> result = CACHE.get(); if (result != null) { CACHE.remove(); for (final RequestScopedItem item : result) { item.invalidate(); } } }
java
public <X> X invokeOnInstance(Object instance, Object... parameters) throws IllegalArgumentException, SecurityException, IllegalAccessException, InvocationTargetException, NoSuchMethodException { final Map<Class<?>, Method> methods = this.methods; Method method = methods.get(instance.getClass()); if (method == null) { // the same method may be written to the map twice, but that is ok // lookupMethod is very slow Method delegate = annotatedMethod.getJavaMember(); method = SecurityActions.lookupMethod(instance.getClass(), delegate.getName(), delegate.getParameterTypes()); SecurityActions.ensureAccessible(method); synchronized (this) { final Map<Class<?>, Method> newMethods = new HashMap<Class<?>, Method>(methods); newMethods.put(instance.getClass(), method); this.methods = WeldCollections.immutableMapView(newMethods); } } return cast(method.invoke(instance, parameters)); }
java
@SuppressWarnings("unchecked") protected Class<? extends Annotation> annotationTypeForName(String name) { try { return (Class<? extends Annotation>) resourceLoader.classForName(name); } catch (ResourceLoadingException cnfe) { return DUMMY_ANNOTATION; } }
java
protected Class<?> classForName(String name) { try { return resourceLoader.classForName(name); } catch (ResourceLoadingException cnfe) { return DUMMY_CLASS; } }
java
public void addInterface(Class<?> newInterface) { if (!newInterface.isInterface()) { throw new IllegalArgumentException(newInterface + " is not an interface"); } additionalInterfaces.add(newInterface); }
java
public T create(BeanInstance beanInstance) { final T proxy = (System.getSecurityManager() == null) ? run() : AccessController.doPrivileged(this); ((ProxyObject) proxy).weld_setHandler(new ProxyMethodHandler(contextId, beanInstance, bean)); return proxy; }
java
public Class<T> getProxyClass() { String suffix = "_$$_Weld" + getProxyNameSuffix(); String proxyClassName = getBaseProxyName(); if (!proxyClassName.endsWith(suffix)) { proxyClassName = proxyClassName + suffix; } if (proxyClassName.startsWith(JAVA)) { proxyClassName = proxyClassName.replaceFirst(JAVA, "org.jboss.weld"); } Class<T> proxyClass = null; Class<?> originalClass = bean != null ? bean.getBeanClass() : proxiedBeanType; BeanLogger.LOG.generatingProxyClass(proxyClassName); try { // First check to see if we already have this proxy class proxyClass = cast(classLoader == null? proxyServices.loadClass(originalClass, proxyClassName) : classLoader.loadClass(proxyClassName)); } catch (ClassNotFoundException e) { // Create the proxy class for this instance try { proxyClass = createProxyClass(originalClass, proxyClassName); } catch (Throwable e1) { //attempt to load the class again, just in case another thread //defined it between the check and the create method try { proxyClass = cast(classLoader == null? proxyServices.loadClass(originalClass, proxyClassName) : classLoader.loadClass(proxyClassName)); } catch (ClassNotFoundException e2) { BeanLogger.LOG.catchingDebug(e1); throw BeanLogger.LOG.unableToLoadProxyClass(bean, proxiedBeanType, e1); } } } return proxyClass; }
java
public static <T> void setBeanInstance(String contextId, T proxy, BeanInstance beanInstance, Bean<?> bean) { if (proxy instanceof ProxyObject) { ProxyObject proxyView = (ProxyObject) proxy; proxyView.weld_setHandler(new ProxyMethodHandler(contextId, beanInstance, bean)); } }
java
protected void addConstructors(ClassFile proxyClassType, List<DeferredBytecode> initialValueBytecode) { try { if (getBeanType().isInterface()) { ConstructorUtils.addDefaultConstructor(proxyClassType, initialValueBytecode, !useConstructedFlag()); } else { boolean constructorFound = false; for (Constructor<?> constructor : AccessController.doPrivileged(new GetDeclaredConstructorsAction(getBeanType()))) { if ((constructor.getModifiers() & Modifier.PRIVATE) == 0) { constructorFound = true; String[] exceptions = new String[constructor.getExceptionTypes().length]; for (int i = 0; i < exceptions.length; ++i) { exceptions[i] = constructor.getExceptionTypes()[i].getName(); } ConstructorUtils.addConstructor(BytecodeUtils.VOID_CLASS_DESCRIPTOR, DescriptorUtils.parameterDescriptors(constructor.getParameterTypes()), exceptions, proxyClassType, initialValueBytecode, !useConstructedFlag()); } } if (!constructorFound) { // the bean only has private constructors, we need to generate // two fake constructors that call each other addConstructorsForBeanWithPrivateConstructors(proxyClassType); } } } catch (Exception e) { throw new WeldException(e); } }
java
public static ClassLoader resolveClassLoaderForBeanProxy(String contextId, Class<?> proxiedType, TypeInfo typeInfo, ProxyServices proxyServices) { Class<?> superClass = typeInfo.getSuperClass(); if (superClass.getName().startsWith(JAVA)) { ClassLoader cl = proxyServices.getClassLoader(proxiedType); if (cl == null) { cl = Thread.currentThread().getContextClassLoader(); } return cl; } return Container.instance(contextId).services().get(ProxyServices.class).getClassLoader(superClass); }
java