Search in sources :

Example 1 with Configuration

use of org.apache.meecrowave.configuration.Configuration in project meecrowave by apache.

the class TomcatAutoInitializer method onStartup.

@Override
public void onStartup(final Set<Class<?>> c, final ServletContext ctx) {
    final Configuration builder = Configuration.class.cast(ctx.getAttribute("meecrowave.configuration"));
    if (!builder.isTomcatAutoSetup()) {
        return;
    }
    final ServletRegistration.Dynamic def = ctx.addServlet("default", DefaultServlet.class);
    def.setInitParameter("listings", "false");
    def.setInitParameter("debug", "0");
    def.setLoadOnStartup(1);
    def.addMapping("/");
    try {
        final String jsp = "org.apache.jasper.servlet.JspServlet";
        TomcatAutoInitializer.class.getClassLoader().loadClass(jsp);
        final ServletRegistration.Dynamic jspDef = ctx.addServlet("jsp", jsp);
        if (jspDef != null) {
            jspDef.setInitParameter("fork", "false");
            jspDef.setInitParameter("xpoweredBy", "false");
            jspDef.setInitParameter("development", Boolean.toString(builder.isTomcatJspDevelopment()));
            jspDef.setLoadOnStartup(3);
            jspDef.addMapping("*.jsp");
            jspDef.addMapping("*.jspx");
        }
    } catch (final NoClassDefFoundError | ClassNotFoundException e) {
    // not there, skip
    }
}
Also used : ServletRegistration(javax.servlet.ServletRegistration) Configuration(org.apache.meecrowave.configuration.Configuration)

Example 2 with Configuration

use of org.apache.meecrowave.configuration.Configuration in project meecrowave by apache.

the class Meecrowave method deployWebapp.

