Exemplo n.º 1
0
  private static class ClassFilter implements FileFilter {
    private static final String DEFAULT_INCLUDE = "\\*";
    private static final String DEFAULT_EXCLUDE = "";
    private static final Pattern INCLUDE_PATTERN =
        Pattern.compile(
            SystemInstance.get()
                .getOptions()
                .get(OPENEJB_JAR_ENHANCEMENT_INCLUDE, DEFAULT_INCLUDE));
    private static final Pattern EXCLUDE_PATTERN =
        Pattern.compile(
            SystemInstance.get()
                .getOptions()
                .get(OPENEJB_JAR_ENHANCEMENT_EXCLUDE, DEFAULT_EXCLUDE));

    @Override
    public boolean accept(final File file) {
      boolean isClass = file.getName().endsWith(CLASS_EXT);
      if (DEFAULT_EXCLUDE.equals(EXCLUDE_PATTERN.pattern())
          && DEFAULT_INCLUDE.equals(INCLUDE_PATTERN.pattern())) {
        return isClass;
      }

      final String path = file.getAbsolutePath();
      return isClass
          && INCLUDE_PATTERN.matcher(path).matches()
          && !EXCLUDE_PATTERN.matcher(path).matches();
    }
  }
  @Test
  public void testRollback() throws Exception {
    SystemInstance.init(new Properties());
    final BeanContext cdi =
        new BeanContext(
            "foo",
            null,
            new ModuleContext(
                "foo",
                null,
                "bar",
                new AppContext("foo", SystemInstance.get(), null, null, null, false),
                null,
                null),
            Object.class,
            null,
            new HashMap<String, String>());
    cdi.addApplicationException(AE1.class, true, true);
    cdi.addApplicationException(AE3.class, true, false);
    cdi.addApplicationException(AE6.class, false, true);

    assertEquals(ExceptionType.APPLICATION_ROLLBACK, cdi.getExceptionType(new AE1()));
    assertEquals(ExceptionType.APPLICATION_ROLLBACK, cdi.getExceptionType(new AE2()));
    assertEquals(ExceptionType.APPLICATION_ROLLBACK, cdi.getExceptionType(new AE3()));
    assertEquals(ExceptionType.SYSTEM, cdi.getExceptionType(new AE4()));
    assertEquals(ExceptionType.SYSTEM, cdi.getExceptionType(new AE5()));
    assertEquals(ExceptionType.APPLICATION, cdi.getExceptionType(new AE6()));
    assertEquals(ExceptionType.APPLICATION, cdi.getExceptionType(new AE7()));
  }
Exemplo n.º 3
0
  public static Object build(
      final Collection<ServiceInfo> services,
      final ServiceInfo info,
      final ObjectRecipe serviceRecipe) {
    if ("org.apache.openejb.config.sys.MapFactory".equals(info.className)) {
      return info.properties;
    }

    if (!info.properties.containsKey("properties")) {
      info.properties.put("properties", new UnsetPropertiesRecipe());
    }

    // we can't ask for having a setter for existing code
    serviceRecipe.allow(Option.FIELD_INJECTION);
    serviceRecipe.allow(Option.PRIVATE_PROPERTIES);

    for (final Map.Entry<Object, Object> entry : info.properties.entrySet()) { // manage links
      final String key = entry.getKey().toString();
      final Object value = entry.getValue();
      if (value instanceof String) {
        final String valueStr = value.toString();
        if (valueStr.startsWith("$")) {
          serviceRecipe.setProperty(key, resolve(services, valueStr.substring(1)));
        } else if (valueStr.startsWith("@")) {
          final Context jndiContext =
              SystemInstance.get().getComponent(ContainerSystem.class).getJNDIContext();
          try {
            serviceRecipe.setProperty(
                key,
                jndiContext.lookup(
                    JndiConstants.OPENEJB_RESOURCE_JNDI_PREFIX + valueStr.substring(1)));
          } catch (final NamingException e) {
            try {
              serviceRecipe.setProperty(key, jndiContext.lookup(valueStr.substring(1)));
            } catch (final NamingException e1) {
              Logger.getInstance(LogCategory.OPENEJB, ServiceInfos.class)
                  .warning(
                      "Value "
                          + valueStr
                          + " starting with @ but doesn't point to an existing resource, using raw value");
              serviceRecipe.setProperty(key, value);
            }
          }
        } else {
          serviceRecipe.setProperty(key, value);
        }
      } else {
        serviceRecipe.setProperty(key, entry.getValue());
      }
    }

    final Object service = serviceRecipe.create();

    SystemInstance.get()
        .addObserver(
            service); // TODO: remove it? in all case the observer should remove itself when done
    Assembler.logUnusedProperties(serviceRecipe, info);

    return service;
  }
