Search in sources :

Example 36 with ObjectRecipe

use of org.apache.xbean.recipe.ObjectRecipe in project tomee by apache.

the class Client method main.

public static void main(final String[] args) throws Exception {
    if (args.length != 1) {
        System.err.println("Pass the base url as parameter");
        return;
    }
    final ConsoleReader reader = new ConsoleReader(System.in, new OutputStreamWriter(System.out));
    reader.addCompletor(new FileNameCompletor());
    reader.addCompletor(new SimpleCompletor(CommandManager.keys().toArray(new String[CommandManager.size()])));
    String line;
    while ((line = reader.readLine(PROMPT)) != null) {
        if (EXIT_CMD.equals(line)) {
            break;
        }
        Class<?> cmdClass = null;
        for (Map.Entry<String, Class<?>> cmd : CommandManager.getCommands().entrySet()) {
            if (line.startsWith(cmd.getKey())) {
                cmdClass = cmd.getValue();
                break;
            }
        }
        if (cmdClass != null) {
            final ObjectRecipe recipe = new ObjectRecipe(cmdClass);
            recipe.setProperty("url", args[0]);
            recipe.setProperty("command", line);
            recipe.setProperty("commands", CommandManager.getCommands());
            recipe.allow(Option.CASE_INSENSITIVE_PROPERTIES);
            recipe.allow(Option.IGNORE_MISSING_PROPERTIES);
            recipe.allow(Option.NAMED_PARAMETERS);
            try {
                final AbstractCommand cmdInstance = (AbstractCommand) recipe.create();
                cmdInstance.execute(line);
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            System.err.println("sorry i don't understand '" + line + "'");
        }
    }
}
Also used : ConsoleReader(jline.ConsoleReader) ObjectRecipe(org.apache.xbean.recipe.ObjectRecipe) FileNameCompletor(jline.FileNameCompletor) SimpleCompletor(jline.SimpleCompletor) AbstractCommand(jug.client.command.api.AbstractCommand) OutputStreamWriter(java.io.OutputStreamWriter) Map(java.util.Map)

Example 37 with ObjectRecipe

use of org.apache.xbean.recipe.ObjectRecipe in project tomee by apache.

the class Configuration method loadFromProperties.

public void loadFromProperties(final Properties config) {
    // filtering properties with system properties or themself
    final StrSubstitutor strSubstitutor = new StrSubstitutor(new StrLookup<String>() {

        @Override
        public String lookup(final String key) {
            final String property = System.getProperty(key);
            return property == null ? config.getProperty(key) : null;
        }
    });
    for (final String key : config.stringPropertyNames()) {
        final String val = config.getProperty(key);
        if (val == null || val.trim().isEmpty()) {
            continue;
        }
        final String newVal = strSubstitutor.replace(config.getProperty(key));
        if (!val.equals(newVal)) {
            config.setProperty(key, newVal);
        }
    }
    final String http = config.getProperty("http");
    if (http != null) {
        setHttpPort(Integer.parseInt(http));
    }
    final String https = config.getProperty("https");
    if (https != null) {
        setHttpsPort(Integer.parseInt(https));
    }
    final String stop = config.getProperty("stop");
    if (stop != null) {
        setStopPort(Integer.parseInt(stop));
    }
    final String host = config.getProperty("host");
    if (host != null) {
        setHost(host);
    }
    final String dir = config.getProperty("dir");
    if (dir != null) {
        setDir(dir);
    }
    final String serverXml = config.getProperty("serverXml");
    if (serverXml != null) {
        setServerXml(serverXml);
    }
    final String keepServerXmlAsThis = config.getProperty("keepServerXmlAsThis");
    if (keepServerXmlAsThis != null) {
        setKeepServerXmlAsThis(Boolean.parseBoolean(keepServerXmlAsThis));
    }
    final String quickSession = config.getProperty("quickSession");
    if (quickSession != null) {
        setQuickSession(Boolean.parseBoolean(quickSession));
    }
    final String skipHttp = config.getProperty("skipHttp");
    if (skipHttp != null) {
        setSkipHttp(Boolean.parseBoolean(skipHttp));
    }
    final String ssl = config.getProperty("ssl");
    if (ssl != null) {
        setSsl(Boolean.parseBoolean(ssl));
    }
    final String http2 = config.getProperty("http2");
    if (http2 != null) {
        setHttp2(Boolean.parseBoolean(http2));
    }
    final String deleteBaseOnStartup = config.getProperty("deleteBaseOnStartup");
    if (deleteBaseOnStartup != null) {
        setDeleteBaseOnStartup(Boolean.parseBoolean(deleteBaseOnStartup));
    }
    final String webResourceCached = config.getProperty("webResourceCached");
    if (webResourceCached != null) {
        setWebResourceCached(Boolean.parseBoolean(webResourceCached));
    }
    final String withEjbRemote = config.getProperty("withEjbRemote");
    if (withEjbRemote != null) {
        setWithEjbRemote(Boolean.parseBoolean(withEjbRemote));
    }
    final String deployOpenEjbApp = config.getProperty("deployOpenEjbApp");
    if (deployOpenEjbApp != null) {
        setDeployOpenEjbApp(Boolean.parseBoolean(deployOpenEjbApp));
    }
    final String keystoreFile = config.getProperty("keystoreFile");
    if (keystoreFile != null) {
        setKeystoreFile(keystoreFile);
    }
    final String keystorePass = config.getProperty("keystorePass");
    if (keystorePass != null) {
        setKeystorePass(keystorePass);
    }
    final String keystoreType = config.getProperty("keystoreType");
    if (keystoreType != null) {
        setKeystoreType(keystoreType);
    }
    final String clientAuth = config.getProperty("clientAuth");
    if (clientAuth != null) {
        setClientAuth(clientAuth);
    }
    final String keyAlias = config.getProperty("keyAlias");
    if (keyAlias != null) {
        setKeyAlias(keyAlias);
    }
    final String sslProtocol = config.getProperty("sslProtocol");
    if (sslProtocol != null) {
        setSslProtocol(sslProtocol);
    }
    final String webXml = config.getProperty("webXml");
    if (webXml != null) {
        setWebXml(webXml);
    }
    final String tempDir = config.getProperty("tempDir");
    if (tempDir != null) {
        setTempDir(tempDir);
    }
    final String customWebResources = config.getProperty("customWebResources");
    if (customWebResources != null) {
        setCustomWebResources(customWebResources);
    }
    final String classesFilterType = config.getProperty("classesFilter");
    if (classesFilterType != null) {
        try {
            setClassesFilter(Filter.class.cast(Thread.currentThread().getContextClassLoader().loadClass(classesFilterType).newInstance()));
        } catch (final InstantiationException | IllegalAccessException | ClassNotFoundException e) {
            throw new IllegalArgumentException(e);
        }
    }
    final String conf = config.getProperty("conf");
    if (conf != null) {
        setConf(conf);
    }
    for (final String prop : config.stringPropertyNames()) {
        if (prop.startsWith("properties.")) {
            property(prop.substring("properties.".length()), config.getProperty(prop));
        } else if (prop.startsWith("users.")) {
            user(prop.substring("users.".length()), config.getProperty(prop));
        } else if (prop.startsWith("roles.")) {
            role(prop.substring("roles.".length()), config.getProperty(prop));
        } else if (prop.startsWith("connector.")) {
            // created in container
            property(prop, config.getProperty(prop));
        } else if (prop.equals("realm")) {
            final ObjectRecipe recipe = new ObjectRecipe(config.getProperty(prop));
            for (final String realmConfig : config.stringPropertyNames()) {
                if (realmConfig.startsWith("realm.")) {
                    recipe.setProperty(realmConfig.substring("realm.".length()), config.getProperty(realmConfig));
                }
            }
            setRealm(Realm.class.cast(recipe.create()));
        } else if (prop.equals("login")) {
            final ObjectRecipe recipe = new ObjectRecipe(LoginConfigBuilder.class.getName());
            for (final String nestedConfig : config.stringPropertyNames()) {
                if (nestedConfig.startsWith("login.")) {
                    recipe.setProperty(nestedConfig.substring("login.".length()), config.getProperty(nestedConfig));
                }
            }
            loginConfig(LoginConfigBuilder.class.cast(recipe.create()));
        } else if (prop.equals("securityConstraint")) {
            final ObjectRecipe recipe = new ObjectRecipe(SecurityConstaintBuilder.class.getName());
            for (final String nestedConfig : config.stringPropertyNames()) {
                if (nestedConfig.startsWith("securityConstraint.")) {
                    recipe.setProperty(nestedConfig.substring("securityConstraint.".length()), config.getProperty(nestedConfig));
                }
            }
            securityConstaint(SecurityConstaintBuilder.class.cast(recipe.create()));
        } else if (prop.equals("configurationCustomizer.")) {
            final String next = prop.substring("configurationCustomizer.".length());
            if (next.contains(".")) {
                continue;
            }
            final ObjectRecipe recipe = new ObjectRecipe(properties.getProperty(prop + ".class"));
            for (final String nestedConfig : config.stringPropertyNames()) {
                if (nestedConfig.startsWith(prop) && !prop.endsWith(".class")) {
                    recipe.setProperty(nestedConfig.substring(prop.length() + 1), config.getProperty(nestedConfig));
                }
            }
            addCustomizer(ConfigurationCustomizer.class.cast(recipe.create()));
        }
    }
}
Also used : StrSubstitutor(org.apache.commons.lang3.text.StrSubstitutor) ObjectRecipe(org.apache.xbean.recipe.ObjectRecipe) Filter(org.apache.xbean.finder.filter.Filter) Realm(org.apache.catalina.Realm)

Example 38 with ObjectRecipe

use of org.apache.xbean.recipe.ObjectRecipe in project tomee by apache.

the class LazyRealm method instance.

private Realm instance() {
    if (delegate == null) {
        synchronized (this) {
            if (delegate == null) {
                final Object instance;
                ClassLoader cl = Thread.currentThread().getContextClassLoader();
                if (container != null && container.getLoader() != null && container.getLoader().getClassLoader() != null) {
                    cl = container.getLoader().getClassLoader();
                }
                final Class<?> clazz;
                try {
                    clazz = cl.loadClass(realmClass);
                } catch (final ClassNotFoundException e) {
                    throw new TomEERuntimeException(e);
                }
                if (!cdi) {
                    try {
                        final ObjectRecipe recipe = new ObjectRecipe(clazz);
                        recipe.allow(Option.CASE_INSENSITIVE_PROPERTIES);
                        recipe.allow(Option.IGNORE_MISSING_PROPERTIES);
                        recipe.allow(Option.FIELD_INJECTION);
                        recipe.allow(Option.PRIVATE_PROPERTIES);
                        if (properties != null) {
                            final Properties props = new PropertiesAdapter().unmarshal(properties.trim().replaceAll("\\p{Space}*(\\p{Alnum}*)=", "\n$1="));
                            recipe.setAllProperties(props);
                        }
                        instance = recipe.create();
                    } catch (final Exception e) {
                        throw new TomEERuntimeException(e);
                    }
                } else {
                    final WebBeansContext webBeansContext;
                    try {
                        webBeansContext = WebBeansContext.currentInstance();
                        if (webBeansContext == null) {
                            return null;
                        }
                    } catch (final IllegalStateException ise) {
                        // too early to have a cdi bean, skip these methods - mainly init() but @PostConstruct works then
                        return null;
                    }
                    final BeanManager bm = webBeansContext.getBeanManagerImpl();
                    final Set<Bean<?>> beans = bm.getBeans(clazz);
                    final Bean<?> bean = bm.resolve(beans);
                    if (bean == null) {
                        return null;
                    }
                    creationalContext = bm.createCreationalContext(null);
                    instance = bm.getReference(bean, clazz, creationalContext);
                }
                if (instance == null) {
                    throw new TomEERuntimeException("realm can't be retrieved from cdi");
                }
                if (instance instanceof Realm) {
                    delegate = (Realm) instance;
                    delegate.setContainer(container);
                    delegate.setCredentialHandler(credentialHandler);
                    if (Lifecycle.class.isInstance(delegate)) {
                        if (init) {
                            try {
                                final Lifecycle lifecycle = Lifecycle.class.cast(delegate);
                                lifecycle.init();
                                if (start) {
                                    lifecycle.start();
                                }
                            } catch (final LifecycleException e) {
                            // no-op
                            }
                        }
                    }
                } else {
                    delegate = new LowTypedRealm(instance);
                    delegate.setContainer(container);
                    delegate.setCredentialHandler(credentialHandler);
                }
                for (final PropertyChangeListener listener : support.getPropertyChangeListeners()) {
                    delegate.addPropertyChangeListener(listener);
                }
            }
        }
    }
    return delegate;
}
Also used : LifecycleException(org.apache.catalina.LifecycleException) PropertyChangeListener(java.beans.PropertyChangeListener) Lifecycle(org.apache.catalina.Lifecycle) Properties(java.util.Properties) TomEERuntimeException(org.apache.tomee.catalina.TomEERuntimeException) LifecycleException(org.apache.catalina.LifecycleException) IOException(java.io.IOException) TomEERuntimeException(org.apache.tomee.catalina.TomEERuntimeException) Bean(javax.enterprise.inject.spi.Bean) PropertiesAdapter(org.apache.openejb.config.sys.PropertiesAdapter) WebBeansContext(org.apache.webbeans.config.WebBeansContext) ObjectRecipe(org.apache.xbean.recipe.ObjectRecipe) BeanManager(javax.enterprise.inject.spi.BeanManager) Realm(org.apache.catalina.Realm)

Example 39 with ObjectRecipe

use of org.apache.xbean.recipe.ObjectRecipe in project tomee by apache.

the class Container method createConnector.

protected Connector createConnector() {
    final Connector connector;
    final Properties properties = configuration.getProperties();
    if (properties != null) {
        final Map<String, String> attributes = new HashMap<>();
        final ObjectRecipe recipe = new ObjectRecipe(Connector.class);
        for (final String key : properties.stringPropertyNames()) {
            if (!key.startsWith("connector.")) {
                continue;
            }
            final String substring = key.substring("connector.".length());
            if (!substring.startsWith("attributes.")) {
                recipe.setProperty(substring, properties.getProperty(key));
            } else {
                attributes.put(substring.substring("attributes.".length()), properties.getProperty(key));
            }
        }
        connector = recipe.getProperties().isEmpty() ? new Connector() : Connector.class.cast(recipe.create());
        for (final Map.Entry<String, String> attr : attributes.entrySet()) {
            connector.setAttribute(attr.getKey(), attr.getValue());
        }
    } else {
        connector = new Connector();
    }
    return connector;
}
Also used : Connector(org.apache.catalina.connector.Connector) ObjectRecipe(org.apache.xbean.recipe.ObjectRecipe) HashMap(java.util.HashMap) CatalinaProperties(org.apache.catalina.startup.CatalinaProperties) Properties(java.util.Properties) Map(java.util.Map) HashMap(java.util.HashMap)

Example 40 with ObjectRecipe

use of org.apache.xbean.recipe.ObjectRecipe in project meecrowave by apache.

the class Meecrowave method buildSslHostConfig.

private List<SSLHostConfig> buildSslHostConfig() {
    final List<SSLHostConfig> sslHostConfigs = new ArrayList<>();
    // Configures default SSLHostConfig
    final ObjectRecipe defaultSslHostConfig = new ObjectRecipe(SSLHostConfig.class);
    for (final String key : configuration.properties.stringPropertyNames()) {
        if (key.startsWith("connector.sslhostconfig.") && key.split("\\.").length == 3) {
            final String substring = key.substring("connector.sslhostconfig.".length());
            defaultSslHostConfig.setProperty(substring, configuration.properties.getProperty(key));
        }
    }
    if (!defaultSslHostConfig.getProperties().isEmpty()) {
        sslHostConfigs.add(SSLHostConfig.class.cast(defaultSslHostConfig.create()));
    }
    // Allows to add N Multiple SSLHostConfig elements not including the default one.
    final Collection<Integer> itemNumbers = configuration.properties.stringPropertyNames().stream().filter(key -> (key.startsWith("connector.sslhostconfig.") && key.split("\\.").length == 4)).map(key -> Integer.parseInt(key.split("\\.")[2])).collect(toSet());
    itemNumbers.stream().sorted().forEach(itemNumber -> {
        final ObjectRecipe recipe = new ObjectRecipe(SSLHostConfig.class);
        final String prefix = "connector.sslhostconfig." + itemNumber + '.';
        configuration.properties.stringPropertyNames().stream().filter(k -> k.startsWith(prefix)).forEach(key -> {
            final String keyName = key.split("\\.")[3];
            recipe.setProperty(keyName, configuration.properties.getProperty(key));
        });
        if (!recipe.getProperties().isEmpty()) {
            final SSLHostConfig sslHostConfig = SSLHostConfig.class.cast(recipe.create());
            sslHostConfigs.add(sslHostConfig);
            new LogFacade(Meecrowave.class.getName()).info("Created SSLHostConfig #" + itemNumber + " (" + sslHostConfig.getHostName() + ")");
        }
    });
    return sslHostConfigs;
}
Also used : MeecrowaveClientLifecycleListener(org.apache.meecrowave.cxf.MeecrowaveClientLifecycleListener) ProvidedLoader(org.apache.meecrowave.tomcat.ProvidedLoader) SecurityCollection(org.apache.tomcat.util.descriptor.web.SecurityCollection) SecretKeySpec(javax.crypto.spec.SecretKeySpec) ServerSocket(java.net.ServerSocket) URLClassLoader(java.net.URLClassLoader) Host(org.apache.catalina.Host) StopListening(org.apache.meecrowave.api.StopListening) Map(java.util.Map) SAXParser(javax.xml.parsers.SAXParser) Path(java.nio.file.Path) Log4j2Log(org.apache.meecrowave.logging.tomcat.Log4j2Log) LifecycleException(org.apache.catalina.LifecycleException) Set(java.util.Set) CDI(javax.enterprise.inject.spi.CDI) CDIInstanceManager(org.apache.meecrowave.tomcat.CDIInstanceManager) StandardCharsets(java.nio.charset.StandardCharsets) WebBeansContext(org.apache.webbeans.config.WebBeansContext) BufferStrategy(org.apache.johnzon.core.BufferStrategy) ResourceFinder(org.apache.xbean.finder.ResourceFinder) Stream(java.util.stream.Stream) ConfigurableBus(org.apache.meecrowave.cxf.ConfigurableBus) JarScanFilter(org.apache.tomcat.JarScanFilter) TomcatAutoInitializer(org.apache.meecrowave.tomcat.TomcatAutoInitializer) Log4j2Logger(org.apache.meecrowave.logging.jul.Log4j2Logger) Connector(org.apache.catalina.connector.Connector) StandardHost(org.apache.catalina.core.StandardHost) AnnotatedType(javax.enterprise.inject.spi.AnnotatedType) StandardCopyOption(java.nio.file.StandardCopyOption) ArrayList(java.util.ArrayList) CreationalContext(javax.enterprise.context.spi.CreationalContext) StrLookup(org.apache.commons.text.StrLookup) SecurityConstraint(org.apache.tomcat.util.descriptor.web.SecurityConstraint) StreamSupport(java.util.stream.StreamSupport) SSLHostConfig(org.apache.tomcat.util.net.SSLHostConfig) ManagementFactory(java.lang.management.ManagementFactory) Service(org.apache.catalina.Service) Properties(java.util.Properties) LogFacade(org.apache.meecrowave.logging.tomcat.LogFacade) Files(java.nio.file.Files) FileOutputStream(java.io.FileOutputStream) IOException(java.io.IOException) ValueTransformer(org.apache.meecrowave.service.ValueTransformer) Field(java.lang.reflect.Field) File(java.io.File) ObjectRecipe(org.apache.xbean.recipe.ObjectRecipe) DefaultHandler(org.xml.sax.helpers.DefaultHandler) TreeMap(java.util.TreeMap) Paths(java.nio.file.Paths) CliOption(org.apache.meecrowave.runner.cli.CliOption) BeanManager(javax.enterprise.inject.spi.BeanManager) MeecrowaveContextConfig(org.apache.catalina.startup.MeecrowaveContextConfig) URL(java.net.URL) Lifecycle(org.apache.catalina.Lifecycle) Catalina(org.apache.catalina.startup.Catalina) OWBJarScanner(org.apache.meecrowave.tomcat.OWBJarScanner) Http2Protocol(org.apache.coyote.http2.Http2Protocol) IO(org.apache.meecrowave.io.IO) LifecycleState(org.apache.catalina.LifecycleState) Collectors.toSet(java.util.stream.Collectors.toSet) Server(org.apache.catalina.Server) StartListening(org.apache.meecrowave.api.StartListening) Collections.emptyList(java.util.Collections.emptyList) Collection(java.util.Collection) ServiceLoader(java.util.ServiceLoader) FileNotFoundException(java.io.FileNotFoundException) Objects(java.util.Objects) Base64(java.util.Base64) List(java.util.List) Realm(org.apache.catalina.Realm) SAXException(org.xml.sax.SAXException) Writer(java.io.Writer) StandardContext(org.apache.catalina.core.StandardContext) NoDescriptorRegistry(org.apache.meecrowave.tomcat.NoDescriptorRegistry) OWBAutoSetup(org.apache.meecrowave.openwebbeans.OWBAutoSetup) LoginConfig(org.apache.tomcat.util.descriptor.web.LoginConfig) SAXParserFactory(javax.xml.parsers.SAXParserFactory) HashMap(java.util.HashMap) AtomicReference(java.util.concurrent.atomic.AtomicReference) Function(java.util.function.Function) Cipher(javax.crypto.Cipher) BiPredicate(java.util.function.BiPredicate) ServletContainerInitializer(javax.servlet.ServletContainerInitializer) Log4j2Shutdown(org.apache.meecrowave.logging.log4j2.Log4j2Shutdown) Attributes(org.xml.sax.Attributes) ROOT(java.util.Locale.ROOT) InjectionTarget(javax.enterprise.inject.spi.InjectionTarget) Manager(org.apache.catalina.Manager) CxfCdiAutoSetup(org.apache.meecrowave.cxf.CxfCdiAutoSetup) LinkedList(java.util.LinkedList) OutputStream(java.io.OutputStream) Collections.emptySet(java.util.Collections.emptySet) MalformedURLException(java.net.MalformedURLException) ManagerBase(org.apache.catalina.session.ManagerBase) Log4j2LoggerFactory(org.apache.meecrowave.logging.openwebbeans.Log4j2LoggerFactory) Optional.ofNullable(java.util.Optional.ofNullable) LoggingAccessLogPattern(org.apache.meecrowave.tomcat.LoggingAccessLogPattern) FileWriter(java.io.FileWriter) Globals(org.apache.catalina.Globals) StandardManager(org.apache.catalina.session.StandardManager) FileInputStream(java.io.FileInputStream) Context(org.apache.catalina.Context) StrSubstitutor(org.apache.commons.text.StrSubstitutor) Registry(org.apache.tomcat.util.modeler.Registry) Consumer(java.util.function.Consumer) Tomcat(org.apache.catalina.startup.Tomcat) Collectors.toList(java.util.stream.Collectors.toList) BusFactory(org.apache.cxf.BusFactory) InputStream(java.io.InputStream) LogFacade(org.apache.meecrowave.logging.tomcat.LogFacade) ObjectRecipe(org.apache.xbean.recipe.ObjectRecipe) ArrayList(java.util.ArrayList) SSLHostConfig(org.apache.tomcat.util.net.SSLHostConfig)

Aggregations

ObjectRecipe (org.apache.xbean.recipe.ObjectRecipe)41 Map (java.util.Map)18 HashMap (java.util.HashMap)13 Properties (java.util.Properties)12 IOException (java.io.IOException)11 OpenEJBException (org.apache.openejb.OpenEJBException)9 NamingException (javax.naming.NamingException)8 InvocationTargetException (java.lang.reflect.InvocationTargetException)7 Set (java.util.Set)4 TreeMap (java.util.TreeMap)4 ApplicationException (org.apache.openejb.ApplicationException)4 SystemException (org.apache.openejb.SystemException)4 SuperProperties (org.apache.openejb.util.SuperProperties)4 MalformedURLException (java.net.MalformedURLException)3 URISyntaxException (java.net.URISyntaxException)3 TimeoutException (java.util.concurrent.TimeoutException)3 InstanceNotFoundException (javax.management.InstanceNotFoundException)3 MalformedObjectNameException (javax.management.MalformedObjectNameException)3 Realm (org.apache.catalina.Realm)3 Connector (org.apache.catalina.connector.Connector)3