public Meecrowave deployWebapp(final DeploymentMeta meta) {
    if (contexts.containsKey(meta.context)) {
        throw new IllegalArgumentException("Already deployed: '" + meta.context + "'");
    }
    // always nice to see the deployment with something else than internals
    final String base = tomcat.getService().findConnectors().length > 0 ? (configuration.getActiveProtocol() + "://" + tomcat.getHost().getName() + ':' + configuration.getActivePort()) : "";
    new LogFacade(Meecrowave.class.getName()).info("--------------- " + base + meta.context);
    final OWBJarScanner scanner = new OWBJarScanner();
    final StandardContext ctx = new StandardContext() {

        @Override
        public void setApplicationEventListeners(final Object[] listeners) {
            if (listeners == null) {
                super.setApplicationEventListeners(null);
                return;
            }
            // if we don't -> no @RequestScoped in request listeners :(
            for (int i = 1; i < listeners.length; i++) {
                if (OWBAutoSetup.EagerBootListener.class.isInstance(listeners[i])) {
                    final Object first = listeners[0];
                    listeners[0] = listeners[i];
                    listeners[i] = first;
                    break;
                }
            }
            // and finally let it go after our re-ordering
            super.setApplicationEventListeners(listeners);
        }
    };
    ctx.setPath(meta.context);
    ctx.setName(meta.context);
    ctx.setJarScanner(scanner);
    ctx.setInstanceManager(new CDIInstanceManager());
    ofNullable(meta.docBase).ifPresent(d -> {
        try {
            ctx.setDocBase(meta.docBase.getCanonicalPath());
        } catch (final IOException e) {
            ctx.setDocBase(meta.docBase.getAbsolutePath());
        }
    });
    ofNullable(configuration.getTomcatFilter()).ifPresent(filter -> {
        try {
            scanner.setJarScanFilter(JarScanFilter.class.cast(Thread.currentThread().getContextClassLoader().loadClass(filter).newInstance()));
        } catch (final ClassNotFoundException | InstantiationException | IllegalAccessException e) {
            throw new IllegalArgumentException(e);
        }
    });
    final AtomicReference<Runnable> releaseSCI = new AtomicReference<>();
    final ServletContainerInitializer meecrowaveInitializer = (c, ctx1) -> {
        ctx1.setAttribute("meecrowave.configuration", getConfiguration());
        ctx1.setAttribute("meecrowave.instance", Meecrowave.this);
        new OWBAutoSetup().onStartup(c, ctx1);
        if (Cxfs.IS_PRESENT) {
            new CxfCdiAutoSetup().onStartup(c, ctx1);
        }
        new TomcatAutoInitializer().onStartup(c, ctx1);
        if (configuration.isInjectServletContainerInitializer()) {
            final Field f;
            try {
                // now cdi is on, we can inject cdi beans in ServletContainerInitializer
                f = StandardContext.class.getDeclaredField("initializers");
                if (!f.isAccessible()) {
                    f.setAccessible(true);
                }
            } catch (final Exception e) {
                throw new IllegalStateException("Bad tomcat version", e);
            }
            final List<AutoCloseable> cc;
            try {
                cc = ((Map<ServletContainerInitializer, Set<Class<?>>>) f.get(ctx)).keySet().stream().filter(i -> !i.getClass().getName().startsWith(Meecrowave.class.getName())).map(i -> {
                    try {
                        return this.inject(i);
                    } catch (final IllegalArgumentException iae) {
                        return null;
                    }
                }).filter(Objects::nonNull).collect(toList());
            } catch (final IllegalAccessException e) {
                throw new IllegalStateException("Can't read initializers", e);
            }
            releaseSCI.set(() -> cc.forEach(closeable -> {
                try {
                    closeable.close();
                } catch (final Exception e) {
                    throw new IllegalStateException(e);
                }
            }));
        }
    };
    ctx.addLifecycleListener(new MeecrowaveContextConfig(configuration, meta.docBase != null, meecrowaveInitializer, meta.redeployCallback));
    ctx.addLifecycleListener(event -> {
        switch(event.getType()) {
            case Lifecycle.BEFORE_START_EVENT:
                if (configuration.getWebSessionCookieConfig() != null) {
                    final Properties p = new Properties();
                    try {
                        p.load(new StringReader(configuration.getWebSessionCookieConfig()));
                    } catch (final IOException e) {
                        throw new IllegalArgumentException(e);
                    }
                    if (p.containsKey("domain")) {
                        ctx.setSessionCookieDomain(p.getProperty("domain"));
                    }
                    if (p.containsKey("path")) {
                        ctx.setSessionCookiePath(p.getProperty("path"));
                    }
                    if (p.containsKey("name")) {
                        ctx.setSessionCookieName(p.getProperty("name"));
                    }
                    if (p.containsKey("use-trailing-slash")) {
                        ctx.setSessionCookiePathUsesTrailingSlash(Boolean.parseBoolean(p.getProperty("use-trailing-slash")));
                    }
                    if (p.containsKey("http-only")) {
                        ctx.setUseHttpOnly(Boolean.parseBoolean(p.getProperty("http-only")));
                    }
                    if (p.containsKey("secured")) {
                        final SessionCookieConfig sessionCookieConfig = ctx.getServletContext().getSessionCookieConfig();
                        sessionCookieConfig.setSecure(Boolean.parseBoolean(p.getProperty("secured")));
                    }
                }
                break;
            case Lifecycle.AFTER_START_EVENT:
                ctx.getResources().setCachingAllowed(configuration.isWebResourceCached());
                break;
            case Lifecycle.BEFORE_INIT_EVENT:
                if (configuration.getLoginConfig() != null) {
                    ctx.setLoginConfig(configuration.getLoginConfig().build());
                }
                for (final SecurityConstaintBuilder sc : configuration.getSecurityConstraints()) {
                    ctx.addConstraint(sc.build());
                }
                if (configuration.getWebXml() != null) {
                    ctx.getServletContext().setAttribute(Globals.ALT_DD_ATTR, configuration.getWebXml());
                }
                break;
            default:
        }
    });
    // after having configured the security!!!
    ctx.addLifecycleListener(new Tomcat.FixContextListener());
    ctx.addServletContainerInitializer(meecrowaveInitializer, emptySet());
    if (configuration.isUseTomcatDefaults()) {
        ctx.setSessionTimeout(configuration.getWebSessionTimeout() != null ? configuration.getWebSessionTimeout() : 30);
        ctx.addWelcomeFile("index.html");
        ctx.addWelcomeFile("index.htm");
        Tomcat.addDefaultMimeTypeMappings(ctx);
    } else if (configuration.getWebSessionTimeout() != null) {
        ctx.setSessionTimeout(configuration.getWebSessionTimeout());
    }
    ofNullable(meta.consumer).ifPresent(c -> c.accept(ctx));
    if (configuration.isQuickSession() && ctx.getManager() == null) {
        final StandardManager manager = new StandardManager();
        manager.setSessionIdGenerator(new StandardSessionIdGenerator() {

            @Override
            protected void getRandomBytes(final byte[] bytes) {
                ThreadLocalRandom.current().nextBytes(bytes);
            }

            @Override
            public String toString() {
                return "MeecrowaveSessionIdGenerator@" + System.identityHashCode(this);
            }
        });
        ctx.setManager(manager);
    }
    if (configuration.isAntiResourceLocking() && StandardContext.class.isInstance(ctx)) {
        StandardContext.class.cast(ctx).setAntiResourceLocking(true);
    }
    configuration.getInitializers().forEach(i -> ctx.addServletContainerInitializer(i, emptySet()));
    configuration.getGlobalContextConfigurers().forEach(it -> it.accept(ctx));
    final Host host = tomcat.getHost();
    host.addChild(ctx);
    final ClassLoader classLoader = ctx.getLoader().getClassLoader();
    if (host.getState().isAvailable()) {
        fire(new StartListening(findFirstConnector(), host, ctx), classLoader);
    }
    contexts.put(meta.context, () -> {
        if (host.getState().isAvailable()) {
            fire(new StopListening(findFirstConnector(), host, ctx), classLoader);
        }
        ofNullable(releaseSCI.get()).ifPresent(Runnable::run);
        tomcat.getHost().removeChild(ctx);
    });
    return this;
}
Also used : MeecrowaveContextConfig(org.apache.meecrowave.tomcat.MeecrowaveContextConfig) ProvidedLoader(org.apache.meecrowave.tomcat.ProvidedLoader) SessionCookieConfig(javax.servlet.SessionCookieConfig) 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) ResourceFinder(org.apache.xbean.finder.ResourceFinder) Stream(java.util.stream.Stream) ConfigurableBus(org.apache.meecrowave.cxf.ConfigurableBus) JarScanFilter(org.apache.tomcat.JarScanFilter) Log4j2s(org.apache.meecrowave.logging.log4j2.Log4j2s) 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) SecurityConstraint(org.apache.tomcat.util.descriptor.web.SecurityConstraint) ThreadLocalRandom(java.util.concurrent.ThreadLocalRandom) StreamSupport(java.util.stream.StreamSupport) SSLHostConfig(org.apache.tomcat.util.net.SSLHostConfig) ManagementFactory(java.lang.management.ManagementFactory) Properties(java.util.Properties) LogFacade(org.apache.meecrowave.logging.tomcat.LogFacade) Files(java.nio.file.Files) Cxfs(org.apache.meecrowave.cxf.Cxfs) 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) StringReader(java.io.StringReader) TreeMap(java.util.TreeMap) Paths(java.nio.file.Paths) Pipeline(org.apache.catalina.Pipeline) BeanManager(javax.enterprise.inject.spi.BeanManager) URL(java.net.URL) Lifecycle(org.apache.catalina.Lifecycle) Priotities(org.apache.meecrowave.service.Priotities) 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) StandardSessionIdGenerator(org.apache.catalina.util.StandardSessionIdGenerator) ServiceLoader(java.util.ServiceLoader) Substitutor(org.apache.meecrowave.lang.Substitutor) 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) OWBAutoSetup(org.apache.meecrowave.openwebbeans.OWBAutoSetup) LoginConfig(org.apache.tomcat.util.descriptor.web.LoginConfig) SAXParserFactory(javax.xml.parsers.SAXParserFactory) Valve(org.apache.catalina.Valve) HashMap(java.util.HashMap) AtomicReference(java.util.concurrent.atomic.AtomicReference) Function(java.util.function.Function) Cipher(javax.crypto.Cipher) Option(org.apache.xbean.recipe.Option) BiPredicate(java.util.function.BiPredicate) ServletContainerInitializer(javax.servlet.ServletContainerInitializer) Log4j2Shutdown(org.apache.meecrowave.logging.log4j2.Log4j2Shutdown) Attributes(org.xml.sax.Attributes) Comparator.comparing(java.util.Comparator.comparing) ROOT(java.util.Locale.ROOT) InjectionTarget(javax.enterprise.inject.spi.InjectionTarget) CxfCdiAutoSetup(org.apache.meecrowave.cxf.CxfCdiAutoSetup) OutputStream(java.io.OutputStream) Collections.emptySet(java.util.Collections.emptySet) MalformedURLException(java.net.MalformedURLException) 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) Configuration(org.apache.meecrowave.configuration.Configuration) StandardManager(org.apache.catalina.session.StandardManager) FileInputStream(java.io.FileInputStream) Context(org.apache.catalina.Context) 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) InputStream(java.io.InputStream) Tomcat(org.apache.catalina.startup.Tomcat) Set(java.util.Set) Collectors.toSet(java.util.stream.Collectors.toSet) Collections.emptySet(java.util.Collections.emptySet) CxfCdiAutoSetup(org.apache.meecrowave.cxf.CxfCdiAutoSetup) JarScanFilter(org.apache.tomcat.JarScanFilter) Properties(java.util.Properties) OWBJarScanner(org.apache.meecrowave.tomcat.OWBJarScanner) ServletContainerInitializer(javax.servlet.ServletContainerInitializer) Field(java.lang.reflect.Field) LogFacade(org.apache.meecrowave.logging.tomcat.LogFacade) CDIInstanceManager(org.apache.meecrowave.tomcat.CDIInstanceManager) OWBAutoSetup(org.apache.meecrowave.openwebbeans.OWBAutoSetup) TomcatAutoInitializer(org.apache.meecrowave.tomcat.TomcatAutoInitializer) MeecrowaveContextConfig(org.apache.meecrowave.tomcat.MeecrowaveContextConfig) StringReader(java.io.StringReader) URLClassLoader(java.net.URLClassLoader) ArrayList(java.util.ArrayList) Collections.emptyList(java.util.Collections.emptyList) List(java.util.List) Collectors.toList(java.util.stream.Collectors.toList) SessionCookieConfig(javax.servlet.SessionCookieConfig) StartListening(org.apache.meecrowave.api.StartListening) StandardManager(org.apache.catalina.session.StandardManager) AtomicReference(java.util.concurrent.atomic.AtomicReference) Host(org.apache.catalina.Host) StandardHost(org.apache.catalina.core.StandardHost) StopListening(org.apache.meecrowave.api.StopListening) IOException(java.io.IOException) SecurityConstraint(org.apache.tomcat.util.descriptor.web.SecurityConstraint) LifecycleException(org.apache.catalina.LifecycleException) IOException(java.io.IOException) SAXException(org.xml.sax.SAXException) MalformedURLException(java.net.MalformedURLException) StandardSessionIdGenerator(org.apache.catalina.util.StandardSessionIdGenerator) StandardContext(org.apache.catalina.core.StandardContext)