Exemplo n.º 4
0
  @Test // using an internal lookup because in tomee embedded new InitialContext() is not guaranteed
  public void checkEmIsHibernateOne() throws Exception {
    AppInfo info = null;
    for (final AppInfo app :
        SystemInstance.get().getComponent(Assembler.class).getDeployedApplications()) {
      if (app.appId.endsWith("hibernate-app")) {
        info = app;
        break;
      }
    }

    assertNotNull(info);
    final EntityManagerFactory emf =
        (EntityManagerFactory)
            SystemInstance.get()
                .getComponent(ContainerSystem.class)
                .getJNDIContext()
                .lookup(
                    Assembler.PERSISTENCE_UNIT_NAMING_CONTEXT
                        + info.persistenceUnits.iterator().next().id);
    assertTrue(
        ((ReloadableEntityManagerFactory) emf)
            .getDelegate()
            .getClass()
            .getName()
            .startsWith("org.hibernate."));
  }
  public Object getObject() throws NamingException {
    if (reference != null) {
      return reference.getObject();
    }

    SystemInstance systemInstance = SystemInstance.get();

    EjbResolver resolver = systemInstance.getComponent(EjbResolver.class);

    String deploymentId = resolver.resolve(info, moduleUri);

    if (deploymentId == null) {
      String key = "lazyEjbRefNotResolved";
      if (info.getHome() != null) {
        key += ".home";
      }
      String message =
          messages.format(
              key, info.getName(), info.getEjbLink(), info.getHome(), info.getInterface());
      throw new NameNotFoundException(message);
    }

    ContainerSystem containerSystem = systemInstance.getComponent(ContainerSystem.class);

    BeanContext beanContext = containerSystem.getBeanContext(deploymentId);

    if (beanContext == null) {
      String message = messages.format("deploymentNotFound", info.getName(), deploymentId);
      throw new NameNotFoundException(message);
    }

    InterfaceType type = null;
    switch (info.getRefType()) {
      case LOCAL:
        type = InterfaceType.BUSINESS_LOCAL;
        break;
      case REMOTE:
        type = InterfaceType.BUSINESS_REMOTE;
        break;
    }

    String jndiName =
        "openejb/Deployment/" + JndiBuilder.format(deploymentId, info.getInterface(), type);

    if (useCrossClassLoaderRef && isRemote(beanContext)) {
      reference = new CrossClassLoaderJndiReference(jndiName);
    } else {
      reference = new IntraVmJndiReference(jndiName);
    }

    return reference.getObject();
  }
