Search in sources :

Example 1 with Resource

use of org.apache.openejb.config.sys.Resource in project tomee by apache.

the class ConfigurationFactory method toConfigDeclaration.

public static Object toConfigDeclaration(final String id, final URI uri) throws OpenEJBException {
    final String serviceType;
    try {
        serviceType = uri.getHost();
        final Object object;
        try {
            object = JaxbOpenejb.create(serviceType);
        } catch (final Exception e) {
            throw new OpenEJBException("Invalid URI '" + uri + "'. " + e.getMessage());
        }
        final Map<String, String> map;
        try {
            map = URISupport.parseParamters(uri);
        } catch (final URISyntaxException e) {
            throw new OpenEJBException("Unable to parse URI parameters '" + uri + "'. URISyntaxException: " + e.getMessage());
        }
        if (object instanceof AbstractService) {
            final AbstractService service = (AbstractService) object;
            service.setId(id);
            service.setType(map.remove("type"));
            service.setProvider(map.remove("provider"));
            service.setClassName(map.remove("class-name"));
            service.setConstructor(map.remove("constructor"));
            service.setFactoryName(map.remove("factory-name"));
            service.setPropertiesProvider(map.remove("properties-provider"));
            service.setTemplate(map.remove("template"));
            final String cp = map.remove("classpath");
            if (null != cp) {
                service.setClasspath(cp);
            }
            service.setClasspathAPI(map.remove("classpath-api"));
            if (object instanceof Resource) {
                final Resource resource = Resource.class.cast(object);
                final String aliases = map.remove("aliases");
                if (aliases != null) {
                    resource.getAliases().addAll(Arrays.asList(aliases.split(",")));
                }
                final String depOn = map.remove("depends-on");
                if (depOn != null) {
                    resource.getDependsOn().addAll(Arrays.asList(depOn.split(",")));
                }
                resource.setPostConstruct(map.remove("post-construct"));
                resource.setPreDestroy(map.remove("pre-destroy"));
            }
            service.getProperties().putAll(map);
        } else if (object instanceof Deployments) {
            final Deployments deployments = (Deployments) object;
            deployments.setDir(map.remove("dir"));
            deployments.setFile(map.remove("jar"));
            final String cp = map.remove("classpath");
            if (cp != null) {
                final String[] paths = cp.split(File.pathSeparator);
                final List<URL> urls = new ArrayList<>();
                for (final String path : paths) {
                    final Set<String> values = ProvisioningUtil.realLocation(PropertyPlaceHolderHelper.value(path));
                    for (final String v : values) {
                        urls.add(new File(v).toURI().normalize().toURL());
                    }
                }
                deployments.setClasspath(new URLClassLoaderFirst(urls.toArray(new URL[urls.size()]), ParentClassLoaderFinder.Helper.get()));
            }
        } else if (SystemProperty.class.isInstance(object)) {
            final SystemProperty sp = SystemProperty.class.cast(object);
            sp.setName(map.remove("name"));
            sp.setValue(map.remove("value"));
        }
        return object;
    } catch (final Exception e) {
        throw new OpenEJBException("Error declaring service '" + id + "'. Unable to create Service definition from URI '" + uri.toString() + "'", e);
    }
}
Also used : OpenEJBException(org.apache.openejb.OpenEJBException) URLClassLoaderFirst(org.apache.openejb.util.classloader.URLClassLoaderFirst) Set(java.util.Set) HashSet(java.util.HashSet) Resource(org.apache.openejb.config.sys.Resource) AdditionalDeployments(org.apache.openejb.config.sys.AdditionalDeployments) Deployments(org.apache.openejb.config.sys.Deployments) URISyntaxException(java.net.URISyntaxException) AbstractService(org.apache.openejb.config.sys.AbstractService) IOException(java.io.IOException) URISyntaxException(java.net.URISyntaxException) OpenEJBException(org.apache.openejb.OpenEJBException) MalformedURLException(java.net.MalformedURLException) URL(java.net.URL) ArrayList(java.util.ArrayList) List(java.util.List) LinkedList(java.util.LinkedList) File(java.io.File)

Example 2 with Resource

use of org.apache.openejb.config.sys.Resource in project tomee by apache.

the class EffectiveTomEEXml method main.