Example 3 with Configuration

use of org.apache.meecrowave.configuration.Configuration in project meecrowave by apache.

the class MeecrowaveConfiguration method toMeecrowaveConfiguration.

Configuration toMeecrowaveConfiguration() {
    final Meecrowave.Builder builder = new Meecrowave.Builder();
    for (final Field field : MeecrowaveConfiguration.class.getDeclaredFields()) {
        final String name = field.getName();
        if ("users".equals(name) || "roles".equals(name) || "cxfServletParams".equals(name) || "loginConfig".equals(name) || "securityConstraints".equals(name) || "realm".equals(name)) {
            // specific syntax
            continue;
        }
        try {
            final Field configField = Configuration.class.getDeclaredField(field.getName());
            if (!configField.getType().equals(field.getType())) {
                continue;
            }
            if (!field.isAccessible()) {
                field.setAccessible(true);
            }
            final Object value = field.get(this);
            if (value != null) {
                if (!configField.isAccessible()) {
                    configField.setAccessible(true);
                }
                configField.set(builder, value);
            }
        } catch (final NoSuchFieldException nsfe) {
        // ignored
        } catch (final Exception e) {
            throw new IllegalStateException(e);
        }
    }
    if (httpPort < 0) {
        builder.randomHttpPort();
    }
    // for Map use properties
    if (users != null) {
        final Properties properties = new Properties() {

            {
                try {
                    load(new ByteArrayInputStream(users.getBytes(StandardCharsets.UTF_8)));
                } catch (final IOException e) {
                    throw new IllegalStateException(e);
                }
            }
        };
        builder.setUsers(properties.stringPropertyNames().stream().collect(toMap(identity(), properties::getProperty)));
    }
    if (roles != null) {
        final Properties properties = new Properties() {

            {
                try {
                    load(new ByteArrayInputStream(roles.getBytes(StandardCharsets.UTF_8)));
                } catch (final IOException e) {
                    throw new IllegalStateException(e);
                }
            }
        };
        builder.setRoles(properties.stringPropertyNames().stream().collect(toMap(identity(), properties::getProperty)));
    }
    if (cxfServletParams != null) {
        final Properties properties = new Properties() {

            {
                try {
                    load(new ByteArrayInputStream(cxfServletParams.getBytes(StandardCharsets.UTF_8)));
                } catch (final IOException e) {
                    throw new IllegalStateException(e);
                }
            }
        };
        builder.setCxfServletParams(properties.stringPropertyNames().stream().collect(toMap(identity(), properties::getProperty)));
    }
    // for other not simple type use the Cli syntax
    final ClassLoader loader = Thread.currentThread().getContextClassLoader();
    if (realm != null) {
        try {
            int end = realm.indexOf(':');
            if (end < 0) {
                builder.setRealm(Realm.class.cast(loader.loadClass(realm).newInstance()));
            } else {
                final ObjectRecipe recipe = new ObjectRecipe(realm.substring(0, end));
                Stream.of(realm.substring(end + 1, realm.length()).split(";")).map(v -> v.split("=")).forEach(v -> recipe.setProperty(v[0], v[1]));
                builder.setRealm(Realm.class.cast(recipe.create(loader)));
            }
        } catch (final Exception cnfe) {
            throw new IllegalArgumentException(realm);
        }
    }
    if (securityConstraints != null) {
        builder.setSecurityConstraints(Stream.of(securityConstraints.split("|")).map(item -> {
            try {
                final ObjectRecipe recipe = new ObjectRecipe(Meecrowave.SecurityConstaintBuilder.class);
                Stream.of(item.split(";")).map(v -> v.split("=")).forEach(v -> recipe.setProperty(v[0], v[1]));
                return Meecrowave.SecurityConstaintBuilder.class.cast(recipe.create(loader));
            } catch (final Exception cnfe) {
                throw new IllegalArgumentException(securityConstraints);
            }
        }).collect(toList()));
    }
    if (loginConfig != null) {
        try {
            final ObjectRecipe recipe = new ObjectRecipe(Meecrowave.LoginConfigBuilder.class);
            Stream.of(loginConfig.split(";")).map(v -> v.split("=")).forEach(v -> recipe.setProperty(v[0], v[1]));
            builder.setLoginConfig(Meecrowave.LoginConfigBuilder.class.cast(recipe.create(loader)));
        } catch (final Exception cnfe) {
            throw new IllegalArgumentException(loginConfig);
        }
    }
    return builder;
}
Also used : Properties(java.util.Properties) ContainerConfiguration(org.jboss.arquillian.container.spi.client.container.ContainerConfiguration) Configuration(org.apache.meecrowave.configuration.Configuration) IOException(java.io.IOException) ConfigurationException(org.jboss.arquillian.container.spi.ConfigurationException) Field(java.lang.reflect.Field) File(java.io.File) StandardCharsets(java.nio.charset.StandardCharsets) ObjectRecipe(org.apache.xbean.recipe.ObjectRecipe) Collectors.toList(java.util.stream.Collectors.toList) Stream(java.util.stream.Stream) Collectors.toMap(java.util.stream.Collectors.toMap) ByteArrayInputStream(java.io.ByteArrayInputStream) Realm(org.apache.catalina.Realm) Function.identity(java.util.function.Function.identity) Multiline(org.jboss.arquillian.config.descriptor.api.Multiline) Meecrowave(org.apache.meecrowave.Meecrowave) IOException(java.io.IOException) Properties(java.util.Properties) IOException(java.io.IOException) ConfigurationException(org.jboss.arquillian.container.spi.ConfigurationException) Field(java.lang.reflect.Field) ObjectRecipe(org.apache.xbean.recipe.ObjectRecipe) ByteArrayInputStream(java.io.ByteArrayInputStream) Realm(org.apache.catalina.Realm) Meecrowave(org.apache.meecrowave.Meecrowave)