Exemplo n.º 6
0
 @Override
 public void doFilter(ServletRequest request, ServletResponse response)
     throws IOException, ServletException {
   final HttpListenerRegistry registry =
       SystemInstance.get().getComponent(HttpListenerRegistry.class);
   registry.setOrigin(origin);
   try {
     registry.onMessage(
         HttpRequest.class.isInstance(request)
             ? HttpRequest.class.cast(request)
             : new ServletRequestAdapter(HttpServletRequest.class.cast(request)),
         HttpResponse.class.isInstance(response)
             ? HttpResponse.class.cast(response)
             : new ServletResponseAdapter(HttpServletResponse.class.cast(response)));
   } catch (final RuntimeException re) {
     throw re;
   } catch (final ServletException e) {
     final Throwable cause = e.getCause();
     if (RuntimeException.class.isInstance(
         cause)) { // frameworks generally wrap with ServletException
       throw RuntimeException.class.cast(cause);
     }
     throw e;
   } catch (final IOException e) {
     throw e;
   } catch (final Exception e) {
     throw new ServletException(e);
   } finally {
     registry.setOrigin(origin);
   }
 }
Exemplo n.º 7
0
  public CmpContainer(
      final Object id,
      final TransactionManager transactionManager,
      final SecurityService securityService,
      final String cmpEngineFactory)
      throws OpenEJBException {
    this.containerID = id;
    this.securityService = securityService;
    synchronizationRegistry =
        SystemInstance.get().getComponent(TransactionSynchronizationRegistry.class);
    entrancyTracker = new EntrancyTracker(synchronizationRegistry);

    // create the cmp engine instance
    ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
    if (classLoader == null) {
      classLoader = getClass().getClassLoader();
    }

    final CmpEngineFactory factory;
    try {
      final Class<?> cmpEngineFactoryClass = classLoader.loadClass(cmpEngineFactory);
      factory = (CmpEngineFactory) cmpEngineFactoryClass.newInstance();
    } catch (final Exception e) {
      throw new OpenEJBException("Unable to create cmp engine factory " + cmpEngineFactory, e);
    }
    factory.setTransactionManager(transactionManager);
    factory.setTransactionSynchronizationRegistry(synchronizationRegistry);
    factory.setCmpCallback(new ContainerCmpCallback());
    cmpEngine = factory.create();
  }
 public String toScreen() {
   final String str = "both files " + file1 + '\'' + " and " + file2 + '\'';
   if (SystemInstance.get().getOptions().get(OPENEJB_CHECK_CLASSLOADER_VERBOSE, false)) {
     return str + " contains files=" + files;
   }
   return str;
 }
Exemplo n.º 9
0
 @Override
 public T get() {
   if (webBeansContext == null) {
     webBeansContext = WebBeansContext.currentInstance();
   }
   return (T) SystemInstance.get().getComponent(type);
 }
Exemplo n.º 10
0
  @Override
  public void start() throws ServiceException {
    sshServer = SshServer.setUpDefaultServer();
    sshServer.setPort(port);
    sshServer.setHost(bind);

    final String basePath = SystemInstance.get().getBase().getDirectory().getAbsolutePath();
    if (SecurityUtils.isBouncyCastleRegistered()) {
      sshServer.setKeyPairProvider(
          new PEMGeneratorHostKeyProvider(new File(basePath, KEY_NAME + ".pem").getPath()));
    } else {
      sshServer.setKeyPairProvider(
          new SimpleGeneratorHostKeyProvider(new File(basePath, KEY_NAME + ".ser").getPath()));
    }

    final OpenEJBShellFactory sf = new OpenEJBShellFactory(bind, port);
    sshServer.setShellFactory(sf);

    final JaasPasswordAuthenticator authenticator = new OpenEJBJaasPasswordAuthenticator();
    authenticator.setDomain(domain);
    sshServer.setPasswordAuthenticator(authenticator);

    try {
      sshServer.start();
    } catch (IOException e) {
      // no-op
    }
  }
  private void bindResource(final String name, final Object value, final String type) {
    Assembler assembler =
        (Assembler) SystemInstance.get().getComponent(org.apache.openejb.spi.Assembler.class);
    try {
      assembler
          .getContainerSystem()
          .getJNDIContext()
          .lookup(Assembler.OPENEJB_RESOURCE_JNDI_PREFIX + name);
      return;
    } catch (NamingException ne) {
      // no-op: OK
    }

    final ResourceInfo resourceInfo = new ResourceInfo();
    resourceInfo.id = name;
    resourceInfo.service = "Resource";
    resourceInfo.types.add(type);
    PassthroughFactory.add(resourceInfo, value);

    logger.info(
        "Importing a Tomcat Resource with id '" + resourceInfo.id + "' of type '" + type + "'.");
    try {
      assembler.createResource(resourceInfo);
    } catch (OpenEJBException e) {
      logger.error("Unable to bind Global Tomcat resource " + name + " into OpenEJB", e);
    }
  }