public static void main(final String[] args) throws Exception {
    final CommandLine line = parseCommand(args);
    if (line == null) {
        return;
    }
    final Openejb openejb = JaxbOpenejb.readConfig(findXml(line).getCanonicalPath());
    final ConfigurationFactory configFact = new ConfigurationFactory();
    for (final Resource r : openejb.getResource()) {
        final ResourceInfo ri = configFact.configureService(r, ResourceInfo.class);
        if (!ri.properties.containsKey("SkipImplicitAttributes")) {
            ri.properties.put("SkipImplicitAttributes", "false");
        }
        r.getProperties().clear();
        r.getProperties().putAll(ri.properties);
    }
    // TODO: others
    final Marshaller marshaller = JaxbOpenejb.getContext(Openejb.class).createMarshaller();
    marshaller.setProperty("jaxb.formatted.output", true);
    marshaller.marshal(openejb, System.out);
}
Also used : ResourceInfo(org.apache.openejb.assembler.classic.ResourceInfo) CommandLine(org.apache.commons.cli.CommandLine) Marshaller(javax.xml.bind.Marshaller) Resource(org.apache.openejb.config.sys.Resource) Openejb(org.apache.openejb.config.sys.Openejb) JaxbOpenejb(org.apache.openejb.config.sys.JaxbOpenejb)

Example 3 with Resource

use of org.apache.openejb.config.sys.Resource in project tomee by apache.

the class ConfigurationFactory method configureService.

/**
 * This is the major piece of code that configures services.
 * It merges the data from the <ServiceProvider> declaration
 * with the data from the openejb.xml file (say <Resource>)
 *
 * The end result is a canonical (i.e. flattened) ServiceInfo
 * The ServiceInfo will be of a specific type (ContainerInfo, ResourceInfo, etc)
 *
 * @param service  Service
 * @param infoType Class
 * @param <T>      infoType
 * @return ServiceInfo
 * @throws OpenEJBException On error
 */