Example 4 with Configuration

use of org.apache.meecrowave.configuration.Configuration in project meecrowave by apache.

the class ConfigurableBus method initProviders.

public void initProviders(final Configuration builder, final ClassLoader loader) {
    final List<Object> providers = ofNullable(builder.getJaxrsDefaultProviders()).map(s -> Stream.of(s.split(" *, *")).map(String::trim).filter(p -> !p.isEmpty()).map(name -> {
        try {
            return Thread.currentThread().getContextClassLoader().loadClass(name).newInstance();
        } catch (InstantiationException | IllegalAccessException | ClassNotFoundException e) {
            throw new IllegalArgumentException(name + " can't be created");
        }
    }).collect(Collectors.<Object>toList())).orElseGet(() -> {
        // ensure both providers share the same memory reuse logic
        final JsonProvider provider = JsonProvider.provider();
        final JsonReaderFactory readerFactory = provider.createReaderFactory(new HashMap<String, Object>() {

            {
                put(JsonParserFactoryImpl.SUPPORTS_COMMENTS, builder.isJsonpSupportsComment());
                Optional.of(builder.getJsonpMaxStringLen()).filter(v -> v > 0).ifPresent(s -> put(JsonParserFactoryImpl.MAX_STRING_LENGTH, s));
                Optional.of(builder.getJsonpMaxReadBufferLen()).filter(v -> v > 0).ifPresent(s -> put(JsonParserFactoryImpl.BUFFER_LENGTH, s));
                ofNullable(builder.getJsonpBufferStrategy()).ifPresent(s -> put(AbstractJsonFactory.BUFFER_STRATEGY, s));
            }
        });
        final JsonWriterFactory writerFactory = provider.createWriterFactory(new HashMap<String, Object>() {

            {
                put(JsonGenerator.PRETTY_PRINTING, builder.isJsonpPrettify());
                Optional.of(builder.getJsonpMaxWriteBufferLen()).filter(v -> v > 0).ifPresent(v -> put(JsonGeneratorFactoryImpl.GENERATOR_BUFFER_LENGTH, v));
                ofNullable(builder.getJsonpBufferStrategy()).ifPresent(s -> put(AbstractJsonFactory.BUFFER_STRATEGY, s));
            }
        });
        return Stream.<Object>of(new ConfiguredJsonbJaxrsProvider(builder.getJsonbEncoding(), builder.isJsonbNulls(), builder.isJsonbIJson(), builder.isJsonbPrettify(), builder.getJsonbBinaryStrategy(), builder.getJsonbNamingStrategy(), builder.getJsonbOrderStrategy(), new DelegateJsonProvider(provider, readerFactory, writerFactory))).collect(toList());
    });
    if (builder.isJaxrsAutoActivateBeanValidation()) {
        try {
            // we don't need the jaxrsbeanvalidationfeature since bean validation cdi extension handles it normally
            loader.loadClass("javax.validation.Validation");
            final Object instance = loader.loadClass("org.apache.cxf.jaxrs.validation.ValidationExceptionMapper").getConstructor().newInstance();
            // validate bval can be used, check NoClassDefFoundError javax.validation.ValidationException
            instance.getClass().getGenericInterfaces();
            providers.add(instance);
        } catch (final Exception | NoClassDefFoundError e) {
        // no-op
        }
    }
    // client
    if (getProperty("org.apache.cxf.jaxrs.bus.providers") == null) {
        setProperty("skip.default.json.provider.registration", "true");
        setProperty("org.apache.cxf.jaxrs.bus.providers", providers);
    }
}
Also used : JsonReaderFactory(javax.json.JsonReaderFactory) JsonWriterFactory(javax.json.JsonWriterFactory) Produces(javax.ws.rs.Produces) Provider(javax.ws.rs.ext.Provider) JsonParserFactoryImpl(org.apache.johnzon.core.JsonParserFactoryImpl) JsonBuilderFactory(javax.json.JsonBuilderFactory) Collections.singletonList(java.util.Collections.singletonList) JsonProvider(javax.json.spi.JsonProvider) JsonValue(javax.json.JsonValue) BigDecimal(java.math.BigDecimal) JsonStructure(javax.json.JsonStructure) MediaType(javax.ws.rs.core.MediaType) JsonNumber(javax.json.JsonNumber) Consumes(javax.ws.rs.Consumes) Map(java.util.Map) BigInteger(java.math.BigInteger) ClientLifeCycleManagerImpl(org.apache.cxf.bus.managers.ClientLifeCycleManagerImpl) JsonObject(javax.json.JsonObject) JsonbBuilder(javax.json.bind.JsonbBuilder) Collection(java.util.Collection) JsonGeneratorFactory(javax.json.stream.JsonGeneratorFactory) Reader(java.io.Reader) AbstractJsonFactory(org.apache.johnzon.core.AbstractJsonFactory) Collectors(java.util.stream.Collectors) List(java.util.List) Stream(java.util.stream.Stream) Type(java.lang.reflect.Type) Writer(java.io.Writer) Annotation(java.lang.annotation.Annotation) Optional(java.util.Optional) JsonObjectBuilder(javax.json.JsonObjectBuilder) JsonGenerator(javax.json.stream.JsonGenerator) JsonArrayBuilder(javax.json.JsonArrayBuilder) JsonPatch(javax.json.JsonPatch) ClientLifeCycleManager(org.apache.cxf.endpoint.ClientLifeCycleManager) HashMap(java.util.HashMap) JsonParserFactory(javax.json.stream.JsonParserFactory) ExtensionManagerBus(org.apache.cxf.bus.extension.ExtensionManagerBus) JsonbJaxrsProvider(org.apache.johnzon.jaxrs.jsonb.jaxrs.JsonbJaxrsProvider) OutputStream(java.io.OutputStream) JsonParser(javax.json.stream.JsonParser) JsonReader(javax.json.JsonReader) Optional.ofNullable(java.util.Optional.ofNullable) JsonArray(javax.json.JsonArray) JsonMergePatch(javax.json.JsonMergePatch) Configuration(org.apache.meecrowave.configuration.Configuration) JsonGeneratorFactoryImpl(org.apache.johnzon.core.JsonGeneratorFactoryImpl) JsonString(javax.json.JsonString) Collectors.toList(java.util.stream.Collectors.toList) JsonPatchBuilder(javax.json.JsonPatchBuilder) JsonWriter(javax.json.JsonWriter) Jsonb(javax.json.bind.Jsonb) JsonPointer(javax.json.JsonPointer) InputStream(java.io.InputStream) JsonString(javax.json.JsonString) JsonProvider(javax.json.spi.JsonProvider) JsonObject(javax.json.JsonObject) JsonWriterFactory(javax.json.JsonWriterFactory) JsonReaderFactory(javax.json.JsonReaderFactory)