Exemplo n.º 12
0
  public static List<Object> resolve(
      final Collection<ServiceInfo> serviceInfos, final String[] ids, final Factory factory) {
    if (ids == null || ids.length == 0) {
      return null;
    }

    final List<Object> instances = new ArrayList<Object>();
    for (final String id : ids) {
      Object instance = resolve(serviceInfos, id);
      if (instance == null) { // maybe id == classname
        try {
          final Class<?> aClass = Thread.currentThread().getContextClassLoader().loadClass(id);
          if (factory == null) {
            instance = aClass.newInstance();
          } else {
            instance = factory.newInstance(aClass);
          }
        } catch (final Exception e) {
          // ignore
        }
      }
      if (instance == null) {
        instance =
            resolve(
                SystemInstance.get().getComponent(OpenEjbConfiguration.class).facilities.services,
                id);
      }

      if (instance != null) {
        instances.add(instance);
      }
    }
    return instances;
  }
Exemplo n.º 13
0
  public DiscoveryRegistry(final DiscoveryAgent agent) {

    executor =
        new ThreadPoolExecutor(
            1,
            10,
            30,
            TimeUnit.SECONDS,
            new LinkedBlockingQueue<Runnable>(1),
            new ThreadFactory() {
              @Override
              public Thread newThread(final Runnable runable) {
                final Thread t = new Thread(runable, DiscoveryRegistry.class.getSimpleName());
                t.setDaemon(true);
                return t;
              }
            });

    executor.setRejectedExecutionHandler(
        new RejectedExecutionHandler() {
          @Override
          public void rejectedExecution(final Runnable r, final ThreadPoolExecutor tpe) {
            if (null == r
                || null == tpe
                || tpe.isShutdown()
                || tpe.isTerminated()
                || tpe.isTerminating()) {
              return;
            }

            try {
              tpe.getQueue().offer(r, 20, TimeUnit.SECONDS);
            } catch (InterruptedException e) {
              // Ignore
            }
          }
        });

    SystemInstance.get().setComponent(DiscoveryRegistry.class, this);
    SystemInstance.get().setComponent(DiscoveryAgent.class, this);

    if (null != agent) {
      addDiscoveryAgent(agent);
    }
  }
 private boolean inTransaction() {
   try {
     TransactionManager transactionManager =
         SystemInstance.get().getComponent(TransactionManager.class);
     int status = transactionManager.getStatus();
     return status == Status.STATUS_ACTIVE || status == Status.STATUS_MARKED_ROLLBACK;
   } catch (SystemException e) {
     throw new RuntimeException(e);
   }
 }
  private void initializeDependencies(BeanContext beanContext) throws OpenEJBException {
    SystemInstance systemInstance = SystemInstance.get();
    ContainerSystem containerSystem = systemInstance.getComponent(ContainerSystem.class);
    for (String dependencyId : beanContext.getDependsOn()) {
      BeanContext dependencyContext = containerSystem.getBeanContext(dependencyId);
      if (dependencyContext == null) {
        throw new OpenEJBException(
            "Deployment does not exist. Deployment(id='" + dependencyContext + "')");
      }

      final Object containerData = dependencyContext.getContainerData();

      // Bean may not be a singleton or may be a singleton
      // managed by a different container implementation
      if (containerData instanceof Data) {
        Data data = (Data) containerData;

        data.initialize();
      }
    }
  }