public <T extends ServiceInfo> T configureService(org.apache.openejb.config.Service service, final Class<? extends T> infoType) throws OpenEJBException {
    try {
        if (infoType == null) {
            throw new NullPointerException("type");
        }
        if (service == null) {
            service = getDefaultService(infoType);
            if (service == null) {
                throw new OpenEJBException(messages.format("configureService.noDefaultService", infoType.getName()));
            }
        }
        {
            String template = service.getTemplate();
            if (template == null) {
                template = SystemInstance.get().getProperty(Template.class.getName());
            }
            if (template != null) {
                template = unaliasPropertiesProvider(template);
                // don't trim them, user wants to handle it himself, let him do it
                final ObjectRecipe recipe = newObjectRecipe(template);
                recipe.setProperty("serviceId", service.getId());
                // note: we can also use reflection if needed to limit the dependency
                Template.class.cast(recipe.create()).configure(service);
            }
        }
        final ServiceProvider provider = getServiceProvider(service, infoType);
        if (service.getId() == null) {
            service.setId(provider.getId());
        }
        final Properties overrides = trim(getSystemProperties(overrideKey(service), provider.getService()));
        final Properties serviceProperties = service.getProperties();
        trim(serviceProperties);
        trim(provider.getProperties());
        logger.info("configureService.configuring", service.getId(), provider.getService(), provider.getId());
        if (logger.isDebugEnabled()) {
            for (final Map.Entry<Object, Object> entry : serviceProperties.entrySet()) {
                final Object key = entry.getKey();
                Object value = entry.getValue();
                if (key instanceof String && "password".equalsIgnoreCase((String) key)) {
                    value = "<hidden>";
                }
                logger.debug("[" + key + "=" + value + "]");
            }
            for (final Map.Entry<Object, Object> entry : overrides.entrySet()) {
                final Object key = entry.getKey();
                Object value = entry.getValue();
                if (key instanceof String && "password".equalsIgnoreCase((String) key)) {
                    value = "<hidden>";
                }
                logger.debug("Override [" + key + "=" + value + "]");
            }
        }
        final Properties props = new SuperProperties().caseInsensitive(true);
        // weird hack but sometimes we don't want default values when we want null for instance
        if (serviceProperties == null || "false".equals(serviceProperties.getProperty(IGNORE_DEFAULT_VALUES_PROP, "false"))) {
            props.putAll(provider.getProperties());
        }
        if (serviceProperties != null) {
            props.putAll(serviceProperties);
        }
        props.putAll(overrides);
        {
            // force user properties last
            String propertiesProvider = service.getPropertiesProvider();
            if (propertiesProvider == null) {
                propertiesProvider = SystemInstance.get().getProperty(PropertiesResourceProvider.class.getName());
            }
            if (propertiesProvider != null) {
                propertiesProvider = unaliasPropertiesProvider(propertiesProvider);
                // don't trim them, user wants to handle it himself, let him do it
                final ObjectRecipe recipe = newObjectRecipe(propertiesProvider);
                recipe.setFactoryMethod("provides");
                recipe.setProperty("serviceId", service.getId());
                recipe.setProperties(props);
                // let user get all config
                recipe.setProperty("properties", props);
                final Properties p = Properties.class.cast(recipe.create());
                props.putAll(p);
            }
        }
        props.remove(IGNORE_DEFAULT_VALUES_PROP);
        final T info;
        try {
            info = infoType.newInstance();
        } catch (final Exception e) {
            throw new OpenEJBException(messages.format("configureService.cannotInstantiateClass", infoType.getName()), e);
        }
        // some jndi adjustment
        if (service.getId().startsWith("java:/")) {
            service.setId(service.getId().substring("java:/".length()));
        }
        info.service = provider.getService();
        info.types.addAll(provider.getTypes());
        info.description = provider.getDescription();
        info.displayName = provider.getDisplayName();
        info.className = provider.getClassName();
        info.factoryMethod = provider.getFactoryName();
        info.id = service.getId();
        info.properties = props;
        info.constructorArgs.addAll(parseConstructorArgs(provider));
        if (info instanceof ResourceInfo && service instanceof Resource) {
            final ResourceInfo ri = ResourceInfo.class.cast(info);
            final Resource resource = Resource.class.cast(service);
            ri.jndiName = resource.getJndi();
            ri.postConstruct = resource.getPostConstruct();
            ri.preDestroy = resource.getPreDestroy();
            ri.aliases.addAll(resource.getAliases());
            ri.dependsOn.addAll(resource.getDependsOn());
        }
        if (service.getClasspath() != null && service.getClasspath().length() > 0) {
            info.classpath = resolveClasspath(service.getClasspath());
        }
        info.classpathAPI = service.getClasspathAPI();
        specialProcessing(info);
        return info;
    } catch (final NoSuchProviderException e) {
        final String message = logger.fatal("configureService.failed", e, (null != service ? service.getId() : ""));
        throw new OpenEJBException(message + ": " + e.getMessage());
    } catch (final Throwable e) {
        final String message = logger.fatal("configureService.failed", e, (null != service ? service.getId() : ""));
        throw new OpenEJBException(message, e);
    }
}
Also used : OpenEJBException(org.apache.openejb.OpenEJBException) ResourceInfo(org.apache.openejb.assembler.classic.ResourceInfo) Resource(org.apache.openejb.config.sys.Resource) Properties(java.util.Properties) SuperProperties(org.apache.openejb.util.SuperProperties) SuperProperties(org.apache.openejb.util.SuperProperties) IOException(java.io.IOException) URISyntaxException(java.net.URISyntaxException) OpenEJBException(org.apache.openejb.OpenEJBException) MalformedURLException(java.net.MalformedURLException) Template(org.apache.openejb.api.resource.Template) ObjectRecipe(org.apache.xbean.recipe.ObjectRecipe) ServiceProvider(org.apache.openejb.config.sys.ServiceProvider) PropertiesResourceProvider(org.apache.openejb.api.resource.PropertiesResourceProvider) Map(java.util.Map) HashMap(java.util.HashMap)

Example 4 with Resource

use of org.apache.openejb.config.sys.Resource in project tomee by apache.

the class ConvertDataSourceDefinitions method toResource.