Example 5 with Configuration

use of org.apache.meecrowave.configuration.Configuration in project meecrowave by apache.

the class MeecrowaveRunMojo method getConfig.

private Configuration getConfig() {
    final Configuration config = new Configuration();
    for (final Field field : MeecrowaveRunMojo.class.getDeclaredFields()) {
        if ("properties".equals(field.getName())) {
            continue;
        }
        try {
            final Field configField = Configuration.class.getDeclaredField(field.getName());
            field.setAccessible(true);
            configField.setAccessible(true);
            final Object value = field.get(this);
            if (value != null) {
                configField.set(config, value);
                getLog().debug("using " + field.getName() + " = " + value);
            }
        } catch (final NoSuchFieldException nsfe) {
        // ignored
        } catch (final Exception e) {
            getLog().warn("can't initialize attribute " + field.getName());
        }
    }
    config.loadFrom(meecrowaveProperties);
    if (properties != null) {
        config.getProperties().putAll(properties);
    }
    return config;
}
Also used : Field(java.lang.reflect.Field) Configuration(org.apache.meecrowave.configuration.Configuration) ScriptException(javax.script.ScriptException) MalformedURLException(java.net.MalformedURLException) IOException(java.io.IOException)

Aggregations

Configuration (org.apache.meecrowave.configuration.Configuration)12 IOException (java.io.IOException)8 Field (java.lang.reflect.Field)5 Collection (java.util.Collection)5 Map (java.util.Map)5 Optional.ofNullable (java.util.Optional.ofNullable)5 Collectors.toList (java.util.stream.Collectors.toList)5 Stream (java.util.stream.Stream)5 File (java.io.File)4 InputStream (java.io.InputStream)4 MalformedURLException (java.net.MalformedURLException)4 URL (java.net.URL)4 StandardCharsets (java.nio.charset.StandardCharsets)4 HashMap (java.util.HashMap)4 List (java.util.List)4 OutputStream (java.io.OutputStream)3 StringReader (java.io.StringReader)3 Writer (java.io.Writer)3 URLClassLoader (java.net.URLClassLoader)3 ArrayList (java.util.ArrayList)3