Exemplo n.º 16
0
 @Override
 protected void setComponentInstanceMap() {
   // TODO: think if not using a proxy could be more clever ;)
   componentInstanceMap =
       Map.class.cast(
           Proxy.newProxyInstance(
               Thread.currentThread().getContextClassLoader(),
               MAP,
               new TransactionalMapHandler(
                   this,
                   SystemInstance.get().getComponent(TransactionSynchronizationRegistry.class))));
 }
Exemplo n.º 17
0
 public static synchronized void init(final Properties properties) throws Exception {
   if (initialized) return;
   system = new SystemInstance(properties);
   readUserSystemProperties();
   readSystemProperties();
   readSystemProperties(get().currentProfile());
   System.getProperties()
       .putAll(system.getProperties()); // if the user read System.getProperties() instead of our
   // properties, used in bval-tomee tck for instance
   initialized = true;
   get().setProperty("openejb.profile.custom", Boolean.toString(!get().isDefaultProfile()));
 }
Exemplo n.º 18
0
  public Object getObjectInstance(Object object, Name name, Context context, Hashtable environment)
      throws Exception {
    Reference ref = (Reference) object;

    // load the component type class
    String className = getProperty(ref, COMPONENT_TYPE);
    Class<?> clazz = loadClass(className);
    if (clazz == null) return null;

    // lookup the value
    Object value = SystemInstance.get().getComponent(clazz);
    return value;
  }
Exemplo n.º 19
0
  @Override
  public Enumeration<URL> getResources(final String name) throws IOException {
    if (!getState().isAvailable()) {
      return null;
    }

    if ("META-INF/services/javax.servlet.ServletContainerInitializer".equals(name)) {
      final Collection<URL> list = new ArrayList<>(Collections.list(super.getResources(name)));
      final Iterator<URL> it = list.iterator();
      while (it.hasNext()) {
        final URL next = it.next();
        final File file = Files.toFile(next);
        if (!file.isFile() && NewLoaderLogic.skip(next)) {
          it.remove();
        }
      }
      return Collections.enumeration(list);
    }
    if ("META-INF/services/javax.websocket.ContainerProvider".equals(name)) {
      final Collection<URL> list = new ArrayList<>(Collections.list(super.getResources(name)));
      final Iterator<URL> it = list.iterator();
      while (it.hasNext()) {
        final URL next = it.next();
        final File file = Files.toFile(next);
        if (!file.isFile() && NewLoaderLogic.skip(next)) {
          it.remove();
        }
      }
      return Collections.enumeration(list);
    }
    if ("META-INF/faces-config.xml".equals(name)) { // mojarra workaround
      try {
        if (WebBeansContext.currentInstance() == null
            && Boolean.parseBoolean(
                SystemInstance.get().getProperty("tomee.jsf.ignore-owb", "true"))) {
          final Collection<URL> list = new HashSet<>(Collections.list(super.getResources(name)));
          final Iterator<URL> it = list.iterator();
          while (it.hasNext()) {
            final String fileName = Files.toFile(it.next()).getName();
            if (fileName.startsWith("openwebbeans-" /*jsf|el22*/) && fileName.endsWith(".jar")) {
              it.remove();
            }
          }
          return Collections.enumeration(list);
        }
      } catch (final Throwable th) {
        // no-op
      }
    }
    return URLClassLoaderFirst.filterResources(name, super.getResources(name));
  }
Exemplo n.º 20
0
  private static void readSystemProperties(final String prefix) {
    final String completePrefix;
    if (prefix != null && !prefix.isEmpty()) {
      completePrefix = prefix + ".";
    } else {
      completePrefix = "";
    }

    // Read in and apply the conf/system.properties
    final File conf = system.getConf(completePrefix + "system.properties");
    if (conf != null && conf.exists()) {
      addSystemProperties(conf);
    }
  }