private Resource toResource(final DataSource datasource) {
    final String name = cleanUpName(datasource.getName());
    final Resource def = new Resource(name, javax.sql.DataSource.class.getName());
    def.setJndi(datasource.getName().replaceFirst("java:", ""));
    def.setType("javax.sql.DataSource");
    final Properties p = def.getProperties();
    put(p, "JtaManaged", datasource.getTransactional());
    put(p, "InitialSize", datasource.getInitialPoolSize());
    put(p, "DefaultIsolationLevel", datasource.getIsolationLevel());
    put(p, "LoginTimeout", datasource.getLoginTimeout());
    put(p, "MinEvictableIdleTimeMillis", datasource.getMaxIdleTime());
    put(p, "MaxIdle", datasource.getMaxPoolSize());
    put(p, "MinIdle", datasource.getMinPoolSize());
    put(p, "MaxStatements", datasource.getMaxStatements());
    put(p, "Password", datasource.getPassword());
    put(p, "JdbcUrl", datasource.getUrl());
    put(p, "UserName", datasource.getUser());
    put(p, "JdbcDriver", datasource.getClassName());
    put(p, "PortNumber", datasource.getPortNumber());
    put(p, "DatabaseName", datasource.getDatabaseName());
    put(p, "Description", datasource.getDescription());
    put(p, "ServerName", datasource.getServerName());
    // do we need it??
    put(p, "Definition", rawDefinition(datasource));
    put(p, AutoConfig.ORIGIN_FLAG, AutoConfig.ORIGIN_ANNOTATION);
    setProperties(datasource, p);
    // to force it to be bound in JndiEncBuilder
    put(p, "JndiName", def.getJndi());
    return def;
}
Also used : Resource(org.apache.openejb.config.sys.Resource) Properties(java.util.Properties) DataSource(org.apache.openejb.jee.DataSource)

Example 5 with Resource

use of org.apache.openejb.config.sys.Resource in project tomee by apache.

the class ConvertJMSConnectionFactoryDefinitions method toResource.

private Resource toResource(final JMSConnectionFactory factory) {
    final String name = cleanUpName(factory.getName());
    final Resource factoryResource = new Resource(name, javax.jms.ConnectionFactory.class.getName());
    factoryResource.setJndi(factory.getName().replaceFirst("java:", ""));
    factoryResource.setType(factory.getInterfaceName() != null && !factory.getInterfaceName().isEmpty() ? factory.getInterfaceName() : "javax.jms.ConnectionFactory");
    if (factory.getClassName() != null && !factory.getClassName().isEmpty()) {
        factoryResource.setClassName(factory.getClassName());
    }
    final Properties p = factoryResource.getProperties();
    put(p, AutoConfig.ORIGIN_FLAG, AutoConfig.ORIGIN_ANNOTATION);
    put(p, "JndiName", factoryResource.getJndi());
    if (factory.getResourceAdapter() != null && !factory.getResourceAdapter().isEmpty()) {
        put(p, "ResourceAdapter", factory.getResourceAdapter());
    }
    if (factory.isTransactional()) {
        put(p, "TransactionSupport", "xa");
    } else {
        put(p, "TransactionSupport", "none");
    }
    if (factory.getMaxPoolSize() != null && factory.getMaxPoolSize() > 0) {
        put(p, "PoolMaxSize", factory.getMaxPoolSize());
    }
    if (factory.getMinPoolSize() != null && factory.getMinPoolSize() > 0) {
        put(p, "PoolMinSize", factory.getMinPoolSize());
    }
    if (factory.getUser() != null && !factory.getUser().isEmpty()) {
        put(p, "UserName", factory.getUser());
    }
    if (factory.getPassword() != null && !factory.getPassword().isEmpty()) {
        put(p, "Password", factory.getUser());
    }
    if (factory.getClientId() != null && !factory.getClientId().isEmpty()) {
        put(p, "Clientid", factory.getUser());
    }
    setProperties(factory, p);
    return factoryResource;
}
Also used : JMSConnectionFactory(org.apache.openejb.jee.JMSConnectionFactory) Resource(org.apache.openejb.config.sys.Resource) Properties(java.util.Properties)

Aggregations

Resource (org.apache.openejb.config.sys.Resource)30 ResourceInfo (org.apache.openejb.assembler.classic.ResourceInfo)15 Test (org.junit.Test)12 Properties (java.util.Properties)11 ArrayList (java.util.ArrayList)7 OpenEJBException (org.apache.openejb.OpenEJBException)6 File (java.io.File)5 IOException (java.io.IOException)5 Resources (org.apache.openejb.config.sys.Resources)5 DataSource (javax.sql.DataSource)4 Container (org.apache.openejb.config.sys.Container)4 Openejb (org.apache.openejb.config.sys.Openejb)4 URL (java.net.URL)3 HashMap (java.util.HashMap)3 InitialContext (javax.naming.InitialContext)3 SecurityServiceInfo (org.apache.openejb.assembler.classic.SecurityServiceInfo)3 TransactionServiceInfo (org.apache.openejb.assembler.classic.TransactionServiceInfo)3 SuperProperties (org.apache.openejb.util.SuperProperties)3 ByteArrayInputStream (java.io.ByteArrayInputStream)2 MalformedURLException (java.net.MalformedURLException)2