@Override public void setResources(final WebResourceRoot resources) { this.resources = resources; if (StandardRoot.class.isInstance(resources)) { final List<WebResourceSet> jars = (List<WebResourceSet>) Reflections.get(resources, "jarResources"); if (jars != null && !jars.isEmpty()) { final Iterator<WebResourceSet> jarIt = jars.iterator(); while (jarIt.hasNext()) { final WebResourceSet set = jarIt.next(); if (set.getBaseUrl() == null) { continue; } final File file = URLs.toFile(set.getBaseUrl()); try { if (file.exists() && (!TomEEClassLoaderEnricher.validateJarFile(file) || !jarIsAccepted(file))) { // need to remove this resource LOGGER.warning("Removing " + file.getAbsolutePath() + " since it is offending"); jarIt.remove(); } } catch (final IOException e) { // ignore } } } } }
public static ValidatorFactory buildFactory( final ValidationInfo config, final ClassLoader classLoader) { ValidatorFactory factory = null; final Thread thread = Thread.currentThread(); final ClassLoader oldContextLoader = thread.getContextClassLoader(); try { thread.setContextClassLoader(classLoader); if (config == null) { factory = Validation.buildDefaultValidatorFactory(); } else { final Configuration<?> configuration = getConfig(config); try { factory = configuration.buildValidatorFactory(); } catch (final ValidationException ve) { thread.setContextClassLoader(ValidatorBuilder.class.getClassLoader()); factory = Validation.buildDefaultValidatorFactory(); thread.setContextClassLoader(classLoader); logger.warning( "Unable create validator factory with config " + config + " (" + ve.getMessage() + ")." + " Default factory will be used."); } } } finally { thread.setContextClassLoader(oldContextLoader); } return factory; }
@Override public void contextInitialized(ServletContextEvent servletContextEvent) { try { OpenEJBLifecycle.initializeServletContext( servletContextEvent.getServletContext(), webBeansContext); } catch (final Exception e) { logger.warning(e.getMessage(), e); } ensureRequestScope(); }
public DeployTimeEnhancer() { Method mtd; Constructor<?> cstr; final ClassLoader cl = DeployTimeEnhancer.class.getClassLoader(); try { final Class<?> enhancerClass = cl.loadClass("org.apache.openjpa.enhance.PCEnhancer"); final Class<?> arg2 = cl.loadClass("org.apache.openjpa.lib.util.Options"); cstr = arg2.getConstructor(Properties.class); mtd = enhancerClass.getMethod("run", String[].class, arg2); } catch (Exception e) { LOGGER.warning("openjpa enhancer can't be found in the container, will be skipped"); mtd = null; cstr = null; } optionsConstructor = cstr; enhancerMethod = mtd; }
private boolean jarIsAccepted(final File file) { if (configurer == null) { return true; } try { if (!configurer.accept(file.toURI().toURL())) { LOGGER.warning( "jar '" + file.getAbsolutePath() + "' is excluded: " + file.getName() + ". It will be ignored."); return false; } } catch (final MalformedURLException e) { // no-op } return true; }
public DynamicMBeanWrapper(final WebBeansContext wc, final Object givenInstance) { Class<?> annotatedMBean = givenInstance.getClass(); // javaassist looses annotation so simply unwrap it if (wc != null) { if (givenInstance.getClass().getName().contains("$Owb")) { // isProxy annotatedMBean = annotatedMBean.getSuperclass(); } } classloader = annotatedMBean.getClassLoader(); instance = givenInstance; final CacheInfo cache = CACHE.get(annotatedMBean); if (cache == null) { final String description; final List<MBeanAttributeInfo> attributeInfos = new ArrayList<MBeanAttributeInfo>(); final List<MBeanOperationInfo> operationInfos = new ArrayList<MBeanOperationInfo>(); final List<MBeanNotificationInfo> notificationInfos = new ArrayList<MBeanNotificationInfo>(); // class final Description classDescription = findAnnotation(annotatedMBean, Description.class); description = getDescription(classDescription, "a MBean built by OpenEJB"); final NotificationInfo notification = findAnnotation(annotatedMBean, NotificationInfo.class); if (notification != null) { final MBeanNotificationInfo notificationInfo = getNotificationInfo(notification); notificationInfos.add(notificationInfo); } final NotificationInfos notifications = findAnnotation(annotatedMBean, NotificationInfos.class); if (notifications != null && notifications.value() != null) { for (final NotificationInfo n : notifications.value()) { final MBeanNotificationInfo notificationInfo = getNotificationInfo(n); notificationInfos.add(notificationInfo); } } // methods for (final Method m : annotatedMBean.getMethods()) { final int modifiers = m.getModifiers(); if (m.getDeclaringClass().equals(Object.class) || !Modifier.isPublic(modifiers) || Modifier.isAbstract(modifiers)) { continue; } if (findAnnotation(m, ManagedAttribute.class) != null) { final String methodName = m.getName(); String attrName = methodName; if ((attrName.startsWith("get") && m.getParameterTypes().length == 0 || attrName.startsWith("set") && m.getParameterTypes().length == 1) && attrName.length() > 3) { attrName = attrName.substring(3); if (attrName.length() > 1) { attrName = Character.toLowerCase(attrName.charAt(0)) + attrName.substring(1); } else { attrName = attrName.toLowerCase(); } } else { logger.warning( "ignoring attribute " + m.getName() + " for " + annotatedMBean.getName()); } if (methodName.startsWith("get")) { getters.put(attrName, m); } else if (methodName.startsWith("set")) { setters.put(attrName, m); } } else if (findAnnotation(m, ManagedOperation.class) != null) { operations.put(m.getName(), m); String operationDescr = ""; final Description descr = findAnnotation(m, Description.class); if (descr != null) { operationDescr = getDescription(descr, "-"); } operationInfos.add(newMethodDescriptor(operationDescr, m)); } } for (final Map.Entry<String, Method> e : getters.entrySet()) { final String key = e.getKey(); final Method mtd = e.getValue(); String attrDescr = ""; final Description descr = findAnnotation(mtd, Description.class); if (descr != null) { attrDescr = getDescription(descr, "-"); } try { attributeInfos.add(new MBeanAttributeInfo(key, attrDescr, mtd, setters.get(key))); } catch (final IntrospectionException ex) { logger.warning("can't manage " + key + " for " + mtd.getName(), ex); } } // for updatable but not readable attributes for (final Map.Entry<String, Method> e : setters.entrySet()) { final String key = e.getKey(); if (getters.get(key) != null) { continue; // already done } final Method mtd = e.getValue(); String attrDescr = ""; final Description descr = findAnnotation(mtd, Description.class); if (descr != null) { attrDescr = getDescription(descr, "-"); } try { attributeInfos.add(new MBeanAttributeInfo(key, attrDescr, null, setters.get(key))); } catch (final IntrospectionException ex) { logger.warning("can't manage " + key + " for " + mtd.getName(), ex); } } info = new MBeanInfo( annotatedMBean.getName(), description, attributeInfos.toArray(new MBeanAttributeInfo[attributeInfos.size()]), null, // default constructor is mandatory operationInfos.toArray(new MBeanOperationInfo[operationInfos.size()]), notificationInfos.toArray(new MBeanNotificationInfo[notificationInfos.size()])); if (annotatedMBean.getAnnotation(Internal.class) != null) { CACHE.put(annotatedMBean, new CacheInfo(info, getters, setters, operations)); } } else { info = cache.mBeanInfo; getters.putAll(cache.getters); setters.putAll(cache.setters); operations.putAll(cache.operations); } }
public void enhance(@Observes final BeforeDeploymentEvent event) { if (enhancerMethod == null) { LOGGER.debug("OpenJPA is not available so no deploy-time enhancement will be done"); return; } // find persistence.xml final Map<String, List<String>> classesByPXml = new HashMap<String, List<String>>(); final List<URL> usedUrls = new ArrayList<URL>(); // for fake classloader for (URL url : event.getUrls()) { final File file = URLs.toFile(url); if (file.isDirectory()) { final String pXmls = getWarPersistenceXml(url); if (pXmls != null) { feed(classesByPXml, pXmls); } usedUrls.add(url); } else if (file.getName().endsWith(".jar")) { try { final JarFile jar = new JarFile(file); ZipEntry entry = jar.getEntry(META_INF_PERSISTENCE_XML); if (entry != null) { final String path = file.getAbsolutePath(); final File unpacked = new File(path.substring(0, path.length() - 4) + TMP_ENHANCEMENT_SUFFIX); JarExtractor.extract(file, unpacked); // replace jar by folder url since otherwise enhancement doesn't work usedUrls.add(unpacked.toURI().toURL()); feed(classesByPXml, new File(unpacked, META_INF_PERSISTENCE_XML).getAbsolutePath()); } } catch (IOException e) { // ignored } } else { usedUrls.add(url); } } // enhancement final ClassLoader tccl = Thread.currentThread().getContextClassLoader(); final ClassLoader fakeClassLoader = new URLClassLoaderFirst( usedUrls.toArray(new URL[usedUrls.size()]), event.getParentClassLoader()); Thread.currentThread().setContextClassLoader(fakeClassLoader); try { for (Map.Entry<String, List<String>> entry : classesByPXml.entrySet()) { final Properties opts = new Properties(); opts.setProperty(PROPERTIES_FILE_PROP, entry.getKey()); final Object optsArg; try { optsArg = optionsConstructor.newInstance(opts); } catch (Exception e) { LOGGER.debug("can't create options for enhancing"); return; } LOGGER.info("enhancing url(s): " + Arrays.asList(event.getUrls())); try { enhancerMethod.invoke(null, toFilePaths(entry.getValue()), optsArg); } catch (Exception e) { LOGGER.warning("can't enhanced at deploy-time entities", e); } } } finally { Thread.currentThread().setContextClassLoader(tccl); usedUrls.clear(); } // clean up extracted jars and replace jar to keep consistent classloading for (Map.Entry<String, List<String>> entry : classesByPXml.entrySet()) { final List<String> values = entry.getValue(); for (String rawPath : values) { if (rawPath.endsWith(TMP_ENHANCEMENT_SUFFIX + "/") || rawPath.endsWith(TMP_ENHANCEMENT_SUFFIX)) { final File dir = new File(rawPath); final File file = new File( rawPath.substring(0, rawPath.length() - TMP_ENHANCEMENT_SUFFIX.length() - 1) + ".jar"); if (file.exists()) { String name = dir.getName(); name = name.substring(0, name.length() - TMP_ENHANCEMENT_SUFFIX.length()) + ".jar"; final File target = new File(dir.getParentFile(), name); try { // override existing jar otherwise classloading is broken in tomee Files.delete(file); JarCreator.jarDir(dir, target); } catch (final IOException e) { LOGGER.error("can't repackage enhanced jar file " + file.getName()); } Files.delete(dir); } } } values.clear(); } classesByPXml.clear(); }
@SuppressWarnings("unchecked") private static Configuration<?> getConfig(final ValidationInfo info) { Configuration<?> target = null; final Thread thread = Thread.currentThread(); final ClassLoader classLoader = thread.getContextClassLoader(); String providerClassName = info.providerClassName; if (providerClassName == null) { providerClassName = SystemInstance.get().getOptions().get(VALIDATION_PROVIDER_KEY, (String) null); } if (providerClassName != null) { try { @SuppressWarnings({"unchecked", "rawtypes"}) final Class clazz = classLoader.loadClass(providerClassName); target = Validation.byProvider(clazz).configure(); logger.info("Using " + providerClassName + " as validation provider."); } catch (final ClassNotFoundException e) { logger.warning("Unable to load provider class " + providerClassName, e); } catch (final ValidationException ve) { logger.warning( "Unable create validator factory with provider " + providerClassName + " (" + ve.getMessage() + ")." + " Default one will be used."); } } if (target == null) { // force to use container provider to ignore any conflicting configuration thread.setContextClassLoader(ValidatorBuilder.class.getClassLoader()); target = Validation.byDefaultProvider().configure(); thread.setContextClassLoader(classLoader); } final Set<ExecutableType> types = new HashSet<>(); for (final String type : info.validatedTypes) { types.add(ExecutableType.valueOf(type)); } final Map<String, String> props = new HashMap<>(); for (final Map.Entry<Object, Object> entry : info.propertyTypes.entrySet()) { final PropertyType property = new PropertyType(); property.setName((String) entry.getKey()); property.setValue((String) entry.getValue()); props.put(property.getName(), property.getValue()); if (logger.isDebugEnabled()) { logger.debug( "Found property '" + property.getName() + "' with value '" + property.getValue()); } target.addProperty(property.getName(), property.getValue()); } final OpenEjbBootstrapConfig bootstrapConfig = new OpenEjbBootstrapConfig( providerClassName, info.constraintFactoryClass, info.messageInterpolatorClass, info.traversableResolverClass, info.parameterNameProviderClass, new HashSet<>(info.constraintMappings), info.executableValidationEnabled, types, props); final OpenEjbConfig config = new OpenEjbConfig(bootstrapConfig, target); target.ignoreXmlConfiguration(); final String messageInterpolatorClass = info.messageInterpolatorClass; if (messageInterpolatorClass != null) { try { @SuppressWarnings("unchecked") final Class<MessageInterpolator> clazz = (Class<MessageInterpolator>) classLoader.loadClass(messageInterpolatorClass); target.messageInterpolator(newInstance(config, clazz)); } catch (final Exception e) { logger.warning( "Unable to set " + messageInterpolatorClass + " as message interpolator.", e); } logger.info("Using " + messageInterpolatorClass + " as message interpolator."); } final String traversableResolverClass = info.traversableResolverClass; if (traversableResolverClass != null) { try { @SuppressWarnings("unchecked") final Class<TraversableResolver> clazz = (Class<TraversableResolver>) classLoader.loadClass(traversableResolverClass); target.traversableResolver(newInstance(config, clazz)); } catch (final Exception e) { logger.warning( "Unable to set " + traversableResolverClass + " as traversable resolver.", e); } logger.info("Using " + traversableResolverClass + " as traversable resolver."); } final String constraintFactoryClass = info.constraintFactoryClass; if (constraintFactoryClass != null) { try { @SuppressWarnings("unchecked") final Class<ConstraintValidatorFactory> clazz = (Class<ConstraintValidatorFactory>) classLoader.loadClass(constraintFactoryClass); target.constraintValidatorFactory(newInstance(config, clazz)); } catch (final Exception e) { logger.warning("Unable to set " + constraintFactoryClass + " as constraint factory.", e); } logger.info("Using " + constraintFactoryClass + " as constraint factory."); } for (final String mappingFileName : info.constraintMappings) { if (logger.isDebugEnabled()) { logger.debug("Opening input stream for " + mappingFileName); } final InputStream in = classLoader.getResourceAsStream(mappingFileName); if (in == null) { logger.warning( "Unable to open input stream for mapping file " + mappingFileName + ". It will be ignored"); } else { target.addMapping(in); } } if (info.parameterNameProviderClass != null) { try { final Class<ParameterNameProvider> clazz = (Class<ParameterNameProvider>) classLoader.loadClass(info.parameterNameProviderClass); target.parameterNameProvider(newInstance(config, clazz)); } catch (final Exception e) { logger.warning( "Unable to set " + info.parameterNameProviderClass + " as parameter name provider.", e); } logger.info("Using " + info.parameterNameProviderClass + " as parameter name provider."); } return config; }
public EjbJarInfo buildInfo(final EjbModule jar) throws OpenEJBException { deploymentIds.clear(); securityRoles.clear(); final Map<String, EjbDeployment> ejbds = jar.getOpenejbJar().getDeploymentsByEjbName(); final int beansDeployed = jar.getOpenejbJar().getEjbDeploymentCount(); final int beansInEjbJar = jar.getEjbJar().getEnterpriseBeans().length; if (beansInEjbJar != beansDeployed) { for (final EnterpriseBean bean : jar.getEjbJar().getEnterpriseBeans()) { if (!ejbds.containsKey(bean.getEjbName())) { ConfigUtils.logger.warning("conf.0018", bean.getEjbName(), jar.getJarLocation()); } } final String message = messages.format( "conf.0008", jar.getJarLocation(), String.valueOf(beansInEjbJar), String.valueOf(beansDeployed)); logger.warning(message); throw new OpenEJBException(message); } final Map<String, EnterpriseBeanInfo> infos = new HashMap<String, EnterpriseBeanInfo>(); final Map<String, EnterpriseBean> items = new HashMap<String, EnterpriseBean>(); final EjbJarInfo ejbJar = new EjbJarInfo(); ejbJar.path = jar.getJarLocation(); ejbJar.moduleUri = jar.getModuleUri(); ejbJar.moduleId = jar.getModuleId(); if (jar.getEjbJar() != null && jar.getEjbJar().getModuleName() != null) { ejbJar.moduleName = jar.getEjbJar().getModuleName(); } else { ejbJar.moduleName = jar.getModuleId(); } ejbJar.watchedResources.addAll(jar.getWatchedResources()); ejbJar.properties.putAll(jar.getProperties()); ejbJar.properties.putAll(jar.getOpenejbJar().getProperties()); for (final EnterpriseBean bean : jar.getEjbJar().getEnterpriseBeans()) { final EnterpriseBeanInfo beanInfo; if (bean instanceof SessionBean) { beanInfo = initSessionBean((SessionBean) bean, ejbJar, ejbds); } else if (bean instanceof EntityBean) { beanInfo = initEntityBean((EntityBean) bean, ejbds); } else if (bean instanceof MessageDrivenBean) { beanInfo = initMessageBean((MessageDrivenBean) bean, ejbds); } else { throw new OpenEJBException("Unknown bean type: " + bean.getClass().getName()); } ejbJar.enterpriseBeans.add(beanInfo); if (deploymentIds.contains(beanInfo.ejbDeploymentId)) { final String message = messages.format( "conf.0100", beanInfo.ejbDeploymentId, jar.getJarLocation(), beanInfo.ejbName); logger.warning(message); throw new OpenEJBException(message); } deploymentIds.add(beanInfo.ejbDeploymentId); beanInfo.codebase = jar.getJarLocation(); infos.put(beanInfo.ejbName, beanInfo); items.put(beanInfo.ejbName, bean); if (bean.getSecurityIdentity() != null) { beanInfo.runAs = bean.getSecurityIdentity().getRunAs(); final EjbDeployment deployment = ejbds.get(beanInfo.ejbName); if (deployment != null) { for (final RoleMapping mapping : deployment.getRoleMapping()) { if (mapping.getRoleName().equals(beanInfo.runAs)) { beanInfo.runAsUser = mapping.getPrincipalName(); break; } } } } initJndiNames(ejbds, beanInfo); } if (jar.getEjbJar().getAssemblyDescriptor() != null) { initInterceptors(jar, ejbJar); initSecurityRoles(jar, ejbJar); initMethodPermissions(jar, ejbds, ejbJar); initExcludesList(jar, ejbds, ejbJar); initMethodTransactions(jar, ejbds, ejbJar); initMethodConcurrency(jar, ejbds, ejbJar); initApplicationExceptions(jar, ejbJar); for (final EnterpriseBeanInfo bean : ejbJar.enterpriseBeans) { resolveRoleLinks(bean, items.get(bean.ejbName)); } } if (jar.getEjbJar().getRelationships() != null) { initRelationships(jar, infos); } final Beans beans = jar.getBeans(); if (beans != null) { ejbJar.beans = new BeansInfo(); ejbJar.beans.version = beans.getVersion(); ejbJar.beans.discoveryMode = beans.getBeanDiscoveryMode(); if (beans.getScan() != null) { for (final Beans.Scan.Exclude exclude : beans.getScan().getExclude()) { final ExclusionInfo exclusionInfo = new ExclusionInfo(); for (final Object config : exclude.getIfClassAvailableOrIfClassNotAvailableOrIfSystemProperty()) { if (Beans.Scan.Exclude.IfAvailableClassCondition.class.isInstance(config)) { exclusionInfo.availableClasses.add( Beans.Scan.Exclude.ClassCondition.class.cast(config).getName()); } else if (Beans.Scan.Exclude.IfNotAvailableClassCondition.class.isInstance(config)) { exclusionInfo.notAvailableClasses.add( Beans.Scan.Exclude.ClassCondition.class.cast(config).getName()); } else if (Beans.Scan.Exclude.IfSystemProperty.class.isInstance(config)) { final Beans.Scan.Exclude.IfSystemProperty systemProperty = Beans.Scan.Exclude.IfSystemProperty.class.cast(config); if (systemProperty.getValue() == null) { exclusionInfo.systemPropertiesPresence.add(systemProperty.getName()); } else { exclusionInfo.systemProperties.put( systemProperty.getName(), systemProperty.getValue()); } } else { throw new IllegalArgumentException("Not supported: " + config); } } final BeansInfo.ExclusionEntryInfo exclusionEntryInfo = new BeansInfo.ExclusionEntryInfo(); exclusionEntryInfo.name = exclude.getName(); exclusionEntryInfo.exclusion = exclusionInfo; ejbJar.beans.excludes.add(exclusionEntryInfo); } } ejbJar.beans.interceptors.addAll(beans.getInterceptors()); ejbJar.beans.decorators.addAll(beans.getDecorators()); ejbJar.beans.alternativeClasses.addAll(beans.getAlternativeClasses()); ejbJar.beans.alternativeStereotypes.addAll(beans.getAlternativeStereotypes()); ejbJar.beans.duplicatedAlternativeClasses.addAll( beans.getDuplicatedAlternatives().getClasses()); ejbJar.beans.duplicatedAlternativeStereotypes.addAll( beans.getDuplicatedAlternatives().getStereotypes()); ejbJar.beans.duplicatedInterceptors.addAll(beans.getDuplicatedInterceptors()); ejbJar.beans.duplicatedDecorators.addAll(beans.getDuplicatedDecorators()); ejbJar.beans.startupClasses.addAll(beans.getStartupBeans()); final Map<URL, String> discoveryModeByUrl = new HashMap<>(); if (CompositeBeans.class.isInstance(beans)) { discoveryModeByUrl.putAll(CompositeBeans.class.cast(beans).getDiscoveryByUrl()); } else { discoveryModeByUrl.put(null, beans.getBeanDiscoveryMode()); } for (final Map.Entry<URL, List<String>> next : beans.getManagedClasses().entrySet()) { final URL key = next.getKey(); final BeansInfo.BDAInfo bdaInfo = new BeansInfo.BDAInfo(); bdaInfo.managedClasses.addAll(next.getValue()); bdaInfo.discoveryMode = discoveryModeByUrl.get(key); try { bdaInfo.uri = key == null ? null : key.toURI(); } catch (final URISyntaxException e) { bdaInfo.uri = null; } ejbJar.beans.bdas.add(bdaInfo); } } return ejbJar; }
static { boolean result = ClassLoader.registerAsParallelCapable(); if (!result) { LOGGER.warning("Can't register // tomee webapp classloader"); } }