Exemplo n.º 21
0
  private static void addSystemProperties(final File file) {
    if (!file.exists()) {
      return;
    }

    final Properties systemProperties;
    try {
      systemProperties = IO.readProperties(file);
    } catch (IOException e) {
      return;
    }

    system.getProperties().putAll(systemProperties);
  }
Exemplo n.º 22
0
  public static void addAdditionalLibraries() throws IOException {
    final File conf = SystemInstance.get().getConf(ADDITIONAL_LIB_CONFIG);
    if (conf == null || !conf.exists()) {
      return;
    }

    final Properties additionalLibProperties = IO.readProperties(conf);

    final List<String> libToCopy = new ArrayList<String>();
    final String toCopy = additionalLibProperties.getProperty(JAR_KEY);
    if (toCopy != null) {
      for (final String lib : toCopy.split(",")) {
        libToCopy.add(realLocation(lib.trim()));
      }
    }
    final String toExtract = additionalLibProperties.getProperty(ZIP_KEY);
    if (toExtract != null) {
      for (final String zip : toExtract.split(",")) {
        libToCopy.addAll(extract(realLocation(zip)));
      }
    }

    final File destination;
    if (additionalLibProperties.containsKey(DESTINATION_KEY)) {
      destination = new File(additionalLibProperties.getProperty(DESTINATION_KEY));
    } else {
      destination =
          new File(SystemInstance.get().getBase().getDirectory(), Embedder.ADDITIONAL_LIB_FOLDER);
    }
    if (!destination.exists()) {
      Files.mkdirs(destination);
    }

    for (final String lib : libToCopy) {
      copy(new File(lib), destination);
    }
  }
Exemplo n.º 23
0
  // mainly intended to avoid conflicts between internal and overrided spec extensions
  private boolean isFiltered(final Collection<Extension> extensions, final Extension next) {
    final ClassLoader containerLoader = ParentClassLoaderFinder.Helper.get();
    final Class<? extends Extension> extClass = next.getClass();
    if (extClass.getClassLoader() != containerLoader) {
      return false;
    }

    final String name = extClass.getName();
    switch (name) {
      case "org.apache.bval.cdi.BValExtension":
        for (final Extension e : extensions) {
          final String en = e.getClass().getName();

          // org.hibernate.validator.internal.cdi.ValidationExtension but allowing few evolutions of
          // packages
          if (en.startsWith("org.hibernate.validator.") && en.endsWith("ValidationExtension")) {
            log.info("Skipping BVal CDI integration cause hibernate was found in the application");
            return true;
          }
        }
        break;
      case "org.apache.batchee.container.cdi.BatchCDIInjectionExtension": // see
                                                                          // org.apache.openejb.batchee.BatchEEServiceManager
        return "true"
            .equals(SystemInstance.get().getProperty("tomee.batchee.cdi.use-extension", "false"));
      case "org.apache.commons.jcs.jcache.cdi.MakeJCacheCDIInterceptorFriendly":
        final String spi = "META-INF/services/javax.cache.spi.CachingProvider";
        try {
          final Enumeration<URL> appResources =
              Thread.currentThread().getContextClassLoader().getResources(spi);
          if (appResources != null && appResources.hasMoreElements()) {
            final Collection<URL> containerResources =
                Collections.list(containerLoader.getResources(spi));
            do {
              if (!containerResources.contains(appResources.nextElement())) {
                log.info(
                    "Skipping JCS CDI integration cause another provide was found in the application");
                return true;
              }
            } while (appResources.hasMoreElements());
          }
        } catch (final Exception e) {
          // no-op
        }
        break;
      default:
    }
    return false;
  }
Exemplo n.º 24
0
  public File getConf(final String subPath) {
    File conf = null;
    try {
      conf = system.getBase().getDirectory("conf");
    } catch (IOException e) {
      // no-op
    }

    if (conf == null || !conf.exists()) {
      try {
        conf = system.getBase().getDirectory("etc");
      } catch (IOException e) {
        // no-op
      }
    }

    if (conf == null || !conf.exists()) {
      return new File(system.getBase().getDirectory(), "conf");
    }
    if (subPath == null) {
      return conf;
    }
    return new File(conf, subPath);
  }
Exemplo n.º 25
0
 public synchronized void initAdditionalRepos() {
   if (additionalRepos != null) {
     return;
   }
   if (CONTEXT.get() != null) {
     additionalRepos = new LinkedList<>();
     final String contextPath = CONTEXT.get().getServletContext().getContextPath();
     final String name = contextPath.isEmpty() ? "ROOT" : contextPath.substring(1);
     final String externalRepositories =
         SystemInstance.get().getProperty("tomee." + name + ".externalRepositories");
     if (externalRepositories != null) {
       for (final String additional : externalRepositories.split(",")) {
         final String trim = additional.trim();
         if (!trim.isEmpty()) {
           final File file = new File(trim);
           additionalRepos.add(file);
         }
       }
     }
   }
 }
Exemplo n.º 26
0
  private static Collection<String> extract(final String zip) throws IOException {
    final File tmp = new File(SystemInstance.get().getBase().getDirectory(), TEMP_DIR);
    if (!tmp.exists()) {
      try {
        Files.mkdirs(tmp);
      } catch (Files.FileRuntimeException fre) {
        // ignored
      }
    }

    final File zipFile = new File(realLocation(zip));
    final File extracted = new File(tmp, zipFile.getName().replace(".zip", ""));
    if (extracted.exists()) {
      return list(extracted);
    } else {
      Files.mkdirs(extracted);
    }

    Zips.unzip(zipFile, extracted);
    return list(extracted);
  }
Exemplo n.º 27
0
  // embeddeding implementation of sthg (JPA, JSF) can lead to classloading issues if we don't
  // enrich the webapp
  // with our integration jars
  // typically the class will try to be loaded by the common classloader
  // but the interface implemented or the parent class
  // will be in the webapp
  @Override
  public void start() throws LifecycleException {
    super.start(); // do it first otherwise we can't use this as classloader

    // mainly for tomee-maven-plugin
    initAdditionalRepos();
    if (additionalRepos != null && !additionalRepos.isEmpty()) {
      for (final File f : additionalRepos) {
        final DirResourceSet webResourceSet =
            new PremptiveDirResourceSet(resources, "/", f.getAbsolutePath(), "/");
        resources.addPreResources(webResourceSet);
      }
      resources.setCachingAllowed(false);
    }

    // add configurer enrichments
    if (configurer != null) {
      // add now we removed all we wanted
      final URL[] enrichment = configurer.additionalURLs();
      for (final URL url : enrichment) {
        super.addURL(url);
      }
    }

    // add internal enrichments
    for (final URL url : SystemInstance.get().getComponent(WebAppEnricher.class).enrichment(this)) {
      super.addURL(url);
    }

    // WEB-INF/jars.xml
    final File war = Contexts.warPath(CONTEXT.get());
    final File jarsXml = new File(war, "WEB-INF/" + QuickJarsTxtParser.FILE_NAME);
    final ClassLoaderConfigurer configurerTxt = QuickJarsTxtParser.parse(jarsXml);
    if (configurerTxt != null) {
      configurer = new CompositeClassLoaderConfigurer(configurer, configurerTxt);
    }

    stopped = false;
  }
Exemplo n.º 28
0
 public static void install() {
   SystemInstance.get().getOptions().setLogger(new OptionsLog());
 }
Exemplo n.º 29
0
 public static boolean isStatsActivated() {
   return SystemInstance.get().getOptions().get(DISABLE_STAT_INTERCEPTOR_PROPERTY, true);
 }
Exemplo n.º 30
0
  @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;
  }