Repository: kumuluz/kumuluzee Branch: master Commit: 1157fc14be71 Files: 261 Total size: 774.1 KB Directory structure: gitextract_kh8ins4r/ ├── .github/ │ └── workflows/ │ └── kumuluzee-ci.yml ├── .gitignore ├── CONTRIBUTING.md ├── LICENSE ├── README.md ├── bom/ │ └── pom.xml ├── common/ │ ├── pom.xml │ └── src/ │ ├── main/ │ │ ├── java/ │ │ │ └── com/ │ │ │ └── kumuluz/ │ │ │ └── ee/ │ │ │ ├── common/ │ │ │ │ ├── Component.java │ │ │ │ ├── ConfigExtension.java │ │ │ │ ├── Extension.java │ │ │ │ ├── KumuluzServer.java │ │ │ │ ├── LogsExtension.java │ │ │ │ ├── ServletServer.java │ │ │ │ ├── attributes/ │ │ │ │ │ └── ClasspathAttributes.java │ │ │ │ ├── config/ │ │ │ │ │ ├── DataSourceConfig.java │ │ │ │ │ ├── DataSourcePoolConfig.java │ │ │ │ │ ├── DevConfig.java │ │ │ │ │ ├── EeConfig.java │ │ │ │ │ ├── EnvConfig.java │ │ │ │ │ ├── GzipConfig.java │ │ │ │ │ ├── MailServiceConfig.java │ │ │ │ │ ├── MailSessionConfig.java │ │ │ │ │ ├── ServerConfig.java │ │ │ │ │ ├── ServerConnectorConfig.java │ │ │ │ │ └── XaDataSourceConfig.java │ │ │ │ ├── datasources/ │ │ │ │ │ ├── NonJtaXAConnectionWrapper.java │ │ │ │ │ ├── NonJtaXADataSourceWrapper.java │ │ │ │ │ ├── XADataSourceBuilder.java │ │ │ │ │ └── XADataSourceWrapper.java │ │ │ │ ├── dependencies/ │ │ │ │ │ ├── EeComponentDef.java │ │ │ │ │ ├── EeComponentDependencies.java │ │ │ │ │ ├── EeComponentDependency.java │ │ │ │ │ ├── EeComponentOptional.java │ │ │ │ │ ├── EeComponentOptionals.java │ │ │ │ │ ├── EeComponentType.java │ │ │ │ │ ├── EeExtensionDef.java │ │ │ │ │ ├── EeExtensionGroup.java │ │ │ │ │ └── ServerDef.java │ │ │ │ ├── exceptions/ │ │ │ │ │ ├── ComponentsException.java │ │ │ │ │ └── KumuluzServerException.java │ │ │ │ ├── filters/ │ │ │ │ │ └── PoweredByFilter.java │ │ │ │ ├── runtime/ │ │ │ │ │ ├── EeRuntime.java │ │ │ │ │ ├── EeRuntimeComponent.java │ │ │ │ │ ├── EeRuntimeExtension.java │ │ │ │ │ └── EeRuntimeInternal.java │ │ │ │ ├── servlet/ │ │ │ │ │ └── ServletWrapper.java │ │ │ │ ├── utils/ │ │ │ │ │ ├── ClassUtils.java │ │ │ │ │ ├── EnvUtils.java │ │ │ │ │ ├── ResourceUtils.java │ │ │ │ │ └── StringUtils.java │ │ │ │ └── wrapper/ │ │ │ │ ├── ComponentWrapper.java │ │ │ │ ├── EeComponentWrapper.java │ │ │ │ ├── ExtensionWrapper.java │ │ │ │ └── KumuluzServerWrapper.java │ │ │ ├── configuration/ │ │ │ │ ├── ConfigurationDecoder.java │ │ │ │ ├── ConfigurationListener.java │ │ │ │ ├── ConfigurationSource.java │ │ │ │ ├── enums/ │ │ │ │ │ └── ConfigurationValueType.java │ │ │ │ ├── sources/ │ │ │ │ │ ├── EnvironmentConfigurationSource.java │ │ │ │ │ ├── FileConfigurationSource.java │ │ │ │ │ └── SystemPropertyConfigurationSource.java │ │ │ │ └── utils/ │ │ │ │ ├── ConfigurationDecoderUtils.java │ │ │ │ ├── ConfigurationDispatcher.java │ │ │ │ ├── ConfigurationImpl.java │ │ │ │ ├── ConfigurationInterpolationUtil.java │ │ │ │ ├── ConfigurationSourceUtils.java │ │ │ │ └── ConfigurationUtil.java │ │ │ └── logs/ │ │ │ ├── LogDeferrer.java │ │ │ └── impl/ │ │ │ ├── JavaUtilConsoleHandler.java │ │ │ ├── JavaUtilDefaultLogConfigurator.java │ │ │ └── JavaUtilFormatter.java │ │ └── resources/ │ │ └── META-INF/ │ │ ├── kumuluzee/ │ │ │ └── versions.properties │ │ └── services/ │ │ └── com.kumuluz.ee.configuration.ConfigurationSource │ └── test/ │ └── java/ │ └── com/ │ └── kumuluz/ │ └── ee/ │ └── configuration/ │ └── utils/ │ └── ConfigurationInterpolationUtilTest.java ├── components/ │ ├── bean-validation/ │ │ ├── hibernate-validator/ │ │ │ ├── pom.xml │ │ │ └── src/ │ │ │ ├── main/ │ │ │ │ ├── java/ │ │ │ │ │ └── com/ │ │ │ │ │ └── kumuluz/ │ │ │ │ │ └── ee/ │ │ │ │ │ └── beanvalidation/ │ │ │ │ │ └── BeanValidationComponent.java │ │ │ │ └── resources/ │ │ │ │ └── META-INF/ │ │ │ │ └── services/ │ │ │ │ └── com.kumuluz.ee.common.Component │ │ │ └── test/ │ │ │ └── java/ │ │ │ └── com/ │ │ │ └── kumuluz/ │ │ │ └── ee/ │ │ │ └── beanvalidation/ │ │ │ └── test/ │ │ │ ├── HibernateValidatorTest.java │ │ │ └── beans/ │ │ │ ├── Project.java │ │ │ └── User.java │ │ └── pom.xml │ ├── cdi/ │ │ ├── pom.xml │ │ └── weld/ │ │ ├── pom.xml │ │ └── src/ │ │ └── main/ │ │ ├── java/ │ │ │ └── com/ │ │ │ └── kumuluz/ │ │ │ └── ee/ │ │ │ ├── cdi/ │ │ │ │ └── CdiComponent.java │ │ │ ├── configuration/ │ │ │ │ └── cdi/ │ │ │ │ ├── ConfigBundle.java │ │ │ │ ├── ConfigValue.java │ │ │ │ ├── interceptors/ │ │ │ │ │ └── ConfigBundleInterceptor.java │ │ │ │ └── producers/ │ │ │ │ ├── ConfigurationUtilProducer.java │ │ │ │ └── EeConfigProducer.java │ │ │ └── runtime/ │ │ │ └── cdi/ │ │ │ └── producers/ │ │ │ └── EeRuntimeProducer.java │ │ └── resources/ │ │ └── META-INF/ │ │ ├── beans.xml │ │ └── services/ │ │ └── com.kumuluz.ee.common.Component │ ├── el/ │ │ ├── pom.xml │ │ └── uel/ │ │ ├── pom.xml │ │ └── src/ │ │ └── main/ │ │ ├── java/ │ │ │ └── com/ │ │ │ └── kumuluz/ │ │ │ └── ee/ │ │ │ └── el/ │ │ │ └── ElComponent.java │ │ └── resources/ │ │ └── META-INF/ │ │ └── services/ │ │ └── com.kumuluz.ee.common.Component │ ├── javamail/ │ │ ├── pom.xml │ │ └── ri/ │ │ ├── pom.xml │ │ └── src/ │ │ └── main/ │ │ ├── java/ │ │ │ └── com/ │ │ │ └── kumuluz/ │ │ │ └── ee/ │ │ │ └── javamail/ │ │ │ └── ri/ │ │ │ ├── JavaMailComponent.java │ │ │ ├── MailSessionFactory.java │ │ │ └── ManagedPasswordAuthenticator.java │ │ └── resources/ │ │ └── META-INF/ │ │ └── services/ │ │ └── com.kumuluz.ee.common.Component │ ├── jax-rs/ │ │ ├── jersey/ │ │ │ ├── pom.xml │ │ │ └── src/ │ │ │ └── main/ │ │ │ ├── java/ │ │ │ │ ├── com/ │ │ │ │ │ └── kumuluz/ │ │ │ │ │ └── ee/ │ │ │ │ │ └── jaxrs/ │ │ │ │ │ ├── JaxRsComponent.java │ │ │ │ │ └── Jetty10ConnectorProvider.java │ │ │ │ └── org/ │ │ │ │ └── glassfish/ │ │ │ │ └── jersey/ │ │ │ │ └── jetty/ │ │ │ │ └── connector/ │ │ │ │ └── Jetty10Connector.java │ │ │ └── resources/ │ │ │ └── META-INF/ │ │ │ └── services/ │ │ │ ├── com.kumuluz.ee.common.Component │ │ │ └── org.glassfish.jersey.client.spi.ConnectorProvider │ │ └── pom.xml │ ├── jax-ws/ │ │ ├── cxf/ │ │ │ ├── pom.xml │ │ │ └── src/ │ │ │ ├── main/ │ │ │ │ ├── java/ │ │ │ │ │ └── com/ │ │ │ │ │ └── kumuluz/ │ │ │ │ │ └── ee/ │ │ │ │ │ └── jaxws/ │ │ │ │ │ └── cxf/ │ │ │ │ │ ├── JaxWsComponent.java │ │ │ │ │ ├── KumuluzCXFServlet.java │ │ │ │ │ ├── annotations/ │ │ │ │ │ │ └── WsContext.java │ │ │ │ │ ├── processor/ │ │ │ │ │ │ ├── AnnotationProcessorUtil.java │ │ │ │ │ │ ├── JaxWsAnnotationProcessor.java │ │ │ │ │ │ └── JaxWsAnnotationProcessorUtil.java │ │ │ │ │ └── ws/ │ │ │ │ │ ├── CXFWebservicePublisher.java │ │ │ │ │ ├── Endpoint.java │ │ │ │ │ ├── InjectionHelper.java │ │ │ │ │ ├── KumuluzWSInvoker.java │ │ │ │ │ └── KumuluzWebServiceContext.java │ │ │ │ └── resources/ │ │ │ │ └── META-INF/ │ │ │ │ └── services/ │ │ │ │ ├── com.kumuluz.ee.common.Component │ │ │ │ └── javax.annotation.processing.Processor │ │ │ └── test/ │ │ │ ├── java/ │ │ │ │ └── com/ │ │ │ │ └── kumuluz/ │ │ │ │ └── ee/ │ │ │ │ └── jaxws/ │ │ │ │ └── cxf/ │ │ │ │ ├── impl/ │ │ │ │ │ ├── NoWsContextAnnotatedEndpointBean.java │ │ │ │ │ ├── WebServiceContextBean.java │ │ │ │ │ ├── WsContextAnnotatedEndpoint.java │ │ │ │ │ └── WsContextAnnotatedEndpointBean.java │ │ │ │ ├── processor/ │ │ │ │ │ └── JaxWsAnnotationProcessorUtilTest.java │ │ │ │ └── ws/ │ │ │ │ └── KumuluzWebServiceContextTest.java │ │ │ └── resources/ │ │ │ └── META-INF/ │ │ │ └── ws/ │ │ │ └── java.lang.Object │ │ ├── metro/ │ │ │ ├── pom.xml │ │ │ └── src/ │ │ │ └── main/ │ │ │ ├── java/ │ │ │ │ └── com/ │ │ │ │ └── kumuluz/ │ │ │ │ └── ee/ │ │ │ │ └── jaxws/ │ │ │ │ └── metro/ │ │ │ │ └── JaxWsComponent.java │ │ │ └── resources/ │ │ │ └── META-INF/ │ │ │ └── services/ │ │ │ └── com.kumuluz.ee.common.Component │ │ └── pom.xml │ ├── jpa/ │ │ ├── common/ │ │ │ ├── pom.xml │ │ │ └── src/ │ │ │ └── main/ │ │ │ ├── java/ │ │ │ │ └── com/ │ │ │ │ └── kumuluz/ │ │ │ │ └── ee/ │ │ │ │ └── jpa/ │ │ │ │ └── common/ │ │ │ │ ├── PersistenceSettings.java │ │ │ │ ├── PersistenceUnitHolder.java │ │ │ │ ├── PersistenceWrapper.java │ │ │ │ ├── TransactionType.java │ │ │ │ ├── exceptions/ │ │ │ │ │ └── NoDefaultPersistenceUnit.java │ │ │ │ ├── injection/ │ │ │ │ │ ├── EntityManagerWrapper.java │ │ │ │ │ ├── JpaService.java │ │ │ │ │ ├── NonTxEntityManagerWrapper.java │ │ │ │ │ ├── PersistenceContextResource.java │ │ │ │ │ ├── PersistenceContextResourceFactory.java │ │ │ │ │ ├── PersistenceUnitResource.java │ │ │ │ │ └── PersistenceUnitResourceFactory.java │ │ │ │ ├── jta/ │ │ │ │ │ ├── NonTxEntityManagerHolder.java │ │ │ │ │ ├── NonTxQueryWrapper.java │ │ │ │ │ ├── NonTxStoredProcedureQueryWrapper.java │ │ │ │ │ ├── NonTxTypedQueryWrapper.java │ │ │ │ │ ├── SyncEntityManagerWrapper.java │ │ │ │ │ ├── TxScopedEntityManager.java │ │ │ │ │ ├── TxScopedEntityManagerFactory.java │ │ │ │ │ ├── TxScopedEntityManagerWrapper.java │ │ │ │ │ └── TxSynchronization.java │ │ │ │ └── utils/ │ │ │ │ └── PersistenceUtils.java │ │ │ └── resources/ │ │ │ └── META-INF/ │ │ │ └── services/ │ │ │ └── org.jboss.weld.bootstrap.api.Service │ │ ├── eclipselink/ │ │ │ ├── pom.xml │ │ │ └── src/ │ │ │ └── main/ │ │ │ ├── java/ │ │ │ │ └── com/ │ │ │ │ └── kumuluz/ │ │ │ │ └── ee/ │ │ │ │ └── jpa/ │ │ │ │ └── eclipselink/ │ │ │ │ ├── EclipseLinkSettings.java │ │ │ │ ├── JpaComponent.java │ │ │ │ ├── KumuluzPlatform.java │ │ │ │ └── KumuluzTransactionController.java │ │ │ └── resources/ │ │ │ └── META-INF/ │ │ │ └── services/ │ │ │ └── com.kumuluz.ee.common.Component │ │ ├── hibernate/ │ │ │ ├── pom.xml │ │ │ └── src/ │ │ │ └── main/ │ │ │ ├── java/ │ │ │ │ └── com/ │ │ │ │ └── kumuluz/ │ │ │ │ └── ee/ │ │ │ │ └── jpa/ │ │ │ │ └── hibernate/ │ │ │ │ └── JpaComponent.java │ │ │ └── resources/ │ │ │ └── META-INF/ │ │ │ └── services/ │ │ │ └── com.kumuluz.ee.common.Component │ │ └── pom.xml │ ├── jsf/ │ │ ├── mojarra/ │ │ │ ├── pom.xml │ │ │ └── src/ │ │ │ └── main/ │ │ │ ├── java/ │ │ │ │ └── com/ │ │ │ │ └── kumuluz/ │ │ │ │ └── ee/ │ │ │ │ └── jsf/ │ │ │ │ └── mojarra/ │ │ │ │ └── JsfComponent.java │ │ │ └── resources/ │ │ │ └── META-INF/ │ │ │ └── services/ │ │ │ └── com.kumuluz.ee.common.Component │ │ └── pom.xml │ ├── json-b/ │ │ ├── pom.xml │ │ └── yasson/ │ │ ├── pom.xml │ │ └── src/ │ │ └── main/ │ │ ├── java/ │ │ │ └── com/ │ │ │ └── kumuluz/ │ │ │ └── ee/ │ │ │ └── jsonb/ │ │ │ └── yasson/ │ │ │ └── JsonBComponent.java │ │ └── resources/ │ │ └── META-INF/ │ │ └── services/ │ │ └── com.kumuluz.ee.common.Component │ ├── json-p/ │ │ ├── jsonp/ │ │ │ ├── pom.xml │ │ │ └── src/ │ │ │ └── main/ │ │ │ ├── java/ │ │ │ │ └── com/ │ │ │ │ └── kumuluz/ │ │ │ │ └── ee/ │ │ │ │ └── jsonp/ │ │ │ │ ├── JsonPComponent.java │ │ │ │ └── configuration/ │ │ │ │ └── utils/ │ │ │ │ └── JsonConfigurationUtil.java │ │ │ └── resources/ │ │ │ └── META-INF/ │ │ │ └── services/ │ │ │ └── com.kumuluz.ee.common.Component │ │ └── pom.xml │ ├── jsp/ │ │ ├── jetty/ │ │ │ ├── pom.xml │ │ │ └── src/ │ │ │ ├── main/ │ │ │ │ ├── java/ │ │ │ │ │ └── com/ │ │ │ │ │ └── kumuluz/ │ │ │ │ │ └── ee/ │ │ │ │ │ └── jsp/ │ │ │ │ │ └── JspComponent.java │ │ │ │ └── resources/ │ │ │ │ └── META-INF/ │ │ │ │ └── services/ │ │ │ │ └── com.kumuluz.ee.common.Component │ │ │ └── test/ │ │ │ ├── java/ │ │ │ │ └── com/ │ │ │ │ └── kumuluz/ │ │ │ │ └── ee/ │ │ │ │ └── jetty/ │ │ │ │ └── jsp/ │ │ │ │ └── test/ │ │ │ │ ├── JspTest.java │ │ │ │ └── beans/ │ │ │ │ ├── TimeBean.java │ │ │ │ └── UserBean.java │ │ │ └── resources/ │ │ │ └── webapp/ │ │ │ └── index.jsp │ │ └── pom.xml │ ├── jta/ │ │ ├── common/ │ │ │ ├── pom.xml │ │ │ └── src/ │ │ │ └── main/ │ │ │ ├── java/ │ │ │ │ └── com/ │ │ │ │ └── kumuluz/ │ │ │ │ └── ee/ │ │ │ │ └── jta/ │ │ │ │ └── common/ │ │ │ │ ├── JtaProvider.java │ │ │ │ ├── JtaTransactionServices.java │ │ │ │ ├── datasources/ │ │ │ │ │ ├── JtaXAConnectionWrapper.java │ │ │ │ │ ├── JtaXADataSourceWrapper.java │ │ │ │ │ └── XAStatementProxy.java │ │ │ │ ├── exceptions/ │ │ │ │ │ └── CannotRetrieveTxException.java │ │ │ │ └── utils/ │ │ │ │ └── TxUtils.java │ │ │ └── resources/ │ │ │ └── META-INF/ │ │ │ └── services/ │ │ │ └── org.jboss.weld.bootstrap.api.Service │ │ ├── narayana/ │ │ │ ├── pom.xml │ │ │ └── src/ │ │ │ └── main/ │ │ │ ├── java/ │ │ │ │ └── com/ │ │ │ │ └── kumuluz/ │ │ │ │ └── ee/ │ │ │ │ └── jta/ │ │ │ │ └── narayana/ │ │ │ │ ├── JtaComponent.java │ │ │ │ └── NarayanaJtaProvider.java │ │ │ └── resources/ │ │ │ └── META-INF/ │ │ │ └── services/ │ │ │ ├── com.kumuluz.ee.common.Component │ │ │ └── com.kumuluz.ee.jta.common.JtaProvider │ │ └── pom.xml │ ├── pom.xml │ └── websocket/ │ ├── jetty/ │ │ ├── pom.xml │ │ └── src/ │ │ └── main/ │ │ ├── java/ │ │ │ └── com/ │ │ │ └── kumuluz/ │ │ │ └── ee/ │ │ │ └── websocket/ │ │ │ └── jetty/ │ │ │ └── WebSocketComponent.java │ │ └── resources/ │ │ └── META-INF/ │ │ └── services/ │ │ └── com.kumuluz.ee.common.Component │ └── pom.xml ├── core/ │ ├── pom.xml │ └── src/ │ ├── main/ │ │ └── java/ │ │ └── com/ │ │ └── kumuluz/ │ │ └── ee/ │ │ ├── EeApplication.java │ │ ├── factories/ │ │ │ ├── AgroalDataSourceFactory.java │ │ │ ├── EeConfigFactory.java │ │ │ └── JtaXADataSourceFactory.java │ │ └── loaders/ │ │ ├── ComponentLoader.java │ │ ├── ConfigExtensionLoader.java │ │ ├── ExtensionLoader.java │ │ ├── LogsExtensionLoader.java │ │ └── ServerLoader.java │ └── test/ │ └── java/ │ └── com/ │ └── kumuluz/ │ └── ee/ │ └── test/ │ └── ExampleTest.java ├── pom.xml ├── profiles/ │ ├── micro-profile/ │ │ └── pom.xml │ ├── micro-profile-1.0/ │ │ └── pom.xml │ ├── micro-profile-1.1/ │ │ └── pom.xml │ ├── micro-profile-1.2/ │ │ └── pom.xml │ ├── micro-profile-1.3/ │ │ └── pom.xml │ ├── micro-profile-1.4/ │ │ └── pom.xml │ ├── micro-profile-2.0/ │ │ └── pom.xml │ ├── micro-profile-2.1/ │ │ └── pom.xml │ ├── micro-profile-2.2/ │ │ └── pom.xml │ ├── micro-profile-3.0/ │ │ └── pom.xml │ ├── micro-profile-3.1/ │ │ └── pom.xml │ ├── micro-profile-3.2/ │ │ └── pom.xml │ ├── micro-profile-3.3/ │ │ └── pom.xml │ └── pom.xml ├── servlet/ │ ├── jetty/ │ │ ├── pom.xml │ │ └── src/ │ │ └── main/ │ │ ├── java/ │ │ │ └── com/ │ │ │ └── kumuluz/ │ │ │ └── ee/ │ │ │ └── jetty/ │ │ │ ├── JettyAttributes.java │ │ │ ├── JettyFactory.java │ │ │ ├── JettyJarClasspathUtil.java │ │ │ └── JettyServletServer.java │ │ └── resources/ │ │ └── META-INF/ │ │ └── services/ │ │ └── com.kumuluz.ee.common.KumuluzServer │ └── pom.xml ├── settings.xml └── tools/ ├── loader/ │ ├── pom.xml │ └── src/ │ └── main/ │ └── java/ │ └── com/ │ └── kumuluz/ │ └── ee/ │ └── loader/ │ ├── EeBootLoader.java │ ├── EeClassLoader.java │ ├── exception/ │ │ └── EeClassLoaderException.java │ └── jar/ │ ├── FileInfo.java │ ├── JarEntryInfo.java │ └── JarFileInfo.java ├── maven-plugin/ │ ├── README.md │ ├── pom.xml │ └── src/ │ └── main/ │ ├── java/ │ │ └── com/ │ │ └── kumuluz/ │ │ └── ee/ │ │ └── maven/ │ │ └── plugin/ │ │ ├── AbstractCopyDependenciesMojo.java │ │ ├── AbstractPackageMojo.java │ │ ├── CopyDependenciesMojo.java │ │ ├── MojoConstants.java │ │ ├── RepackageMojo.java │ │ ├── RunExplodedMojo.java │ │ └── RunJarMojo.java │ └── resources/ │ └── META-INF/ │ └── kumuluzee/ │ └── plugin-versions.properties └── pom.xml ================================================ FILE CONTENTS ================================================ ================================================ FILE: .github/workflows/kumuluzee-ci.yml ================================================ name: KumuluzEE CI on: [push, pull_request] jobs: test: name: Build and test runs-on: 'ubuntu-latest' strategy: matrix: java-version: ['11', '17', '18'] steps: - name: Checkout code uses: actions/checkout@v2 - name: Set up JDK ${{ matrix.java-version }} uses: actions/setup-java@v1 with: java-version: ${{ matrix.java-version }} - name: Cache Maven packages uses: actions/cache@v2 with: path: ~/.m2 key: ${{ runner.os }}-m2-${{ hashFiles('**/pom.xml') }} restore-keys: ${{ runner.os }}-m2 - name: Install run: mvn --show-version --update-snapshots --batch-mode clean install -DskipTests=true - name: Test run: mvn --batch-mode test publish: name: Publish to OSSRH runs-on: 'ubuntu-latest' needs: test if: github.ref == 'refs/heads/master' || startsWith(github.ref, 'refs/tags/v') steps: - name: Checkout code uses: actions/checkout@v2 - name: Set up JDK 11 uses: actions/setup-java@v1 with: java-version: 11 - name: Restore cache uses: actions/cache@v2 with: path: ~/.m2 key: ${{ runner.os }}-m2-${{ hashFiles('**/pom.xml') }} restore-keys: ${{ runner.os }}-m2 - name: Restore GPG keys env: GPG_KEY: ${{ secrets.OSSRH_GPG_KEY }} GPG_PUB: ${{ secrets.OSSRH_GPG_PUB }} run: 'printf "$GPG_KEY" | base64 --decode > "$GITHUB_WORKSPACE/gpg.key" && printf "$GPG_PUB" | base64 --decode > "$GITHUB_WORKSPACE/gpg.pub" && gpg --batch --import "$GITHUB_WORKSPACE/gpg.pub" "$GITHUB_WORKSPACE/gpg.key"' - name: Publish to OSSRH env: OSSRH_USERNAME: Kumuluz OSSRH_PASSWORD: ${{ secrets.OSSRH_PASSWORD }} GPG_PASSPHRASE: ${{ secrets.OSSRH_GPG_PASSPHRASE }} run: mvn --batch-mode source:jar javadoc:jar deploy -Pdeploy -DskipTests=true --settings ./settings.xml; ================================================ FILE: CONTRIBUTING.md ================================================ # Contributing to KumuluzEE ♥ [KumuluzEE](https://github.com/kumuluz/KumuluzEE) and want to get involved? Thanks! There are plenty of ways you can help! ## Bugs A bug is a _demonstrable problem_ that is caused by the code in the repository. Good bug reports are extremely helpful - thank you! Guidelines for bug reports: 1. **Use the GitHub issue search** — check if the issue has already been reported. 2. **Check if the issue has been fixed** — try to reproduce it using the latest `master` branch in the repository. 3. **Isolate the problem** — ideally create a [reduced test case](http://css-tricks.com/6263-reduced-test-cases/) and a live example. A good bug report shouldn't leave others needing to chase you up for more information. Please try to be as detailed as possible in your report. What is your environment? What steps will reproduce the issue? What OS versions experience the problem? What would you expect to be the outcome? All these details will help people to fix any potential bugs. Example: > Short and descriptive example bug report title > > A summary of the issue and the OS environment in which it occurs. If > suitable, include the steps required to reproduce the bug. > > 1. This is the first step > 2. This is the second step > 3. Further steps, etc. > > `` (a link to the reduced test case) > > Any other information you want to share that is relevant to the issue being > reported. This might include the lines of code that you have identified as > causing the bug, and potential solutions (and your opinions on their > merits). **[File a bug report](https://github.com/kumuluz/KumuluzEE/issues/)** ## Pull requests Good pull requests - patches, improvements, new features - are a fantastic help. They should remain focused in scope and avoid containing unrelated commits. If your contribution involves a significant amount of work or substantial changes to any part of the project, please open an issue to discuss it first. Make sure to adhere to the coding conventions used throughout a project (indentation, accurate comments, etc.). Please update any documentation that is relevant to the change you're making. Please follow this process; it's the best way to get your work included in the project: 1. [Fork](http://help.github.com/fork-a-repo/) the project, clone your fork, and configure the remotes: ```bash # Clones your fork of the repo into the current directory in terminal git clone https://github.com//KumuluzEE.git # Navigate to the newly cloned directory cd KumuluzEE # Assigns the original repo to a remote called "upstream" git remote add upstream https://github.com/kumuluz/KumuluzEE.git ``` 2. If you cloned a while ago, get the latest changes from upstream: ```bash git checkout master git pull upstream master ``` 3. Create a new topic branch to contain your feature, change, or fix: ```bash git checkout -b ``` 4. Commit your changes in logical chunks. Please adhere to these [git commit message guidelines](http://tbaggery.com/2008/04/19/a-note-about-git-commit-messages.html) or your pull request is unlikely be merged into the main project. Use git's [interactive rebase](https://help.github.com/articles/interactive-rebase) feature to tidy up your commits before making them public. 5. Locally merge (or rebase) the upstream development branch into your topic branch: ```bash git pull [--rebase] upstream master ``` 6. Push your topic branch up to your fork: ```bash git push origin ``` 10. [Open a Pull Request](https://help.github.com/articles/using-pull-requests) with a clear title and description. ## Do not… Please **do not** use the issue tracker for personal support requests. Please **do not** derail or troll issues. Keep the discussion on topic and respect the opinions of others. ================================================ FILE: LICENSE ================================================ The MIT License (MIT) Copyright (c) 2015 Sunesis d.o.o. and Tilen Faganel Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ================================================ FILE: README.md ================================================ # KumuluzEE ![KumuluzEE CI](https://github.com/kumuluz/kumuluzee/workflows/KumuluzEE%20CI/badge.svg) > Lightweight open-source framework for developing microservices using standard Java/JakartaEE technologies, extending them with Node.js, Go and other languages, and migrating to cloud-native architecture. KumuluzEE is a lightweight framework for developing microservices using standard Java/JakartaEE technologies, extending them with Node.js, Go and other languages, and migrating existing applications to microservices and cloud-native architecture. KumuluzEE packages microservices as standalone JARs. KumuluzEE microservices are lightweight and optimized for size and start-up time. They fit perfectly with Docker containers. KumuluzEE microservices are fully compatible with Kubernetes and enable Kubernetes-native development. KumuluzEE will also provide support for Serverless Functions on Azure, AWS and Google. KumuluzEE also provides extensions for developing common patterns in cloud-native architectures, including configuration, logging, discovery, fault tolerance with circuit-breakers, metrics, security, event streaming and more. KumuluzEE has been designed to use the standard Java/JakartaEE technologies and APIs with optional extensions for easier development of cloud-native microservices. Therefore, it is particularly suitable for existing enterprise Java developers, who would like to leverage their skills, but progressively move from monolithic to microservice design patterns. KumuluzEE provides full support for **Java** latest versions (check each release for specific information). In addition to Java, KumuluzEE supports several programming languages, including **Node.js** and **Go**. Support for additional languages will be added soon. For these languages, KumuluzEE also provides support for service configuration and discovery. KumuluzEE is Eclipse MicroProfile compliant and provides support for MicroProfile 1.0, 1.1, 1.2, 1.3, 1.4, 2.0, 2.1, 3.0, 3.1, 3.2 and 3.3. Support for 4.x and 5.x is coming soon. KumuluzEE provides support for all MicroProfile specifications, including MicroProfile Config, MicroProfile Health, MicroProfile Fault Tolerance, MicroProfile Metrics, MicroProfile JWT Authentication, MicroProfile Rest Client, MicroProfile OpenAPI and MicroProfile Open Tracing APIs. ## Getting started If you already know how to use Java/JakartaEE, then you already know how to use KumuluzEE. It is simple and straightforward. See the [getting started](https://github.com/kumuluz/KumuluzEE/wiki/Getting-started) wiki section to create your first light-weight standalone Java microservice in 5 minutes. Read [tutorials](https://ee.kumuluz.com/tutorials/) at our home page. Refer to [samples](https://github.com/kumuluz/kumuluzee-samples) for more examples. ## Features Primary features: - Lightweight, cloud-native Java microservices with full support for Docker, Kubernetes and Serverless (coming soon). - Support for all major cloud-native patterns, minimal footprint, quick start-up time, perfect for scaling in the cloud. - No need for a traditional application server. Run your app anywhere Java runs as well as in PaaS and Docker-like environments. - Allows you to develop microservices using standard Java technologies and extend them with Node.js, Go and other languages. - Allows you to gradually migrate existing Java applications to microservices and cloud-native architecture. - Complete control over what Java/JakartaEE components and its implementations are included. Only include what you need and make your app lightweight. - Minimal to no configuration settings up the base server. Develop like any other Java application. - Quick startup time, low resource consumption and stateless scalability accelerates development. - Extend your microservices with common cloud-native patterns, such as config, discovery, logging, fault tolerance, circuit-breakers, etc. KumuluzEE provides all the building blocks. KumuluzEE provides support for various Java/JakartaEE APIs and components. The goal is to support as many Java components as possible (contributions welcome). ## Java/JavaEE/JakartaEE components Currently the following components are supported with more being added over time: - Servlet (Jetty) - CDI (RI Weld) - JAX-RS (RI Jersey) - JSON-P (RI JSONP) - JSON-B (RI Yasson) - JSP (Jetty Apache Jasper) - JPA (RI EclipseLink) - JPA (RI Hibernate) - EL (RI UEL) - JAX-WS (RI Metro) - JAX-WS (Apache CXF) - JSF (RI Mojarra) - WebSocket (Jetty) - Bean Validation (RI Hibernate validator) - JTA (Narayana) - Java Mail (RI JavaMail) Please check each specific KumuluzEE version for specific versions of these components. ## Additional features KumuluzEE provides additional features, which are described on the [project Wiki]( https://github.com/kumuluz/kumuluzee/wiki), particularly: - [Configuration framework](https://github.com/kumuluz/kumuluzee/wiki/Configuration) for easy and efficient configuration of microservices from various sources, such as environment variables, configuration files (yaml), properties, etc. - [TLS/SSL support](https://github.com/kumuluz/kumuluzee/wiki/TLS-SSL-support) for configuring TLS/SSL, including support for **HTTP/2**. KumuluzEE also provides support for [**Uber JARs**](https://github.com/kumuluz/kumuluzee/wiki/Uber-JAR-support). With the KumuluzEE Maven plugin, you can pack and run each microservice as a single, self-contained Uber-JAR. Details are described later in this document. ## KumuluzEE projects In addition to the standard Java EE components, KumuluzEE also comes with several projects that complement and extend its functionality. The projects follow the same modular concept as the Java components in which you can chose if you want to use it as well as the underlying implementation of the project. Most projects are geared towards creating cloud-native microservices including configuration, logging, discovery, fault tolerance including circuit-breakers, metrics, security, event streaming and more. Projects also extend KumuluzEE with technologies, such as Ethereum for blockchain microservices, gRPC, GraphQL, and others. The following projects are available with more planned soon: - [KumuluzEE Config](https://github.com/kumuluz/kumuluzee/wiki/Configuration) (File and environment variables) - [KumuluzEE Config with config server](https://github.com/kumuluz/kumuluzee-config) (Config server etcd/Consul) - [KumuluzEE REST](https://github.com/kumuluz/kumuluzee-rest) (For implementation of common, advanced and flexible REST API functionalities and patterns. Includes support for exposing JPA entities through REST) - [KumuluzEE Logs](https://github.com/kumuluz/kumuluzee-logs) (For advanced microservice framework for logging) - [KumuluzEE Discovery](https://github.com/kumuluz/kumuluzee-discovery) (For dynamic service discovery (etcd or Consul). Fully compatible with Kubernetes) - [KumuluzEE Metrics](https://github.com/kumuluz/kumuluzee-metrics) (For easy collection and reporting of performance metrics) - [KumuluzEE Security](https://github.com/kumuluz/kumuluzee-security) (For easy integration with OAuth2/OpenID identity and access management providers) - [KumuluzEE Health](https://github.com/kumuluz/kumuluzee-health) (For implementing health checks and exposing microservice health information) - [KumuluzEE Fault Tolerance](https://github.com/kumuluz/kumuluzee-fault-tolerance) (For implementing fault tolerance patterns with microservices including circuit breakers and decoupling microservices) - [KumuluzEE Event Streaming](https://github.com/kumuluz/kumuluzee-streaming) (For event streaming support using Apache Kafka) - [KumuluzEE Reactive](https://github.com/kumuluz/kumuluzee-reactive) (For developing reactive microservices and integration with reactive streams (Vert.x and similar)) - [KumuluzEE CORS](https://github.com/kumuluz/kumuluzee-cors) (For Cross-Origin Resource Sharing (CORS) support) - [KumuluzEE Swagger](https://github.com/kumuluz/kumuluzee-swagger) (For Swagger (OpenAPI 2) support and visualization) - [KumuluzEE OpenAPI](https://github.com/kumuluz/kumuluzee-openapi) (For OpenAPI 3 support, interface generation and visualization) - [KumuluzEE Testing](https://github.com/kumuluz/kumuluzee-testing) (Tools and utilities for testing KumuluzEE microservices) - [KumuluzEE gRPC](https://github.com/kumuluz/kumuluzee-grpc) (Native support for gRPC based services) - [KumuluzEE GraphQL](https://github.com/kumuluz/kumuluzee-graphql) (Native support for GraphQL) - [KumuluzEE Ethereum](https://github.com/kumuluz/kumuluzee-ethereum) (For Ethereum-enabled blockchain microservices) - [KumuluzEE AMQP](https://github.com/kumuluz/kumuluzee-amqp) (Support for Advanced Message Queueing Protocol) - [KumuluzEE Feature Flags](https://github.com/kumuluz/kumuluzee-feature-flags) (Support for development with feature flags.) - [KumuluzEE JCache](https://github.com/kumuluz/kumuluzee-jcache) (Support for caching using JCache annotations.) - [KumuluzEE Version](https://github.com/kumuluz/kumuluzee-version) (Support for exposing version details of microservice.) ## MicroProfile KumuluzEE is Eclipse MicroProfile compliant and provides support for: - MicroProfile 1.0 - MicroProfile 1.1 - MicroProfile 1.2 - MicroProfile 1.3 - MicroProfile 1.4 - MicroProfile 2.0 - MicroProfile 2.1 - MicroProfile 3.0 - MicroProfile 3.1 - MicroProfile 3.2 - MicroProfile 3.3 It implements the following MicroProfile APIs: - [MicroProfile Config](https://github.com/kumuluz/kumuluzee-config-mp) - [MicroProfile Health Check](https://github.com/kumuluz/kumuluzee-health) - [MicroProfile Fault Tolerance](https://github.com/kumuluz/kumuluzee-fault-tolerance) - [MicroProfile Metrics](https://github.com/kumuluz/kumuluzee-metrics) - [MicroProfile JWT Authentication](https://github.com/kumuluz/kumuluzee-jwt-auth) - [MicroProfile Rest Client](https://github.com/kumuluz/kumuluzee-rest-client) - [MicroProfile OpenAPI](https://github.com/kumuluz/kumuluzee-openapi-mp) - [MicroProfile Open Tracing](https://github.com/kumuluz/kumuluzee-opentracing) ## Usage KumuluzEE ships with a BOM (bill of materials) which you can use to easily add the various components you need without worrying about the versions and their compatibility as it is required that all components are the same version. Using maven add the BOM module of the library as a dependency to your project. The `${kumuluzee.version}` variables represents the most current minor version. You can see the available version on the [Release Page](https://github.com/kumuluz/KumuluzEE/releases). ```xml com.kumuluz.ee kumuluzee-bom ${kumuluzee.version} pom import ``` Now you can choose either any single combinations of Java components or use one of the common pre-built profiles that ship as part of KumuluzEE. You can chose any of the following profiles: MicroProfile 1.0 ```xml com.kumuluz.ee kumuluzee-microProfile-1.0 ``` MicroProfile 1.1 ```xml com.kumuluz.ee kumuluzee-microProfile-1.1 ``` MicroProfile 1.2 ```xml com.kumuluz.ee kumuluzee-microProfile-1.2 ``` MicroProfile 1.3 ```xml com.kumuluz.ee kumuluzee-microProfile-1.3 ``` MicroProfile 1.4 ```xml com.kumuluz.ee kumuluzee-microProfile-1.4 ``` MicroProfile 2.0 ```xml com.kumuluz.ee kumuluzee-microProfile-2.0 ``` MicroProfile 2.1 ```xml com.kumuluz.ee kumuluzee-microProfile-2.1 ``` MicroProfile 3.0 ```xml com.kumuluz.ee kumuluzee-microProfile-3.0 ``` MicroProfile 3.1 ```xml com.kumuluz.ee kumuluzee-microProfile-3.1 ``` MicroProfile 3.2 ```xml com.kumuluz.ee kumuluzee-microProfile-3.2 ``` MicroProfile 3.3 ```xml com.kumuluz.ee kumuluzee-microProfile-3.3 ``` To choose your Java components with fine grain control include them as your dependencies. You can chose any of the following artifacts: ```xml com.kumuluz.ee kumuluzee-servlet-jetty com.kumuluz.ee kumuluzee-websocket-jetty com.kumuluz.ee kumuluzee-jsp-jetty com.kumuluz.ee kumuluzee-el-uel com.kumuluz.ee kumuluzee-cdi-weld com.kumuluz.ee kumuluzee-jpa-eclipselink com.kumuluz.ee kumuluzee-jpa-hibernate com.kumuluz.ee kumuluzee-jax-rs-jersey com.kumuluz.ee kumuluzee-jax-ws-metro com.kumuluz.ee kumuluzee-jax-ws-cxf com.kumuluz.ee kumuluzee-jsf-mojarra com.kumuluz.ee kumuluzee-bean-validation-hibernate-validator com.kumuluz.ee kumuluzee-json-p-jsonp com.kumuluz.ee kumuluzee-json-b-yasson com.kumuluz.ee kumuluzee-jta-narayana com.kumuluz.ee kumuluzee-javamail-ri ``` To choose your KumuluzEE project, you simply include it as your dependency. You can find the available implementations and options at their respected project pages. ## Pack and run microservice as Uber JAR KumuluzEE (version 2.4 and higher) provides support for packing and running microservices as Uber JARs. It also includes a Maven plugin that correctly packages the microservice. To package a Kumuluz EE microservice into an Uber JAR, you need to add the following plugin declaration into your REST module pom.xml: ```xml com.kumuluz.ee kumuluzee-maven-plugin ${kumuluzee.version} package repackage ``` #### Parameters * __finalName__ Final name of the generated "uber" JAR. __Default value is__: `${project.build.finalName}` or `${project.artifactId}-${project.version}` * __outputDirectory__ Directory containing the generated JAR. __Default value is__: `${project.build.directory}` ### Run Start the application using the following command: ```cmd java -jar ${project.build.finalName}.jar ``` Example: ```cmd java -jar my-app-1.0.0-SNAPSHOT.jar ``` ## Getting started You can find the getting started guide on the projects [wiki](https://github.com/kumuluz/KumuluzEE/wiki/Getting-started). You can find samples [for Java EE and KumuluzEE]( https://github.com/kumuluz/kumuluzee-samples) ## Building Ensure you have JDK 8 (or newer), Maven 3.2.1 (or newer) and Git installed ```bash java -version mvn -version git --version ``` First clone the KumuluzEE repository: ```bash git clone https://github.com/kumuluz/KumuluzEE.git cd KumuluzEE ``` To build KumuluzEE run: ```bash mvn clean package ``` This will build all modules and run the testsuite. Once completed you will find the build archives in the modules respected `target` folder. ## Changelog Recent changes can be viewed on Github on the [Releases Page](https://github.com/kumuluz/KumuluzEE/releases) ## Contribute See the [contributing docs](https://github.com/kumuluz/KumuluzEE/blob/master/CONTRIBUTING.md) When submitting an issue, please follow the [guidelines](https://github.com/kumuluz/KumuluzEE/blob/master/CONTRIBUTING.md#bugs). When submitting a bugfix, write a test that exposes the bug and fails before applying your fix. Submit the test alongside the fix. When submitting a new feature, add tests that cover the feature. ## License MIT ================================================ FILE: bom/pom.xml ================================================ kumuluzee com.kumuluz.ee 4.2.0-SNAPSHOT 4.0.0 pom KumuluzEE BOM Bill of materials for all the KumuluzEE components kumuluzee-bom com.kumuluz.ee kumuluzee-micro-profile ${project.version} com.kumuluz.ee kumuluzee-microProfile-1.0 ${project.version} com.kumuluz.ee kumuluzee-microProfile-1.1 ${project.version} com.kumuluz.ee kumuluzee-microProfile-1.2 ${project.version} com.kumuluz.ee kumuluzee-microProfile-1.3 ${project.version} com.kumuluz.ee kumuluzee-microProfile-1.4 ${project.version} com.kumuluz.ee kumuluzee-microProfile-2.0 ${project.version} com.kumuluz.ee kumuluzee-microProfile-2.1 ${project.version} com.kumuluz.ee kumuluzee-microProfile-2.2 ${project.version} com.kumuluz.ee kumuluzee-microProfile-3.0 ${project.version} com.kumuluz.ee kumuluzee-microProfile-3.1 ${project.version} com.kumuluz.ee kumuluzee-microProfile-3.2 ${project.version} com.kumuluz.ee kumuluzee-microProfile-3.3 ${project.version} com.kumuluz.ee kumuluzee-core ${project.version} com.kumuluz.ee kumuluzee-servlet-jetty ${project.version} com.kumuluz.ee kumuluzee-jsp-jetty ${project.version} com.kumuluz.ee kumuluzee-el-uel ${project.version} com.kumuluz.ee kumuluzee-cdi-weld ${project.version} com.kumuluz.ee kumuluzee-jpa-eclipselink ${project.version} com.kumuluz.ee kumuluzee-jpa-hibernate ${project.version} com.kumuluz.ee kumuluzee-jax-rs-jersey ${project.version} com.kumuluz.ee kumuluzee-jax-ws-metro ${project.version} com.kumuluz.ee kumuluzee-jax-ws-cxf ${project.version} com.kumuluz.ee kumuluzee-jsf-mojarra ${project.version} com.kumuluz.ee kumuluzee-websocket-jetty ${project.version} com.kumuluz.ee kumuluzee-bean-validation-hibernate-validator ${project.version} com.kumuluz.ee kumuluzee-json-p-jsonp ${project.version} com.kumuluz.ee kumuluzee-json-b-yasson ${project.version} com.kumuluz.ee kumuluzee-jta-narayana ${project.version} com.kumuluz.ee kumuluzee-javamail-ri ${project.version} ================================================ FILE: common/pom.xml ================================================ kumuluzee com.kumuluz.ee 4.2.0-SNAPSHOT 4.0.0 KumuluzEE Common KumuluzEE common utilities, configs, exceptions and Java EE component interfaces kumuluzee-common jakarta.annotation jakarta.annotation-api jakarta.servlet jakarta.servlet-api jakarta.transaction jakarta.transaction-api io.agroal agroal-api io.agroal agroal-hikari ${agroal.version} io.agroal agroal-pool ${agroal.version} org.yaml snakeyaml junit junit test src/main/resources true ================================================ FILE: common/src/main/java/com/kumuluz/ee/common/Component.java ================================================ /* * Copyright (c) 2014-2017 Kumuluz and/or its affiliates * and other contributors as indicated by the @author tags and * the contributor list. * * Licensed under the MIT License (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://opensource.org/licenses/MIT * * The software is provided "AS IS", WITHOUT WARRANTY OF ANY KIND, express or * implied, including but not limited to the warranties of merchantability, * fitness for a particular purpose and noninfringement. in no event shall the * authors or copyright holders be liable for any claim, damages or other * liability, whether in an action of contract, tort or otherwise, arising from, * out of or in connection with the software or the use or other dealings in the * software. See the License for the specific language governing permissions and * limitations under the License. */ package com.kumuluz.ee.common; import com.kumuluz.ee.common.config.EeConfig; import com.kumuluz.ee.common.wrapper.KumuluzServerWrapper; /** * @author Tilen Faganel * @since 1.0.0 */ public interface Component { void init(KumuluzServerWrapper server, EeConfig eeConfig); void load(); } ================================================ FILE: common/src/main/java/com/kumuluz/ee/common/ConfigExtension.java ================================================ /* * Copyright (c) 2014-2017 Kumuluz and/or its affiliates * and other contributors as indicated by the @author tags and * the contributor list. * * Licensed under the MIT License (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://opensource.org/licenses/MIT * * The software is provided "AS IS", WITHOUT WARRANTY OF ANY KIND, express or * implied, including but not limited to the warranties of merchantability, * fitness for a particular purpose and noninfringement. in no event shall the * authors or copyright holders be liable for any claim, damages or other * liability, whether in an action of contract, tort or otherwise, arising from, * out of or in connection with the software or the use or other dealings in the * software. See the License for the specific language governing permissions and * limitations under the License. */ package com.kumuluz.ee.common; import com.kumuluz.ee.configuration.ConfigurationSource; import java.util.Collections; import java.util.List; /** * @author Tilen Faganel * @since 2.3.0 */ public interface ConfigExtension extends Extension { /** * @deprecated Use {@link #getConfigurationSources()} instead. */ @Deprecated default ConfigurationSource getConfigurationSource() { return null; } default List getConfigurationSources() { return Collections.emptyList(); } } ================================================ FILE: common/src/main/java/com/kumuluz/ee/common/Extension.java ================================================ /* * Copyright (c) 2014-2017 Kumuluz and/or its affiliates * and other contributors as indicated by the @author tags and * the contributor list. * * Licensed under the MIT License (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://opensource.org/licenses/MIT * * The software is provided "AS IS", WITHOUT WARRANTY OF ANY KIND, express or * implied, including but not limited to the warranties of merchantability, * fitness for a particular purpose and noninfringement. in no event shall the * authors or copyright holders be liable for any claim, damages or other * liability, whether in an action of contract, tort or otherwise, arising from, * out of or in connection with the software or the use or other dealings in the * software. See the License for the specific language governing permissions and * limitations under the License. */ package com.kumuluz.ee.common; import com.kumuluz.ee.common.config.EeConfig; import com.kumuluz.ee.common.wrapper.KumuluzServerWrapper; import java.util.Collections; import java.util.List; /** * @author Tilen Faganel * @since 2.3.0 */ public interface Extension { void load(); void init(KumuluzServerWrapper server, EeConfig eeConfig); default boolean isEnabled() { return true; } default List scanLibraries() { return Collections.emptyList(); } } ================================================ FILE: common/src/main/java/com/kumuluz/ee/common/KumuluzServer.java ================================================ /* * Copyright (c) 2014-2017 Kumuluz and/or its affiliates * and other contributors as indicated by the @author tags and * the contributor list. * * Licensed under the MIT License (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://opensource.org/licenses/MIT * * The software is provided "AS IS", WITHOUT WARRANTY OF ANY KIND, express or * implied, including but not limited to the warranties of merchantability, * fitness for a particular purpose and noninfringement. in no event shall the * authors or copyright holders be liable for any claim, damages or other * liability, whether in an action of contract, tort or otherwise, arising from, * out of or in connection with the software or the use or other dealings in the * software. See the License for the specific language governing permissions and * limitations under the License. */ package com.kumuluz.ee.common; import com.kumuluz.ee.common.config.ServerConfig; import java.util.EventListener; import java.util.Map; import javax.servlet.Servlet; /** * @author Tilen Faganel * @since 1.0.0 */ public interface KumuluzServer { void initServer(); void startServer(); void stopServer(); void setServerConfig(ServerConfig serverConfig); ServerConfig getServerConfig(); } ================================================ FILE: common/src/main/java/com/kumuluz/ee/common/LogsExtension.java ================================================ /* * Copyright (c) 2014-2017 Kumuluz and/or its affiliates * and other contributors as indicated by the @author tags and * the contributor list. * * Licensed under the MIT License (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://opensource.org/licenses/MIT * * The software is provided "AS IS", WITHOUT WARRANTY OF ANY KIND, express or * implied, including but not limited to the warranties of merchantability, * fitness for a particular purpose and noninfringement. in no event shall the * authors or copyright holders be liable for any claim, damages or other * liability, whether in an action of contract, tort or otherwise, arising from, * out of or in connection with the software or the use or other dealings in the * software. See the License for the specific language governing permissions and * limitations under the License. */ package com.kumuluz.ee.common; import java.util.Optional; import java.util.logging.Handler; import java.util.logging.LogManager; /** * @author Tilen Faganel * @since 2.4.0 */ public interface LogsExtension extends Extension { Optional> getJavaUtilLogManagerClass(); Optional getJavaUtilLogHandler(); } ================================================ FILE: common/src/main/java/com/kumuluz/ee/common/ServletServer.java ================================================ /* * Copyright (c) 2014-2017 Kumuluz and/or its affiliates * and other contributors as indicated by the @author tags and * the contributor list. * * Licensed under the MIT License (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://opensource.org/licenses/MIT * * The software is provided "AS IS", WITHOUT WARRANTY OF ANY KIND, express or * implied, including but not limited to the warranties of merchantability, * fitness for a particular purpose and noninfringement. in no event shall the * authors or copyright holders be liable for any claim, damages or other * liability, whether in an action of contract, tort or otherwise, arising from, * out of or in connection with the software or the use or other dealings in the * software. See the License for the specific language governing permissions and * limitations under the License. */ package com.kumuluz.ee.common; import com.kumuluz.ee.common.servlet.ServletWrapper; import javax.servlet.DispatcherType; import javax.servlet.Filter; import javax.servlet.Servlet; import javax.sql.DataSource; import javax.transaction.UserTransaction; import java.util.*; /** * @author Tilen Faganel * @since 1.0.0 */ public interface ServletServer extends KumuluzServer { void registerServlet(Class servletClass, String mapping); void registerServlet(Class servletClass, String mapping, Map parameters); void registerServlet(Class servletClass, String mapping, Map parameters, int initOrder); void registerListener(EventListener listener); void registerFilter(Class filterClass, String pathSpec); void registerFilter(Class filterClass, String pathSpec, Map parameters); void registerFilter(Class filterClass, String pathSpec, EnumSet dispatches); void registerFilter(Class filterClass, String pathSpec, EnumSet dispatches, Map parameters); void registerResource(Object o, String jndiName); void registerDataSource(DataSource ds, String jndiName); void registerTransactionManager(UserTransaction userTransaction); void initWebContext(List scanLibraries); List getRegisteredServlets(); } ================================================ FILE: common/src/main/java/com/kumuluz/ee/common/attributes/ClasspathAttributes.java ================================================ /* * Copyright (c) 2014-2017 Kumuluz and/or its affiliates * and other contributors as indicated by the @author tags and * the contributor list. * * Licensed under the MIT License (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://opensource.org/licenses/MIT * * The software is provided "AS IS", WITHOUT WARRANTY OF ANY KIND, express or * implied, including but not limited to the warranties of merchantability, * fitness for a particular purpose and noninfringement. in no event shall the * authors or copyright holders be liable for any claim, damages or other * liability, whether in an action of contract, tort or otherwise, arising from, * out of or in connection with the software or the use or other dealings in the * software. See the License for the specific language governing permissions and * limitations under the License. */ package com.kumuluz.ee.common.attributes; /** * @author Tilen Faganel * @since 1.0.0 */ public class ClasspathAttributes { public static final String jar = "^((?!lib\\_[^\\/]*\\.jar\\.[^\\/]*\\.tmp|/lib\\_[^\\/]*\\.jar\\.[^\\/]*\\.tmp|.*\\/jre\\/lib\\/.*).)*$"; public static final String exploded = "^.*/classes/.*$"; public static final String exploded_test = ".*/test-classes/.*"; } ================================================ FILE: common/src/main/java/com/kumuluz/ee/common/config/DataSourceConfig.java ================================================ /* * Copyright (c) 2014-2017 Kumuluz and/or its affiliates * and other contributors as indicated by the @author tags and * the contributor list. * * Licensed under the MIT License (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://opensource.org/licenses/MIT * * The software is provided "AS IS", WITHOUT WARRANTY OF ANY KIND, express or * implied, including but not limited to the warranties of merchantability, * fitness for a particular purpose and noninfringement. in no event shall the * authors or copyright holders be liable for any claim, damages or other * liability, whether in an action of contract, tort or otherwise, arising from, * out of or in connection with the software or the use or other dealings in the * software. See the License for the specific language governing permissions and * limitations under the License. */ package com.kumuluz.ee.common.config; import java.util.Collections; import java.util.HashMap; import java.util.Map; /** * @author Tilen Faganel * @since 2.1.0 */ public class DataSourceConfig { public static class Builder { private String jndiName; private String driverClass; private String dataSourceClass; private String connectionUrl; private String username; private String password; private DataSourcePoolConfig.Builder pool = new DataSourcePoolConfig.Builder(); private Map props = new HashMap<>(); public Builder jndiName(String jndiName) { this.jndiName = jndiName; return this; } public Builder driverClass(String driverClass) { this.driverClass = driverClass; return this; } public Builder dataSourceClass(String dataSourceClass) { this.dataSourceClass = dataSourceClass; return this; } public Builder connectionUrl(String connectionUrl) { this.connectionUrl = connectionUrl; return this; } public Builder username(String username) { this.username = username; return this; } public Builder password(String password) { this.password = password; return this; } public Builder pool(DataSourcePoolConfig.Builder pool) { this.pool = pool; return this; } public Builder prop(String key, String value) { this.props.put(key, value); return this; } public DataSourceConfig build() { DataSourceConfig dataSourceConfig = new DataSourceConfig(); dataSourceConfig.jndiName = jndiName; dataSourceConfig.driverClass = driverClass; dataSourceConfig.dataSourceClass = dataSourceClass; dataSourceConfig.connectionUrl = connectionUrl; dataSourceConfig.username = username; dataSourceConfig.password = password; dataSourceConfig.pool = pool.build(); dataSourceConfig.props = Collections.unmodifiableMap(props); return dataSourceConfig; } } private String jndiName; private String driverClass; private String dataSourceClass; private String connectionUrl; private String username; private String password; private DataSourcePoolConfig pool; private Map props; private DataSourceConfig() { } public String getJndiName() { return jndiName; } public String getDriverClass() { return driverClass; } public String getDataSourceClass() { return dataSourceClass; } public String getConnectionUrl() { return connectionUrl; } public String getUsername() { return username; } public String getPassword() { return password; } public DataSourcePoolConfig getPool() { return pool; } public Map getProps() { return props; } } ================================================ FILE: common/src/main/java/com/kumuluz/ee/common/config/DataSourcePoolConfig.java ================================================ /* * Copyright (c) 2014-2017 Kumuluz and/or its affiliates * and other contributors as indicated by the @author tags and * the contributor list. * * Licensed under the MIT License (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://opensource.org/licenses/MIT * * The software is provided "AS IS", WITHOUT WARRANTY OF ANY KIND, express or * implied, including but not limited to the warranties of merchantability, * fitness for a particular purpose and noninfringement. in no event shall the * authors or copyright holders be liable for any claim, damages or other * liability, whether in an action of contract, tort or otherwise, arising from, * out of or in connection with the software or the use or other dealings in the * software. See the License for the specific language governing permissions and * limitations under the License. */ package com.kumuluz.ee.common.config; /** * @author Tilen Faganel * @since 2.4.0 */ public class DataSourcePoolConfig { public static class Builder { private Boolean autoCommit = true; private Boolean flushOnClose = false; private Long connectionTimeout = 30000L; private Long idleTimeout = 600000L; private Long maxLifetime = 1800000L; @Deprecated private Integer minIdle; private Integer initialSize = 0; private Integer minSize = 0; private Integer maxSize = 10; @Deprecated private String name; @Deprecated private Long initializationFailTimeout; @Deprecated private Boolean isolateInternalQueries; @Deprecated private Boolean allowPoolSuspension; @Deprecated private Boolean readOnly; @Deprecated private Boolean registerMbeans; private String connectionInitSql; private String connectionValidSql; private String transactionIsolation; private Long validationTimeout = 5000L; private Long leakDetectionThreshold = 0L; private Long idleValidationTimeout = 0L; public Builder autoCommit(Boolean autoCommit) { this.autoCommit = autoCommit; return this; } public Builder flushOnClose(Boolean flushOnClose) { this.flushOnClose = flushOnClose; return this; } public Builder connectionTimeout(Long connectionTimeout) { this.connectionTimeout = connectionTimeout; return this; } public Builder idleTimeout(Long idleTimeout) { this.idleTimeout = idleTimeout; return this; } public Builder maxLifetime(Long maxLifetime) { this.maxLifetime = maxLifetime; return this; } @Deprecated public Builder minIdle(Integer minIdle) { this.minIdle = minIdle; return this; } public Builder initialSize(Integer initialSize) { this.initialSize = initialSize; return this; } public Builder minSize(Integer minSize) { this.minSize = minSize; return this; } public Builder maxSize(Integer maxSize) { this.maxSize = maxSize; return this; } @Deprecated public Builder name(String name) { this.name = name; return this; } @Deprecated public Builder initializationFailTimeout(Long initializationFailTimeout) { this.initializationFailTimeout = initializationFailTimeout; return this; } @Deprecated public Builder isolateInternalQueries(Boolean isolateInternalQueries) { this.isolateInternalQueries = isolateInternalQueries; return this; } @Deprecated public Builder allowPoolSuspension(Boolean allowPoolSuspension) { this.allowPoolSuspension = allowPoolSuspension; return this; } @Deprecated public Builder readOnly(Boolean readOnly) { this.readOnly = readOnly; return this; } @Deprecated public Builder registerMbeans(Boolean registerMbeans) { this.registerMbeans = registerMbeans; return this; } public Builder connectionInitSql(String connectionInitSql) { this.connectionInitSql = connectionInitSql; return this; } public Builder connectionValidSql(String connectionValidSql) { this.connectionValidSql = connectionValidSql; return this; } public Builder transactionIsolation(String transactionIsolation) { this.transactionIsolation = transactionIsolation; return this; } public Builder validationTimeout(Long validationTimeout) { this.validationTimeout = validationTimeout; return this; } public Builder leakDetectionThreshold(Long leakDetectionThreshold) { this.leakDetectionThreshold = leakDetectionThreshold; return this; } public Builder idleValidationTimeout (Long idleValidationTimeout ) { this.idleValidationTimeout = idleValidationTimeout ; return this; } public DataSourcePoolConfig build() { DataSourcePoolConfig dataSourcePoolConfig = new DataSourcePoolConfig(); dataSourcePoolConfig.autoCommit = autoCommit; dataSourcePoolConfig.flushOnClose = flushOnClose; dataSourcePoolConfig.connectionTimeout = connectionTimeout; dataSourcePoolConfig.idleTimeout = idleTimeout; dataSourcePoolConfig.maxLifetime = maxLifetime; dataSourcePoolConfig.minIdle = minIdle; dataSourcePoolConfig.initialSize = initialSize; dataSourcePoolConfig.minSize = minSize; dataSourcePoolConfig.maxSize = maxSize; dataSourcePoolConfig.name = name; dataSourcePoolConfig.initializationFailTimeout = initializationFailTimeout; dataSourcePoolConfig.isolateInternalQueries = isolateInternalQueries; dataSourcePoolConfig.allowPoolSuspension = allowPoolSuspension; dataSourcePoolConfig.readOnly = readOnly; dataSourcePoolConfig.registerMbeans = registerMbeans; dataSourcePoolConfig.connectionInitSql = connectionInitSql; dataSourcePoolConfig.connectionValidSql = connectionValidSql; dataSourcePoolConfig.transactionIsolation = transactionIsolation; dataSourcePoolConfig.validationTimeout = validationTimeout; dataSourcePoolConfig.leakDetectionThreshold = leakDetectionThreshold; dataSourcePoolConfig.idleValidationTimeout = idleValidationTimeout; return dataSourcePoolConfig; } } private Boolean autoCommit; private Boolean flushOnClose; private Long connectionTimeout; private Long idleTimeout; private Long maxLifetime; @Deprecated private Integer minIdle; private Integer initialSize = 0; private Integer minSize = 0; private Integer maxSize; @Deprecated private String name; @Deprecated private Long initializationFailTimeout; @Deprecated private Boolean isolateInternalQueries; @Deprecated private Boolean allowPoolSuspension; @Deprecated private Boolean readOnly; @Deprecated private Boolean registerMbeans; private String connectionInitSql; private String connectionValidSql; private String transactionIsolation; private Long validationTimeout; private Long leakDetectionThreshold; private Long idleValidationTimeout; private DataSourcePoolConfig() { } public Boolean getFlushOnClose() { return flushOnClose; } public Boolean getAutoCommit() { return autoCommit; } public Long getConnectionTimeout() { return connectionTimeout; } public Long getIdleTimeout() { return idleTimeout; } public Long getMaxLifetime() { return maxLifetime; } @Deprecated public Integer getMinIdle() { return minIdle; } public Integer getInitialSize() { return initialSize; } public Integer getMinSize() { return minSize; } public Integer getMaxSize() { return maxSize; } @Deprecated public String getName() { return name; } @Deprecated public Long getInitializationFailTimeout() { return initializationFailTimeout; } @Deprecated public Boolean getIsolateInternalQueries() { return isolateInternalQueries; } @Deprecated public Boolean getAllowPoolSuspension() { return allowPoolSuspension; } @Deprecated public Boolean getReadOnly() { return readOnly; } @Deprecated public Boolean getRegisterMbeans() { return registerMbeans; } public String getConnectionInitSql() { return connectionInitSql; } public String getConnectionValidSql() { return connectionValidSql; } public String getTransactionIsolation() { return transactionIsolation; } public Long getValidationTimeout() { return validationTimeout; } public Long getLeakDetectionThreshold() { return leakDetectionThreshold; } public Long getIdleValidationTimeout() { return idleValidationTimeout; } } ================================================ FILE: common/src/main/java/com/kumuluz/ee/common/config/DevConfig.java ================================================ /* * Copyright (c) 2014-2017 Kumuluz and/or its affiliates * and other contributors as indicated by the @author tags and * the contributor list. * * Licensed under the MIT License (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://opensource.org/licenses/MIT * * The software is provided "AS IS", WITHOUT WARRANTY OF ANY KIND, express or * implied, including but not limited to the warranties of merchantability, * fitness for a particular purpose and noninfringement. in no event shall the * authors or copyright holders be liable for any claim, damages or other * liability, whether in an action of contract, tort or otherwise, arising from, * out of or in connection with the software or the use or other dealings in the * software. See the License for the specific language governing permissions and * limitations under the License. */ package com.kumuluz.ee.common.config; import java.util.List; /** * @author Tilen Faganel * @since 2.4.0 */ public class DevConfig { public static class Builder { private String webappDir; private List scanLibraries; private Boolean runningTests = false; public Builder scanLibraries(List scanLibraries) { this.scanLibraries = scanLibraries; return this; } public Builder webappDir(String webappDir) { this.webappDir = webappDir; return this; } public Builder runningTests(Boolean runningTests) { this.runningTests = runningTests; return this; } public DevConfig build() { DevConfig devConfig = new DevConfig(); devConfig.webappDir = webappDir; devConfig.scanLibraries = scanLibraries; devConfig.runningTests = runningTests; return devConfig; } } private String webappDir; private List scanLibraries; private Boolean runningTests; private DevConfig() { } public String getWebappDir() { return webappDir; } public List getScanLibraries() { return scanLibraries; } public Boolean getRunningTests() { return runningTests; } } ================================================ FILE: common/src/main/java/com/kumuluz/ee/common/config/EeConfig.java ================================================ /* * Copyright (c) 2014-2017 Kumuluz and/or its affiliates * and other contributors as indicated by the @author tags and * the contributor list. * * Licensed under the MIT License (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://opensource.org/licenses/MIT * * The software is provided "AS IS", WITHOUT WARRANTY OF ANY KIND, express or * implied, including but not limited to the warranties of merchantability, * fitness for a particular purpose and noninfringement. in no event shall the * authors or copyright holders be liable for any claim, damages or other * liability, whether in an action of contract, tort or otherwise, arising from, * out of or in connection with the software or the use or other dealings in the * software. See the License for the specific language governing permissions and * limitations under the License. */ package com.kumuluz.ee.common.config; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.stream.Collectors; /** * @author Tilen Faganel * @since 1.0.0 */ public class EeConfig { public static class Builder { private String name; private String version = "1.0.0"; private Boolean debug = false; private EnvConfig.Builder env = new EnvConfig.Builder(); private DevConfig.Builder dev = new DevConfig.Builder(); private ServerConfig.Builder server = new ServerConfig.Builder(); private List datasources = new ArrayList<>(); private List xaDatasources = new ArrayList<>(); private List mailSessions = new ArrayList<>(); public Builder name(String name) { this.name = name; return this; } public Builder version(String version) { this.version = version; return this; } public Builder debug(Boolean debug) { this.debug = debug; return this; } public Builder env(EnvConfig.Builder env) { this.env = env; return this; } public Builder dev(DevConfig.Builder dev) { this.dev = dev; return this; } public Builder server(ServerConfig.Builder server) { this.server = server; return this; } public Builder datasource(DataSourceConfig.Builder datasource) { this.datasources.add(datasource); return this; } public Builder xaDatasource(XaDataSourceConfig.Builder xaDatasource) { this.xaDatasources.add(xaDatasource); return this; } public Builder mailSession(MailSessionConfig.Builder mailSession) { this.mailSessions.add(mailSession); return this; } public EeConfig build() { List constructedDatasources = datasources.stream().map(DataSourceConfig.Builder::build).collect(Collectors.toList()); List constructedXaDatasources = xaDatasources.stream().map(XaDataSourceConfig.Builder::build).collect(Collectors.toList()); List constructedMailSessions = mailSessions.stream().map(MailSessionConfig.Builder::build).collect(Collectors.toList()); EeConfig eeConfig = new EeConfig(); eeConfig.name = name; eeConfig.version = version; eeConfig.debug = debug; eeConfig.env = env.build(); eeConfig.dev = dev.build(); eeConfig.server = server.build(); eeConfig.datasources = Collections.unmodifiableList(constructedDatasources); eeConfig.xaDatasources = Collections.unmodifiableList(constructedXaDatasources); eeConfig.mailSessions = Collections.unmodifiableList(constructedMailSessions); return eeConfig; } } private static EeConfig instance; private String name; private String version; private Boolean debug; private EnvConfig env; private DevConfig dev; private ServerConfig server; private List datasources; private List xaDatasources; private List mailSessions; private EeConfig() { } public static void initialize(EeConfig eeConfig) { if (instance != null) { throw new IllegalStateException("The EeConfig was already initialized."); } instance = eeConfig; } public static EeConfig getInstance() { if (instance == null) { throw new IllegalStateException("The EeConfig was not yet initialized."); } return instance; } public String getName() { return name; } public String getVersion() { return version; } public Boolean getDebug() { return debug; } public EnvConfig getEnv() { return env; } public DevConfig getDev() { return dev; } public ServerConfig getServer() { return server; } public List getDatasources() { return datasources; } public List getXaDatasources() { return xaDatasources; } public List getMailSessions() { return mailSessions; } } ================================================ FILE: common/src/main/java/com/kumuluz/ee/common/config/EnvConfig.java ================================================ /* * Copyright (c) 2014-2017 Kumuluz and/or its affiliates * and other contributors as indicated by the @author tags and * the contributor list. * * Licensed under the MIT License (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://opensource.org/licenses/MIT * * The software is provided "AS IS", WITHOUT WARRANTY OF ANY KIND, express or * implied, including but not limited to the warranties of merchantability, * fitness for a particular purpose and noninfringement. in no event shall the * authors or copyright holders be liable for any claim, damages or other * liability, whether in an action of contract, tort or otherwise, arising from, * out of or in connection with the software or the use or other dealings in the * software. See the License for the specific language governing permissions and * limitations under the License. */ package com.kumuluz.ee.common.config; /** * @author Tilen Faganel * @since 2.4.0 */ public class EnvConfig { public static class Builder { private String name; public Builder name(String name) { this.name = name; return this; } public EnvConfig build() { EnvConfig envConfig = new EnvConfig(); envConfig.name = name; return envConfig; } } private String name; private EnvConfig() { } public String getName() { return name; } } ================================================ FILE: common/src/main/java/com/kumuluz/ee/common/config/GzipConfig.java ================================================ /* * Copyright (c) 2014-2017 Kumuluz and/or its affiliates * and other contributors as indicated by the @author tags and * the contributor list. * * Licensed under the MIT License (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://opensource.org/licenses/MIT * * The software is provided "AS IS", WITHOUT WARRANTY OF ANY KIND, express or * implied, including but not limited to the warranties of merchantability, * fitness for a particular purpose and noninfringement. in no event shall the * authors or copyright holders be liable for any claim, damages or other * liability, whether in an action of contract, tort or otherwise, arising from, * out of or in connection with the software or the use or other dealings in the * software. See the License for the specific language governing permissions and * limitations under the License. */ package com.kumuluz.ee.common.config; import java.util.List; public class GzipConfig { public static class Builder { private Boolean enabled = false; private Integer minGzipSize; private List includedMethods; private List includedMimeTypes; private List excludedMimeTypes; private List excludedAgentPatterns; private List excludedPaths; private List includedPaths; public Builder enabled(Boolean enabled) { this.enabled = enabled; return this; } public Builder minGzipSize(Integer minGzipSize) { this.minGzipSize = minGzipSize; return this; } public Builder includedMethods(List includedMethods) { this.includedMethods = includedMethods; return this; } public Builder includedMimeTypes(List includedMimeTypes) { this.includedMimeTypes = includedMimeTypes; return this; } public Builder excludedMimeTypes(List excludedMimeTypes) { this.excludedMimeTypes = excludedMimeTypes; return this; } public Builder excludedAgentPatterns(List excludedAgentPatterns) { this.excludedAgentPatterns = excludedAgentPatterns; return this; } public Builder excludedPaths(List excludedPaths) { this.excludedPaths = excludedPaths; return this; } public Builder includedPaths(List includedPaths) { this.includedPaths = includedPaths; return this; } public GzipConfig build() { GzipConfig gzipConfig = new GzipConfig(); gzipConfig.enabled = enabled; gzipConfig.minGzipSize = minGzipSize; gzipConfig.includedMethods = includedMethods; gzipConfig.includedMimeTypes = includedMimeTypes; gzipConfig.excludedMimeTypes = excludedMimeTypes; gzipConfig.excludedAgentPatterns = excludedAgentPatterns; gzipConfig.excludedPaths = excludedPaths; gzipConfig.includedPaths = includedPaths; return gzipConfig; } } private Boolean enabled; private Integer minGzipSize; private List includedMethods; private List includedMimeTypes; private List excludedMimeTypes; private List excludedAgentPatterns; private List excludedPaths; private List includedPaths; private GzipConfig() { } public Boolean getEnabled() { return enabled; } public void setEnabled(Boolean enabled) { this.enabled = enabled; } public Integer getMinGzipSize() { return minGzipSize; } public void setMinGzipSize(Integer minGzipSize) { this.minGzipSize = minGzipSize; } public List getIncludedMethods() { return includedMethods; } public void setIncludedMethods(List includedMethods) { this.includedMethods = includedMethods; } public List getIncludedMimeTypes() { return includedMimeTypes; } public void setIncludedMimeTypes(List includedMimeTypes) { this.includedMimeTypes = includedMimeTypes; } public List getExcludedMimeTypes() { return excludedMimeTypes; } public void setExcludedMimeTypes(List excludedMimeTypes) { this.excludedMimeTypes = excludedMimeTypes; } public List getExcludedPaths() { return excludedPaths; } public void setExcludedPaths(List excludedPaths) { this.excludedPaths = excludedPaths; } public List getIncludedPaths() { return includedPaths; } public void setIncludedPaths(List includedPaths) { this.includedPaths = includedPaths; } } ================================================ FILE: common/src/main/java/com/kumuluz/ee/common/config/MailServiceConfig.java ================================================ package com.kumuluz.ee.common.config; public class MailServiceConfig { public static class Builder { private String protocol; private String host; private Integer port; private Boolean starttls; private String username; private String password; private Long connectionTimeout; private Long timeout; public Builder protocol(String protocol) { this.protocol = protocol; return this; } public Builder host(String host) { this.host = host; return this; } public Builder port(Integer port) { this.port = port; return this; } public Builder starttls(Boolean starttls) { this.starttls = starttls; return this; } public Builder username(String username) { this.username = username; return this; } public Builder password(String password) { this.password = password; return this; } public Builder connectionTimeout(Long connectionTimeout) { this.connectionTimeout = connectionTimeout; return this; } public Builder timeout(Long timeout) { this.timeout = timeout; return this; } public MailServiceConfig build() { MailServiceConfig mailServiceConfig = new MailServiceConfig(); mailServiceConfig.protocol = protocol; mailServiceConfig.host = host; mailServiceConfig.port = port; mailServiceConfig.starttls = starttls; mailServiceConfig.username = username; mailServiceConfig.password = password; mailServiceConfig.connectionTimeout = connectionTimeout; mailServiceConfig.timeout = timeout; return mailServiceConfig; } } private String protocol; private String host; private Integer port; private Boolean starttls; private String username; private String password; private Long connectionTimeout; private Long timeout; private MailServiceConfig(){ } public String getProtocol() { return protocol; } public String getHost() { return host; } public Integer getPort() { return port; } public Boolean getStarttls() { return starttls; } public String getUsername() { return username; } public String getPassword() { return password; } public Long getConnectionTimeout() { return connectionTimeout; } public Long getTimeout() { return timeout; } } ================================================ FILE: common/src/main/java/com/kumuluz/ee/common/config/MailSessionConfig.java ================================================ package com.kumuluz.ee.common.config; import java.util.Collections; import java.util.HashMap; import java.util.Map; public class MailSessionConfig { public static class Builder { private String jndiName; private Boolean debug; private MailServiceConfig.Builder transport; private MailServiceConfig.Builder store; private Map props = new HashMap<>(); public Builder jndiName(String jndiName) { this.jndiName = jndiName; return this; } public Builder debug(Boolean debug) { this.debug = debug; return this; } public Builder transport(MailServiceConfig.Builder transport) { this.transport = transport; return this; } public Builder store(MailServiceConfig.Builder store) { this.store = store; return this; } public Builder prop(String key, String value) { this.props.put(key, value); return this; } public MailSessionConfig build() { MailSessionConfig mailSessionConfig = new MailSessionConfig(); mailSessionConfig.jndiName = jndiName; mailSessionConfig.debug = debug; if (transport != null) mailSessionConfig.transport = transport.build(); if (store != null) mailSessionConfig.store = store.build(); mailSessionConfig.props = Collections.unmodifiableMap(props); return mailSessionConfig; } } private String jndiName; private Boolean debug; private MailServiceConfig transport; private MailServiceConfig store; private Map props; private MailSessionConfig() { } public String getJndiName() { return jndiName; } public Boolean getDebug() { return debug; } public MailServiceConfig getTransport() { return transport; } public MailServiceConfig getStore() { return store; } public Map getProps() { return props; } } ================================================ FILE: common/src/main/java/com/kumuluz/ee/common/config/ServerConfig.java ================================================ /* * Copyright (c) 2014-2017 Kumuluz and/or its affiliates * and other contributors as indicated by the @author tags and * the contributor list. * * Licensed under the MIT License (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://opensource.org/licenses/MIT * * The software is provided "AS IS", WITHOUT WARRANTY OF ANY KIND, express or * implied, including but not limited to the warranties of merchantability, * fitness for a particular purpose and noninfringement. in no event shall the * authors or copyright holders be liable for any claim, damages or other * liability, whether in an action of contract, tort or otherwise, arising from, * out of or in connection with the software or the use or other dealings in the * software. See the License for the specific language governing permissions and * limitations under the License. */ package com.kumuluz.ee.common.config; /** * @author Tilen Faganel * @since 1.0.0 */ public class ServerConfig { public static class Builder { private String baseUrl; private String contextPath = "/"; private Boolean dirBrowsing = false; private Boolean etags = false; private Integer minThreads = 5; private Integer maxThreads = 100; private Boolean forceHttps = false; private Boolean showServerInfo = true; private Boolean forwardStartupException; private ServerConnectorConfig.Builder http = new ServerConnectorConfig.Builder(); private ServerConnectorConfig.Builder https; private GzipConfig.Builder gzip; public Builder baseUrl(String baseUrl) { this.baseUrl = baseUrl; return this; } public Builder contextPath(String contextPath) { this.contextPath = contextPath; return this; } public Builder dirBrowsing(Boolean dirBrowsing) { this.dirBrowsing = dirBrowsing; return this; } public Builder etags(Boolean etags) { this.etags = etags; return this; } public Builder minThreads(Integer minThreads) { this.minThreads = minThreads; return this; } public Builder maxThreads(Integer maxThreads) { this.maxThreads = maxThreads; return this; } public Builder forceHttps(Boolean forceHttps) { this.forceHttps = forceHttps; return this; } public Builder http(ServerConnectorConfig.Builder http) { this.http = http; return this; } public Builder https(ServerConnectorConfig.Builder https) { this.https = https; return this; } public Builder gzip(GzipConfig.Builder gzip) { this.gzip = gzip; return this; } public Builder showServerInfo(Boolean showServerInfo) { this.showServerInfo = showServerInfo; return this; } public Builder forwardStartupException(Boolean forwardStartupException) { this.forwardStartupException = forwardStartupException; return this; } public ServerConfig build() { ServerConfig serverConfig = new ServerConfig(); serverConfig.baseUrl = baseUrl; serverConfig.contextPath = contextPath; serverConfig.dirBrowsing = dirBrowsing; serverConfig.etags = etags; serverConfig.minThreads = minThreads; serverConfig.maxThreads = maxThreads; serverConfig.forceHttps = forceHttps; serverConfig.showServerInfo = showServerInfo; serverConfig.forwardStartupException = forwardStartupException; serverConfig.http = http.build(); if (https != null) serverConfig.https = https.build(); if (gzip != null) serverConfig.gzip = gzip.build(); return serverConfig; } } private String baseUrl; private String contextPath; private Boolean dirBrowsing; private Boolean etags; private Integer minThreads; private Integer maxThreads; private Boolean forceHttps; private Boolean showServerInfo; private Boolean forwardStartupException; private ServerConnectorConfig http; private ServerConnectorConfig https; private GzipConfig gzip; private ServerConfig() { } public String getBaseUrl() { return baseUrl; } public String getContextPath() { return contextPath; } public Boolean getDirBrowsing() { return dirBrowsing; } public Boolean getEtags() { return etags; } public Integer getMinThreads() { return minThreads; } public Integer getMaxThreads() { return maxThreads; } public Boolean getForceHttps() { return forceHttps; } public Boolean getShowServerInfo(){ return showServerInfo; } public Boolean getForwardStartupException() { return forwardStartupException; } public ServerConnectorConfig getHttp() { return http; } public ServerConnectorConfig getHttps() { return https; } public GzipConfig getGzip() { return gzip; } } ================================================ FILE: common/src/main/java/com/kumuluz/ee/common/config/ServerConnectorConfig.java ================================================ /* * Copyright (c) 2014-2017 Kumuluz and/or its affiliates * and other contributors as indicated by the @author tags and * the contributor list. * * Licensed under the MIT License (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://opensource.org/licenses/MIT * * The software is provided "AS IS", WITHOUT WARRANTY OF ANY KIND, express or * implied, including but not limited to the warranties of merchantability, * fitness for a particular purpose and noninfringement. in no event shall the * authors or copyright holders be liable for any claim, damages or other * liability, whether in an action of contract, tort or otherwise, arising from, * out of or in connection with the software or the use or other dealings in the * software. See the License for the specific language governing permissions and * limitations under the License. */ package com.kumuluz.ee.common.config; import java.util.Collections; import java.util.List; /** * @author Tilen Faganel * @since 2.4.0 */ public class ServerConnectorConfig { public final static Integer DEFAULT_HTTP_PORT = 8080; public final static Integer DEFAULT_HTTPS_PORT = 8443; public static class Builder { private Integer port; private String address; private Boolean enabled; private Boolean http2 = false; private Boolean proxyForwarding = false; private Integer requestHeaderSize = 8 * 1024; private Integer responseHeaderSize = 8 * 1024; private Integer idleTimeout = 30 * 1000; private String keystorePath; private String keystorePassword; private String keyAlias; private String keyPassword; private List sslProtocols; private List sslCiphers; public Builder port(Integer port) { this.port = port; return this; } public Builder address(String address) { this.address = address; return this; } public Builder enabled(Boolean enabled) { this.enabled = enabled; return this; } public Builder http2(Boolean http2) { this.http2 = http2; return this; } public Builder proxyForwarding(Boolean proxyForwarding) { this.proxyForwarding = proxyForwarding; return this; } public Builder requestHeaderSize(Integer requestHeaderSize) { this.requestHeaderSize = requestHeaderSize; return this; } public Builder responseHeaderSize(Integer responseHeaderSize) { this.responseHeaderSize = responseHeaderSize; return this; } public Builder idleTimeout(Integer idleTimeout) { this.idleTimeout = idleTimeout; return this; } public Builder keystorePath(String keystorePath) { this.keystorePath = keystorePath; return this; } public Builder keystorePassword(String keystorePassword) { this.keystorePassword = keystorePassword; return this; } public Builder keyAlias(String keyAlias) { this.keyAlias = keyAlias; return this; } public Builder keyPassword(String keyPassword) { this.keyPassword = keyPassword; return this; } public Builder sslProtocols(List sslProtocols) { this.sslProtocols = Collections.unmodifiableList(sslProtocols); return this; } public Builder sslCiphers(List sslCiphers) { this.sslCiphers = Collections.unmodifiableList(sslCiphers); return this; } public ServerConnectorConfig build() { ServerConnectorConfig serverConnectorConfig = new ServerConnectorConfig(); serverConnectorConfig.port = port; serverConnectorConfig.address = address; serverConnectorConfig.enabled = enabled; serverConnectorConfig.http2 = http2; serverConnectorConfig.proxyForwarding = proxyForwarding; serverConnectorConfig.requestHeaderSize = requestHeaderSize; serverConnectorConfig.responseHeaderSize = responseHeaderSize; serverConnectorConfig.idleTimeout = idleTimeout; serverConnectorConfig.keystorePath = keystorePath; serverConnectorConfig.keystorePassword = keystorePassword; serverConnectorConfig.keyAlias = keyAlias; serverConnectorConfig.keyPassword = keyPassword; serverConnectorConfig.sslProtocols = sslProtocols; serverConnectorConfig.sslCiphers = sslCiphers; return serverConnectorConfig; } } private Integer port; private String address; private Boolean enabled; private Boolean http2; private Boolean proxyForwarding; private Integer requestHeaderSize; private Integer responseHeaderSize; private Integer idleTimeout; private String keystorePath; private String keystorePassword; private String keyAlias; private String keyPassword; private List sslProtocols; private List sslCiphers; private ServerConnectorConfig() { } public Integer getPort() { return port; } public String getAddress() { return address; } public Boolean getEnabled() { return enabled; } public Boolean getHttp2() { return http2; } public Boolean getProxyForwarding() { return proxyForwarding; } public Integer getRequestHeaderSize() { return requestHeaderSize; } public Integer getResponseHeaderSize() { return responseHeaderSize; } public Integer getIdleTimeout() { return idleTimeout; } public String getKeystorePath() { return keystorePath; } public String getKeystorePassword() { return keystorePassword; } public String getKeyAlias() { return keyAlias; } public String getKeyPassword() { return keyPassword; } public List getSslProtocols() { return sslProtocols; } public List getSslCiphers() { return sslCiphers; } } ================================================ FILE: common/src/main/java/com/kumuluz/ee/common/config/XaDataSourceConfig.java ================================================ /* * Copyright (c) 2014-2017 Kumuluz and/or its affiliates * and other contributors as indicated by the @author tags and * the contributor list. * * Licensed under the MIT License (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://opensource.org/licenses/MIT * * The software is provided "AS IS", WITHOUT WARRANTY OF ANY KIND, express or * implied, including but not limited to the warranties of merchantability, * fitness for a particular purpose and noninfringement. in no event shall the * authors or copyright holders be liable for any claim, damages or other * liability, whether in an action of contract, tort or otherwise, arising from, * out of or in connection with the software or the use or other dealings in the * software. See the License for the specific language governing permissions and * limitations under the License. */ package com.kumuluz.ee.common.config; import java.util.Collections; import java.util.HashMap; import java.util.Map; /** * @author Tilen Faganel * @since 2.3.0 */ public class XaDataSourceConfig { public static class Builder { private String jndiName; private String xaDatasourceClass; private String username; private String password; private DataSourcePoolConfig.Builder pool = new DataSourcePoolConfig.Builder(); private Map props = new HashMap<>(); public Builder jndiName(String jndiName) { this.jndiName = jndiName; return this; } public Builder xaDatasourceClass(String xaDatasourceClass) { this.xaDatasourceClass = xaDatasourceClass; return this; } public Builder username(String username) { this.username = username; return this; } public Builder password(String password) { this.password = password; return this; } public Builder pool(DataSourcePoolConfig.Builder pool) { this.pool = pool; return this; } public Builder prop(String key, String value) { this.props.put(key, value); return this; } public XaDataSourceConfig build() { XaDataSourceConfig xaDataSourceConfig = new XaDataSourceConfig(); xaDataSourceConfig.jndiName = jndiName; xaDataSourceConfig.xaDatasourceClass = xaDatasourceClass; xaDataSourceConfig.username = username; xaDataSourceConfig.password = password; xaDataSourceConfig.pool = pool.build(); xaDataSourceConfig.props = Collections.unmodifiableMap(props); return xaDataSourceConfig; } } private String jndiName; private String xaDatasourceClass; private String username; private String password; private DataSourcePoolConfig pool; private Map props; private XaDataSourceConfig() { } public String getJndiName() { return jndiName; } public String getXaDatasourceClass() { return xaDatasourceClass; } public String getUsername() { return username; } public String getPassword() { return password; } public DataSourcePoolConfig getPool() { return pool; } public Map getProps() { return props; } } ================================================ FILE: common/src/main/java/com/kumuluz/ee/common/datasources/NonJtaXAConnectionWrapper.java ================================================ /* * Copyright (c) 2014-2017 Kumuluz and/or its affiliates * and other contributors as indicated by the @author tags and * the contributor list. * * Licensed under the MIT License (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://opensource.org/licenses/MIT * * The software is provided "AS IS", WITHOUT WARRANTY OF ANY KIND, express or * implied, including but not limited to the warranties of merchantability, * fitness for a particular purpose and noninfringement. in no event shall the * authors or copyright holders be liable for any claim, damages or other * liability, whether in an action of contract, tort or otherwise, arising from, * out of or in connection with the software or the use or other dealings in the * software. See the License for the specific language governing permissions and * limitations under the License. */ package com.kumuluz.ee.common.datasources; import javax.sql.XAConnection; import java.sql.*; import java.util.Collections; import java.util.Map; import java.util.Properties; import java.util.concurrent.Executor; /** * @author Tilen Faganel * @since 2.3.0 */ @Deprecated public class NonJtaXAConnectionWrapper implements Connection { private Boolean isClosed = false; private XAConnection xaConnection; public NonJtaXAConnectionWrapper(XAConnection xaConnection) { this.xaConnection = xaConnection; } @Override public Statement createStatement() throws SQLException { checkIfValid(); return xaConnection.getConnection().createStatement(); } @Override public PreparedStatement prepareStatement(String sql) throws SQLException { checkIfValid(); return xaConnection.getConnection().prepareStatement(sql); } @Override public CallableStatement prepareCall(String sql) throws SQLException { checkIfValid(); return xaConnection.getConnection().prepareCall(sql); } @Override public String nativeSQL(String sql) throws SQLException { checkIfValid(); return xaConnection.getConnection().nativeSQL(sql); } @Override public void setAutoCommit(boolean autoCommit) throws SQLException { checkIfValid(); xaConnection.getConnection().setAutoCommit(autoCommit); } @Override public boolean getAutoCommit() throws SQLException { checkIfValid(); return xaConnection.getConnection().getAutoCommit(); } @Override public void commit() throws SQLException { checkIfValid(); xaConnection.getConnection().commit(); } @Override public void rollback() throws SQLException { checkIfValid(); xaConnection.getConnection().rollback(); } @Override public void close() throws SQLException { if (isClosed) return; isClosed = true; if (xaConnection != null) { xaConnection.close(); xaConnection = null; } } @Override public boolean isClosed() throws SQLException { return isClosed; } @Override public DatabaseMetaData getMetaData() throws SQLException { checkIfValid(); return xaConnection.getConnection().getMetaData(); } @Override public void setReadOnly(boolean readOnly) throws SQLException { checkIfValid(); xaConnection.getConnection().setReadOnly(readOnly); } @Override public boolean isReadOnly() throws SQLException { checkIfValid(); return xaConnection.getConnection().isReadOnly(); } @Override public void setCatalog(String catalog) throws SQLException { checkIfValid(); xaConnection.getConnection().setCatalog(catalog); } @Override public String getCatalog() throws SQLException { checkIfValid(); return xaConnection.getConnection().getCatalog(); } @Override public void setTransactionIsolation(int level) throws SQLException { checkIfValid(); xaConnection.getConnection().setTransactionIsolation(level); } @Override public int getTransactionIsolation() throws SQLException { checkIfValid(); return xaConnection.getConnection().getTransactionIsolation(); } @Override public SQLWarning getWarnings() throws SQLException { checkIfValid(); return xaConnection.getConnection().getWarnings(); } @Override public void clearWarnings() throws SQLException { checkIfValid(); xaConnection.getConnection().clearWarnings(); } @Override public Statement createStatement(int resultSetType, int resultSetConcurrency) throws SQLException { checkIfValid(); return xaConnection.getConnection().createStatement(resultSetType, resultSetConcurrency); } @Override public PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency) throws SQLException { checkIfValid(); return xaConnection.getConnection().prepareStatement(sql, resultSetType, resultSetConcurrency); } @Override public CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency) throws SQLException { checkIfValid(); return xaConnection.getConnection().prepareCall(sql, resultSetType, resultSetConcurrency); } @Override public Map> getTypeMap() throws SQLException { checkIfValid(); return xaConnection.getConnection().getTypeMap(); } @Override public void setTypeMap(Map> map) throws SQLException { checkIfValid(); xaConnection.getConnection().setTypeMap(map); } @Override public void setHoldability(int holdability) throws SQLException { checkIfValid(); xaConnection.getConnection().setHoldability(holdability); } @Override public int getHoldability() throws SQLException { checkIfValid(); return xaConnection.getConnection().getHoldability(); } @Override public Savepoint setSavepoint() throws SQLException { checkIfValid(); return xaConnection.getConnection().setSavepoint(); } @Override public Savepoint setSavepoint(String name) throws SQLException { checkIfValid(); return xaConnection.getConnection().setSavepoint(name); } @Override public void rollback(Savepoint savepoint) throws SQLException { checkIfValid(); xaConnection.getConnection().rollback(); } @Override public void releaseSavepoint(Savepoint savepoint) throws SQLException { checkIfValid(); xaConnection.getConnection().releaseSavepoint(savepoint); } @Override public Statement createStatement(int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException { checkIfValid(); return xaConnection.getConnection().createStatement(resultSetType, resultSetConcurrency, resultSetHoldability); } @Override public PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException { checkIfValid(); return xaConnection.getConnection().prepareStatement(sql, resultSetType, resultSetConcurrency, resultSetHoldability); } @Override public CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException { checkIfValid(); return xaConnection.getConnection().prepareCall(sql, resultSetType, resultSetConcurrency, resultSetHoldability); } @Override public PreparedStatement prepareStatement(String sql, int autoGeneratedKeys) throws SQLException { checkIfValid(); return xaConnection.getConnection().prepareStatement(sql, autoGeneratedKeys); } @Override public PreparedStatement prepareStatement(String sql, int[] columnIndexes) throws SQLException { checkIfValid(); return xaConnection.getConnection().prepareStatement(sql, columnIndexes); } @Override public PreparedStatement prepareStatement(String sql, String[] columnNames) throws SQLException { checkIfValid(); return xaConnection.getConnection().prepareStatement(sql, columnNames); } @Override public Clob createClob() throws SQLException { checkIfValid(); return xaConnection.getConnection().createClob(); } @Override public Blob createBlob() throws SQLException { checkIfValid(); return xaConnection.getConnection().createBlob(); } @Override public NClob createNClob() throws SQLException { checkIfValid(); return xaConnection.getConnection().createNClob(); } @Override public SQLXML createSQLXML() throws SQLException { checkIfValid(); return xaConnection.getConnection().createSQLXML(); } @Override public boolean isValid(int timeout) throws SQLException { checkIfValid(); return xaConnection.getConnection().isValid(timeout); } @Override public void setClientInfo(String name, String value) throws SQLClientInfoException { try { checkIfValid(); xaConnection.getConnection().setClientInfo(name, value); } catch (SQLException e) { throw new SQLClientInfoException(Collections.emptyMap(), e); } } @Override public void setClientInfo(Properties properties) throws SQLClientInfoException { try { checkIfValid(); xaConnection.getConnection().setClientInfo(properties); } catch (SQLException e) { throw new SQLClientInfoException(Collections.emptyMap(), e); } } @Override public String getClientInfo(String name) throws SQLException { checkIfValid(); return xaConnection.getConnection().getClientInfo(name); } @Override public Properties getClientInfo() throws SQLException { checkIfValid(); return xaConnection.getConnection().getClientInfo(); } @Override public Array createArrayOf(String typeName, Object[] elements) throws SQLException { checkIfValid(); return xaConnection.getConnection().createArrayOf(typeName, elements); } @Override public Struct createStruct(String typeName, Object[] attributes) throws SQLException { checkIfValid(); return xaConnection.getConnection().createStruct(typeName, attributes); } @Override public void setSchema(String schema) throws SQLException { checkIfValid(); xaConnection.getConnection().setSchema(schema); } @Override public String getSchema() throws SQLException { checkIfValid(); return xaConnection.getConnection().getSchema(); } @Override public void abort(Executor executor) throws SQLException { checkIfValid(); xaConnection.getConnection().abort(executor); } @Override public void setNetworkTimeout(Executor executor, int milliseconds) throws SQLException { checkIfValid(); xaConnection.getConnection().setNetworkTimeout(executor, milliseconds); } @Override public int getNetworkTimeout() throws SQLException { checkIfValid(); return xaConnection.getConnection().getNetworkTimeout(); } @Override public T unwrap(Class iface) throws SQLException { checkIfValid(); return xaConnection.getConnection().unwrap(iface); } @Override public boolean isWrapperFor(Class iface) throws SQLException { checkIfValid(); return xaConnection.getConnection().isWrapperFor(iface); } private void checkIfValid() throws SQLException { if (isClosed) throw new SQLException("The connection is closed"); if (xaConnection == null) throw new SQLException("The connection is invalid"); } } ================================================ FILE: common/src/main/java/com/kumuluz/ee/common/datasources/NonJtaXADataSourceWrapper.java ================================================ /* * Copyright (c) 2014-2017 Kumuluz and/or its affiliates * and other contributors as indicated by the @author tags and * the contributor list. * * Licensed under the MIT License (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://opensource.org/licenses/MIT * * The software is provided "AS IS", WITHOUT WARRANTY OF ANY KIND, express or * implied, including but not limited to the warranties of merchantability, * fitness for a particular purpose and noninfringement. in no event shall the * authors or copyright holders be liable for any claim, damages or other * liability, whether in an action of contract, tort or otherwise, arising from, * out of or in connection with the software or the use or other dealings in the * software. See the License for the specific language governing permissions and * limitations under the License. */ package com.kumuluz.ee.common.datasources; import javax.sql.DataSource; import javax.sql.XAConnection; import javax.sql.XADataSource; import java.io.PrintWriter; import java.sql.Connection; import java.sql.SQLException; import java.sql.SQLFeatureNotSupportedException; import java.sql.Wrapper; import java.util.logging.Logger; /** * @author Tilen Faganel * @since 2.3.0 */ @Deprecated public class NonJtaXADataSourceWrapper implements XADataSourceWrapper { protected XADataSource xaDataSource; public NonJtaXADataSourceWrapper(XADataSource xaDataSource) { this.xaDataSource = xaDataSource; } @Override public Connection getConnection() throws SQLException { checkIfValid(); XAConnection xaConnection = xaDataSource.getXAConnection(); return new NonJtaXAConnectionWrapper(xaConnection); } @Override public Connection getConnection(String username, String password) throws SQLException { checkIfValid(); XAConnection xaConnection = xaDataSource.getXAConnection(username, password); return new NonJtaXAConnectionWrapper(xaConnection); } @Override public T unwrap(Class iface) throws SQLException { if (xaDataSource == null) { throw new SQLException("The underlying XADataSource is invalid or cannot be found"); } else if (iface.isInstance(xaDataSource)) { return iface.cast(xaDataSource); } else if (xaDataSource instanceof Wrapper) { return ((java.sql.Wrapper) xaDataSource).unwrap(iface); } else { throw new SQLException("The requested interface cannot be unwrapped"); } } @Override public boolean isWrapperFor(Class iface) throws SQLException { if (xaDataSource == null) { throw new SQLException("The underlying XADataSource is invalid or cannot be found"); } else if (iface.isInstance(xaDataSource)) { return true; } else if (xaDataSource instanceof Wrapper) { return ((java.sql.Wrapper) xaDataSource).isWrapperFor(iface); } return false; } @Override public PrintWriter getLogWriter() throws SQLException { checkIfValid(); return xaDataSource.getLogWriter(); } @Override public void setLogWriter(PrintWriter out) throws SQLException { checkIfValid(); xaDataSource.setLogWriter(out); } @Override public void setLoginTimeout(int seconds) throws SQLException { checkIfValid(); xaDataSource.setLoginTimeout(seconds); } @Override public int getLoginTimeout() throws SQLException { checkIfValid(); return xaDataSource.getLoginTimeout(); } @Override public Logger getParentLogger() throws SQLFeatureNotSupportedException { checkIfValid(); return xaDataSource.getParentLogger(); } protected void checkIfValid() { if (xaDataSource == null) throw new IllegalStateException("The XADataSource is invalid or cannot be found"); } } ================================================ FILE: common/src/main/java/com/kumuluz/ee/common/datasources/XADataSourceBuilder.java ================================================ /* * Copyright (c) 2014-2017 Kumuluz and/or its affiliates * and other contributors as indicated by the @author tags and * the contributor list. * * Licensed under the MIT License (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://opensource.org/licenses/MIT * * The software is provided "AS IS", WITHOUT WARRANTY OF ANY KIND, express or * implied, including but not limited to the warranties of merchantability, * fitness for a particular purpose and noninfringement. in no event shall the * authors or copyright holders be liable for any claim, damages or other * liability, whether in an action of contract, tort or otherwise, arising from, * out of or in connection with the software or the use or other dealings in the * software. See the License for the specific language governing permissions and * limitations under the License. */ package com.kumuluz.ee.common.datasources; import com.kumuluz.ee.common.config.XaDataSourceConfig; import com.kumuluz.ee.common.exceptions.KumuluzServerException; import javax.sql.XADataSource; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; /** * @author Tilen Faganel * @since 2.3.0 */ @Deprecated public class XADataSourceBuilder { private XaDataSourceConfig xaDataSourceConfig; public XADataSourceBuilder(XaDataSourceConfig xaDataSourceConfig) { this.xaDataSourceConfig = xaDataSourceConfig; } public XADataSource constructXaDataSource() { if (xaDataSourceConfig == null) { throw new KumuluzServerException("The XADataSource configuration object for creating a XADataSource cannot be null."); } if (xaDataSourceConfig.getXaDatasourceClass() == null) { throw new KumuluzServerException("The XADataSource class config property 'xa-datasource-class' for creating a XADataSource must be provided."); } XADataSource xaDataSource = createXaDataSourceObject(); setProperty(xaDataSource, "user", xaDataSourceConfig.getUsername()); setProperty(xaDataSource, "password", xaDataSourceConfig.getPassword()); xaDataSourceConfig.getProps().forEach((k, v) -> setProperty(xaDataSource, k, v)); return xaDataSource; } private XADataSource createXaDataSourceObject() { try { return (XADataSource) Class.forName(xaDataSourceConfig.getXaDatasourceClass()).newInstance(); } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | ClassCastException e) { String msg = "The XADataSource class '" + xaDataSourceConfig.getXaDatasourceClass() + "' is either incorrect or is not present in the classpath."; throw new KumuluzServerException(msg, e); } } private void setProperty(Object object, String name, String value) { name = "set" + name.substring(0, 1).toUpperCase() + name.substring(1); Method[] methods = object.getClass().getMethods(); Method matchingMethod = null; for (Method method : methods) { if (method.getName().equalsIgnoreCase(name) && method.getParameterTypes().length == 1) { // ignores overloading, just takes the first match it finds. matchingMethod = method; break; } } if (matchingMethod == null) { String msg = "The XADataSource configuration property '" + name + "' is either incorrect or doesn't exist."; throw new KumuluzServerException(msg); } Class type = matchingMethod.getParameterTypes()[0]; Object argument = value; if (type == Integer.TYPE) { argument = Integer.valueOf(value); } if (type == Boolean.TYPE) { argument = Boolean.valueOf(value); } try { matchingMethod.invoke(object, argument); } catch (IllegalAccessException | InvocationTargetException e) { String msg = "The XADataSource configuration property '" + name + "' is either incorrect or doesn't exist."; throw new KumuluzServerException(msg, e); } } } ================================================ FILE: common/src/main/java/com/kumuluz/ee/common/datasources/XADataSourceWrapper.java ================================================ /* * Copyright (c) 2014-2017 Kumuluz and/or its affiliates * and other contributors as indicated by the @author tags and * the contributor list. * * Licensed under the MIT License (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://opensource.org/licenses/MIT * * The software is provided "AS IS", WITHOUT WARRANTY OF ANY KIND, express or * implied, including but not limited to the warranties of merchantability, * fitness for a particular purpose and noninfringement. in no event shall the * authors or copyright holders be liable for any claim, damages or other * liability, whether in an action of contract, tort or otherwise, arising from, * out of or in connection with the software or the use or other dealings in the * software. See the License for the specific language governing permissions and * limitations under the License. */ package com.kumuluz.ee.common.datasources; import javax.sql.DataSource; /** * @author Tilen Faganel * @since 2.3.0 */ @Deprecated public interface XADataSourceWrapper extends DataSource { } ================================================ FILE: common/src/main/java/com/kumuluz/ee/common/dependencies/EeComponentDef.java ================================================ /* * Copyright (c) 2014-2017 Kumuluz and/or its affiliates * and other contributors as indicated by the @author tags and * the contributor list. * * Licensed under the MIT License (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://opensource.org/licenses/MIT * * The software is provided "AS IS", WITHOUT WARRANTY OF ANY KIND, express or * implied, including but not limited to the warranties of merchantability, * fitness for a particular purpose and noninfringement. in no event shall the * authors or copyright holders be liable for any claim, damages or other * liability, whether in an action of contract, tort or otherwise, arising from, * out of or in connection with the software or the use or other dealings in the * software. See the License for the specific language governing permissions and * limitations under the License. */ package com.kumuluz.ee.common.dependencies; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * @author Tilen Faganel * @since 2.0.0 */ @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.TYPE}) public @interface EeComponentDef { String name(); EeComponentType type(); } ================================================ FILE: common/src/main/java/com/kumuluz/ee/common/dependencies/EeComponentDependencies.java ================================================ /* * Copyright (c) 2014-2017 Kumuluz and/or its affiliates * and other contributors as indicated by the @author tags and * the contributor list. * * Licensed under the MIT License (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://opensource.org/licenses/MIT * * The software is provided "AS IS", WITHOUT WARRANTY OF ANY KIND, express or * implied, including but not limited to the warranties of merchantability, * fitness for a particular purpose and noninfringement. in no event shall the * authors or copyright holders be liable for any claim, damages or other * liability, whether in an action of contract, tort or otherwise, arising from, * out of or in connection with the software or the use or other dealings in the * software. See the License for the specific language governing permissions and * limitations under the License. */ package com.kumuluz.ee.common.dependencies; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * @author Tilen Faganel * @since 2.0.0 */ @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.TYPE}) public @interface EeComponentDependencies { EeComponentDependency[] value(); } ================================================ FILE: common/src/main/java/com/kumuluz/ee/common/dependencies/EeComponentDependency.java ================================================ /* * Copyright (c) 2014-2017 Kumuluz and/or its affiliates * and other contributors as indicated by the @author tags and * the contributor list. * * Licensed under the MIT License (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://opensource.org/licenses/MIT * * The software is provided "AS IS", WITHOUT WARRANTY OF ANY KIND, express or * implied, including but not limited to the warranties of merchantability, * fitness for a particular purpose and noninfringement. in no event shall the * authors or copyright holders be liable for any claim, damages or other * liability, whether in an action of contract, tort or otherwise, arising from, * out of or in connection with the software or the use or other dealings in the * software. See the License for the specific language governing permissions and * limitations under the License. */ package com.kumuluz.ee.common.dependencies; import java.lang.annotation.*; /** * @author Tilen Faganel * @since 2.0.0 */ @Repeatable(EeComponentDependencies.class) @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.TYPE}) public @interface EeComponentDependency { EeComponentType value(); String[] implementations() default {}; } ================================================ FILE: common/src/main/java/com/kumuluz/ee/common/dependencies/EeComponentOptional.java ================================================ /* * Copyright (c) 2014-2017 Kumuluz and/or its affiliates * and other contributors as indicated by the @author tags and * the contributor list. * * Licensed under the MIT License (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://opensource.org/licenses/MIT * * The software is provided "AS IS", WITHOUT WARRANTY OF ANY KIND, express or * implied, including but not limited to the warranties of merchantability, * fitness for a particular purpose and noninfringement. in no event shall the * authors or copyright holders be liable for any claim, damages or other * liability, whether in an action of contract, tort or otherwise, arising from, * out of or in connection with the software or the use or other dealings in the * software. See the License for the specific language governing permissions and * limitations under the License. */ package com.kumuluz.ee.common.dependencies; import java.lang.annotation.*; /** * @author Tilen Faganel * @since 2.0.0 */ @Repeatable(EeComponentOptionals.class) @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.TYPE}) public @interface EeComponentOptional { EeComponentType value(); String[] implementations() default {}; } ================================================ FILE: common/src/main/java/com/kumuluz/ee/common/dependencies/EeComponentOptionals.java ================================================ /* * Copyright (c) 2014-2017 Kumuluz and/or its affiliates * and other contributors as indicated by the @author tags and * the contributor list. * * Licensed under the MIT License (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://opensource.org/licenses/MIT * * The software is provided "AS IS", WITHOUT WARRANTY OF ANY KIND, express or * implied, including but not limited to the warranties of merchantability, * fitness for a particular purpose and noninfringement. in no event shall the * authors or copyright holders be liable for any claim, damages or other * liability, whether in an action of contract, tort or otherwise, arising from, * out of or in connection with the software or the use or other dealings in the * software. See the License for the specific language governing permissions and * limitations under the License. */ package com.kumuluz.ee.common.dependencies; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * @author Tilen Faganel * @since 2.0.0 */ @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.TYPE}) public @interface EeComponentOptionals { EeComponentOptional[] value(); } ================================================ FILE: common/src/main/java/com/kumuluz/ee/common/dependencies/EeComponentType.java ================================================ /* * Copyright (c) 2014-2017 Kumuluz and/or its affiliates * and other contributors as indicated by the @author tags and * the contributor list. * * Licensed under the MIT License (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://opensource.org/licenses/MIT * * The software is provided "AS IS", WITHOUT WARRANTY OF ANY KIND, express or * implied, including but not limited to the warranties of merchantability, * fitness for a particular purpose and noninfringement. in no event shall the * authors or copyright holders be liable for any claim, damages or other * liability, whether in an action of contract, tort or otherwise, arising from, * out of or in connection with the software or the use or other dealings in the * software. See the License for the specific language governing permissions and * limitations under the License. */ package com.kumuluz.ee.common.dependencies; /** * @author Tilen Faganel * @since 2.0.0 */ public enum EeComponentType { SERVLET("Servlet"), WEBSOCKET("WebSocket"), JSP("JSP"), EL("EL"), JSF("JSF"), JPA("JPA"), CDI("CDI"), JAX_RS("JAX-RS"), JAX_WS("JAX-WS"), BEAN_VALIDATION("Bean Validation"), JSON_P("JSON-P"), JSON_B("JSON-B"), JTA("JTA"), EJB("EJB"), BATCH("Batch"), MAIL("JavaMail"); private final String name; EeComponentType(String name) { this.name = name; } public String getName() { return name; } } ================================================ FILE: common/src/main/java/com/kumuluz/ee/common/dependencies/EeExtensionDef.java ================================================ /* * Copyright (c) 2014-2017 Kumuluz and/or its affiliates * and other contributors as indicated by the @author tags and * the contributor list. * * Licensed under the MIT License (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://opensource.org/licenses/MIT * * The software is provided "AS IS", WITHOUT WARRANTY OF ANY KIND, express or * implied, including but not limited to the warranties of merchantability, * fitness for a particular purpose and noninfringement. in no event shall the * authors or copyright holders be liable for any claim, damages or other * liability, whether in an action of contract, tort or otherwise, arising from, * out of or in connection with the software or the use or other dealings in the * software. See the License for the specific language governing permissions and * limitations under the License. */ package com.kumuluz.ee.common.dependencies; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * @author Tilen Faganel * @since 2.3.0 */ @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.TYPE}) public @interface EeExtensionDef { String name(); String group(); } ================================================ FILE: common/src/main/java/com/kumuluz/ee/common/dependencies/EeExtensionGroup.java ================================================ package com.kumuluz.ee.common.dependencies; public class EeExtensionGroup { public final static String CONFIG = "config"; public final static String LOGS = "logs"; public final static String DISCOVERY = "discovery"; public final static String SECURITY = "security"; public final static String FAULT_TOLERANCE = "fault.tolerance"; public final static String STREAMING = "streaming"; public final static String METRICS = "metrics"; public final static String HEALTH = "health"; public final static String CORS = "cors"; public final static String REST_CLIENT = "rest.client"; public final static String AMQP = "amqp"; public final static String CACHING = "caching"; public final static String GRAPHQL = "graphql"; } ================================================ FILE: common/src/main/java/com/kumuluz/ee/common/dependencies/ServerDef.java ================================================ /* * Copyright (c) 2014-2017 Kumuluz and/or its affiliates * and other contributors as indicated by the @author tags and * the contributor list. * * Licensed under the MIT License (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://opensource.org/licenses/MIT * * The software is provided "AS IS", WITHOUT WARRANTY OF ANY KIND, express or * implied, including but not limited to the warranties of merchantability, * fitness for a particular purpose and noninfringement. in no event shall the * authors or copyright holders be liable for any claim, damages or other * liability, whether in an action of contract, tort or otherwise, arising from, * out of or in connection with the software or the use or other dealings in the * software. See the License for the specific language governing permissions and * limitations under the License. */ package com.kumuluz.ee.common.dependencies; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * @author Tilen Faganel * @since 2.0.0 */ @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.TYPE}) public @interface ServerDef { String value(); EeComponentType[] provides() default {}; } ================================================ FILE: common/src/main/java/com/kumuluz/ee/common/exceptions/ComponentsException.java ================================================ /* * Copyright (c) 2014-2017 Kumuluz and/or its affiliates * and other contributors as indicated by the @author tags and * the contributor list. * * Licensed under the MIT License (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://opensource.org/licenses/MIT * * The software is provided "AS IS", WITHOUT WARRANTY OF ANY KIND, express or * implied, including but not limited to the warranties of merchantability, * fitness for a particular purpose and noninfringement. in no event shall the * authors or copyright holders be liable for any claim, damages or other * liability, whether in an action of contract, tort or otherwise, arising from, * out of or in connection with the software or the use or other dealings in the * software. See the License for the specific language governing permissions and * limitations under the License. */ package com.kumuluz.ee.common.exceptions; /** * @author Tilen Faganel * @since 1.0.0 */ public class ComponentsException extends RuntimeException { public ComponentsException(String msg) { super(msg); } public ComponentsException(String msg, Throwable cause) { super(msg, cause); } } ================================================ FILE: common/src/main/java/com/kumuluz/ee/common/exceptions/KumuluzServerException.java ================================================ /* * Copyright (c) 2014-2017 Kumuluz and/or its affiliates * and other contributors as indicated by the @author tags and * the contributor list. * * Licensed under the MIT License (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://opensource.org/licenses/MIT * * The software is provided "AS IS", WITHOUT WARRANTY OF ANY KIND, express or * implied, including but not limited to the warranties of merchantability, * fitness for a particular purpose and noninfringement. in no event shall the * authors or copyright holders be liable for any claim, damages or other * liability, whether in an action of contract, tort or otherwise, arising from, * out of or in connection with the software or the use or other dealings in the * software. See the License for the specific language governing permissions and * limitations under the License. */ package com.kumuluz.ee.common.exceptions; /** * @author Tilen Faganel * @since 1.0.0 */ public class KumuluzServerException extends RuntimeException { public KumuluzServerException(String msg) { super(msg); } public KumuluzServerException(String msg, Throwable cause) { super(msg, cause); } } ================================================ FILE: common/src/main/java/com/kumuluz/ee/common/filters/PoweredByFilter.java ================================================ /* * Copyright (c) 2014-2017 Kumuluz and/or its affiliates * and other contributors as indicated by the @author tags and * the contributor list. * * Licensed under the MIT License (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://opensource.org/licenses/MIT * * The software is provided "AS IS", WITHOUT WARRANTY OF ANY KIND, express or * implied, including but not limited to the warranties of merchantability, * fitness for a particular purpose and noninfringement. in no event shall the * authors or copyright holders be liable for any claim, damages or other * liability, whether in an action of contract, tort or otherwise, arising from, * out of or in connection with the software or the use or other dealings in the * software. See the License for the specific language governing permissions and * limitations under the License. */ package com.kumuluz.ee.common.filters; import javax.servlet.*; import javax.servlet.http.HttpServletResponse; import java.io.IOException; public class PoweredByFilter implements Filter { private String name; @Override public void init(FilterConfig filterConfig) throws ServletException { this.name = filterConfig.getInitParameter("name"); } @Override public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain) throws IOException, ServletException { ((HttpServletResponse) response).addHeader("X-Powered-By", name); chain.doFilter(request, response); } @Override public void destroy() { } } ================================================ FILE: common/src/main/java/com/kumuluz/ee/common/runtime/EeRuntime.java ================================================ /* * Copyright (c) 2014-2017 Kumuluz and/or its affiliates * and other contributors as indicated by the @author tags and * the contributor list. * * Licensed under the MIT License (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://opensource.org/licenses/MIT * * The software is provided "AS IS", WITHOUT WARRANTY OF ANY KIND, express or * implied, including but not limited to the warranties of merchantability, * fitness for a particular purpose and noninfringement. in no event shall the * authors or copyright holders be liable for any claim, damages or other * liability, whether in an action of contract, tort or otherwise, arising from, * out of or in connection with the software or the use or other dealings in the * software. See the License for the specific language governing permissions and * limitations under the License. */ package com.kumuluz.ee.common.runtime; import java.util.List; /** * @author Tilen Faganel * @since 2.4.0 */ public class EeRuntime { private EeRuntimeInternal internalRuntime; private static EeRuntime instance; protected EeRuntime() { } private EeRuntime(EeRuntimeInternal internalRuntime) { this.internalRuntime = internalRuntime; } public static void initialize(EeRuntimeInternal runtimeInternal) { if (instance != null) { throw new IllegalStateException("The EeRuntime was already initialized."); } instance = new EeRuntime(runtimeInternal); } public static EeRuntime getInstance() { if (instance == null) { throw new IllegalStateException("The EeRuntime was not yet initialized."); } return instance; } public String getInstanceId() { return internalRuntime.getInstanceId(); } public String getVersion() { return internalRuntime.getVersion(); } public List getEeComponents() { return internalRuntime.getEeComponents(); } public List getEeExtensions() { return internalRuntime.getEeExtensions(); } } ================================================ FILE: common/src/main/java/com/kumuluz/ee/common/runtime/EeRuntimeComponent.java ================================================ /* * Copyright (c) 2014-2017 Kumuluz and/or its affiliates * and other contributors as indicated by the @author tags and * the contributor list. * * Licensed under the MIT License (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://opensource.org/licenses/MIT * * The software is provided "AS IS", WITHOUT WARRANTY OF ANY KIND, express or * implied, including but not limited to the warranties of merchantability, * fitness for a particular purpose and noninfringement. in no event shall the * authors or copyright holders be liable for any claim, damages or other * liability, whether in an action of contract, tort or otherwise, arising from, * out of or in connection with the software or the use or other dealings in the * software. See the License for the specific language governing permissions and * limitations under the License. */ package com.kumuluz.ee.common.runtime; import com.kumuluz.ee.common.dependencies.EeComponentType; /** * @author Tilen Faganel * @since 2.4.0 */ public class EeRuntimeComponent { private EeComponentType type; private String implementationName; public EeRuntimeComponent(EeComponentType type, String implementationName) { this.type = type; this.implementationName = implementationName; } public EeComponentType getType() { return type; } public String getImplementationName() { return implementationName; } } ================================================ FILE: common/src/main/java/com/kumuluz/ee/common/runtime/EeRuntimeExtension.java ================================================ /* * Copyright (c) 2014-2017 Kumuluz and/or its affiliates * and other contributors as indicated by the @author tags and * the contributor list. * * Licensed under the MIT License (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://opensource.org/licenses/MIT * * The software is provided "AS IS", WITHOUT WARRANTY OF ANY KIND, express or * implied, including but not limited to the warranties of merchantability, * fitness for a particular purpose and noninfringement. in no event shall the * authors or copyright holders be liable for any claim, damages or other * liability, whether in an action of contract, tort or otherwise, arising from, * out of or in connection with the software or the use or other dealings in the * software. See the License for the specific language governing permissions and * limitations under the License. */ package com.kumuluz.ee.common.runtime; /** * @author Jan Meznarič * @since 2.5.0 */ public class EeRuntimeExtension { private String group; private String implementationName; public EeRuntimeExtension(String group, String implementationName) { this.group = group; this.implementationName = implementationName; } public String getGroup() { return group; } public String getImplementationName() { return implementationName; } } ================================================ FILE: common/src/main/java/com/kumuluz/ee/common/runtime/EeRuntimeInternal.java ================================================ /* * Copyright (c) 2014-2017 Kumuluz and/or its affiliates * and other contributors as indicated by the @author tags and * the contributor list. * * Licensed under the MIT License (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://opensource.org/licenses/MIT * * The software is provided "AS IS", WITHOUT WARRANTY OF ANY KIND, express or * implied, including but not limited to the warranties of merchantability, * fitness for a particular purpose and noninfringement. in no event shall the * authors or copyright holders be liable for any claim, damages or other * liability, whether in an action of contract, tort or otherwise, arising from, * out of or in connection with the software or the use or other dealings in the * software. See the License for the specific language governing permissions and * limitations under the License. */ package com.kumuluz.ee.common.runtime; import java.util.Collections; import java.util.List; import java.util.ResourceBundle; import java.util.UUID; /** * @author Tilen Faganel * @since 2.4.0 */ public class EeRuntimeInternal { private String instanceId = UUID.randomUUID().toString(); private String version = ResourceBundle.getBundle("META-INF/kumuluzee/versions").getString("version"); private List eeComponents = Collections.emptyList(); private List eeExtensions = Collections.emptyList(); public String getInstanceId() { return instanceId; } public void setInstanceId(String instanceId) { this.instanceId = instanceId; } public String getVersion() { return version; } public void setVersion(String version) { this.version = version; } public List getEeComponents() { return eeComponents; } public void setEeComponents(List eeComponents) { this.eeComponents = Collections.unmodifiableList(eeComponents); } public List getEeExtensions() { return eeExtensions; } public void setEeExtensions(List eeExtensions) { this.eeExtensions = Collections.unmodifiableList(eeExtensions); } } ================================================ FILE: common/src/main/java/com/kumuluz/ee/common/servlet/ServletWrapper.java ================================================ /* * Copyright (c) 2014-2017 Kumuluz and/or its affiliates * and other contributors as indicated by the @author tags and * the contributor list. * * Licensed under the MIT License (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://opensource.org/licenses/MIT * * The software is provided "AS IS", WITHOUT WARRANTY OF ANY KIND, express or * implied, including but not limited to the warranties of merchantability, * fitness for a particular purpose and noninfringement. in no event shall the * authors or copyright holders be liable for any claim, damages or other * liability, whether in an action of contract, tort or otherwise, arising from, * out of or in connection with the software or the use or other dealings in the * software. See the License for the specific language governing permissions and * limitations under the License. */ package com.kumuluz.ee.common.servlet; /** * @author Urban Malc * @since 2.6.0 */ public class ServletWrapper { private String name; private String contextPath; public ServletWrapper(String name, String contextPath) { this.name = name; this.contextPath = contextPath; } public String getName() { return name; } public String getContextPath() { return contextPath; } } ================================================ FILE: common/src/main/java/com/kumuluz/ee/common/utils/ClassUtils.java ================================================ /* * Copyright (c) 2014-2017 Kumuluz and/or its affiliates * and other contributors as indicated by the @author tags and * the contributor list. * * Licensed under the MIT License (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://opensource.org/licenses/MIT * * The software is provided "AS IS", WITHOUT WARRANTY OF ANY KIND, express or * implied, including but not limited to the warranties of merchantability, * fitness for a particular purpose and noninfringement. in no event shall the * authors or copyright holders be liable for any claim, damages or other * liability, whether in an action of contract, tort or otherwise, arising from, * out of or in connection with the software or the use or other dealings in the * software. See the License for the specific language governing permissions and * limitations under the License. */ package com.kumuluz.ee.common.utils; /** * @author Tilen Faganel * @since 1.0.0 */ public class ClassUtils { public static boolean isPresent(String className) { return loadClass(className) != null; } public static Class loadClass(String className) { try { return Class.forName(className); } catch (Throwable ex) { return null; } } } ================================================ FILE: common/src/main/java/com/kumuluz/ee/common/utils/EnvUtils.java ================================================ /* * Copyright (c) 2014-2017 Kumuluz and/or its affiliates * and other contributors as indicated by the @author tags and * the contributor list. * * Licensed under the MIT License (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://opensource.org/licenses/MIT * * The software is provided "AS IS", WITHOUT WARRANTY OF ANY KIND, express or * implied, including but not limited to the warranties of merchantability, * fitness for a particular purpose and noninfringement. in no event shall the * authors or copyright holders be liable for any claim, damages or other * liability, whether in an action of contract, tort or otherwise, arising from, * out of or in connection with the software or the use or other dealings in the * software. See the License for the specific language governing permissions and * limitations under the License. */ package com.kumuluz.ee.common.utils; import com.kumuluz.ee.common.exceptions.KumuluzServerException; import java.util.Optional; import java.util.function.Consumer; /** * @author Tilen Faganel * @since 1.0.0 */ public class EnvUtils { public static void getEnv(String var, Consumer consumer) { Optional.ofNullable(System.getenv(var)) .filter(s -> !s.isEmpty()) .ifPresent(consumer); } public static void getEnvAsInteger(String var, Consumer consumer) { try { Optional.ofNullable(System.getenv(var)) .filter(s -> !s.isEmpty()) .ifPresent(s -> consumer.accept(Integer.parseInt(s))); } catch (NumberFormatException e) { throw new KumuluzServerException(var + "is in the incorrect format", e); } } } ================================================ FILE: common/src/main/java/com/kumuluz/ee/common/utils/ResourceUtils.java ================================================ /* * Copyright (c) 2014-2017 Kumuluz and/or its affiliates * and other contributors as indicated by the @author tags and * the contributor list. * * Licensed under the MIT License (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://opensource.org/licenses/MIT * * The software is provided "AS IS", WITHOUT WARRANTY OF ANY KIND, express or * implied, including but not limited to the warranties of merchantability, * fitness for a particular purpose and noninfringement. in no event shall the * authors or copyright holders be liable for any claim, damages or other * liability, whether in an action of contract, tort or otherwise, arising from, * out of or in connection with the software or the use or other dealings in the * software. See the License for the specific language governing permissions and * limitations under the License. */ package com.kumuluz.ee.common.utils; import com.kumuluz.ee.common.config.DevConfig; import com.kumuluz.ee.common.config.EeConfig; import com.kumuluz.ee.common.exceptions.KumuluzServerException; import java.io.IOException; import java.net.URISyntaxException; import java.net.URL; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; /** * @author Tilen Faganel * @since 1.0.0 */ public class ResourceUtils { public static String getProjectWebResources() { // First check the `webapp` directory in the compiled resources URL webApp = ResourceUtils.class.getClassLoader().getResource("webapp"); if (webApp != null) { return webApp.toString(); } // Next check if running inside an IDE and try to find the `src/main/webapp` dir URL resourceRoot = ResourceUtils.class.getClassLoader().getResource("."); if (resourceRoot != null) { try { Path resourceRootPath = Paths.get(resourceRoot.toURI()); // If running with maven if (Files.isDirectory(resourceRootPath) && resourceRootPath.getFileName().toString().equals("classes") && resourceRootPath.getParent() != null && resourceRootPath.getParent().getFileName().toString().equals("target")) { DevConfig devConfig = EeConfig.getInstance().getDev(); Path sibling = devConfig.getWebappDir() == null ? Paths.get( "src", "main", "webapp") : Paths.get(devConfig.getWebappDir()); Path sourceWebApp = resourceRootPath.getParent().resolveSibling(sibling); if (Files.isDirectory(sourceWebApp)) { return sourceWebApp.toString(); } } } catch (URISyntaxException e) { throw new KumuluzServerException("Could not retrieve the class loaders' resource dir.", e); } } // Finally if nothing is found, create a temp directory and delete it on shutdown try { final Path tempWebApp = Files.createTempDirectory("kumuluzee-tmp-webapp"); Runtime.getRuntime().addShutdownHook(new Thread(() -> { try { Files.delete(tempWebApp); } catch (IOException ignored) { } })); return tempWebApp.toString(); } catch (IOException e) { throw new KumuluzServerException("Could not initialize a temporary webapp directory.", e); } } public static boolean isRunningInJar() { URL jar = ResourceUtils.class.getClassLoader().getResource("webapp"); return (jar == null || jar.toString().toLowerCase().startsWith("jar:")) && ResourceUtils.class.getClassLoader().getClass().getName().equals("com.kumuluz.ee.loader.EeClassLoader"); } public static boolean isRunningTests() { return EeConfig.getInstance().getDev().getRunningTests(); } } ================================================ FILE: common/src/main/java/com/kumuluz/ee/common/utils/StringUtils.java ================================================ /* * Copyright (c) 2014-2017 Kumuluz and/or its affiliates * and other contributors as indicated by the @author tags and * the contributor list. * * Licensed under the MIT License (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://opensource.org/licenses/MIT * * The software is provided "AS IS", WITHOUT WARRANTY OF ANY KIND, express or * implied, including but not limited to the warranties of merchantability, * fitness for a particular purpose and noninfringement. in no event shall the * authors or copyright holders be liable for any claim, damages or other * liability, whether in an action of contract, tort or otherwise, arising from, * out of or in connection with the software or the use or other dealings in the * software. See the License for the specific language governing permissions and * limitations under the License. */ package com.kumuluz.ee.common.utils; import java.util.List; import java.util.stream.Collectors; import java.util.stream.Stream; /** * @author Tilen Faganel * @since 2.3.0 */ public class StringUtils { /** * Parse upper camel case to lower hyphen case. * * @param s string in upper camel case format * @return string in lower hyphen case format */ public static String camelCaseToHyphenCase(String s) { StringBuilder parsedString = new StringBuilder(s.substring(0, 1).toLowerCase()); for (char c : s.substring(1).toCharArray()) { if (Character.isUpperCase(c)) { parsedString.append("-").append(Character.toLowerCase(c)); } else { parsedString.append(c); } } return parsedString.toString(); } /** * Parse lower hyphen case to upper camel case. * * @param s string in lower hyphen case format * @return string in upper camel case format */ public static String hyphenCaseToCamelCase(String s) { List words = Stream.of(s.split("-")).filter(w -> !"".equals(w)).collect(Collectors.toList()); if (words.size() < 2) { return s; } StringBuilder parsedString = new StringBuilder(words.get(0)); for (int i = 1; i < words.size(); i++) { parsedString.append(Character.toUpperCase(words.get(i).charAt(0))).append(words.get(i).substring(1)); } return parsedString.toString(); } /** * Check whether the string is null or empty * * @param s string to check. * @return 'true' if string is null or empty, 'false' otherwise. */ public static boolean isNullOrEmpty(String s) { return s == null || s.isEmpty(); } } ================================================ FILE: common/src/main/java/com/kumuluz/ee/common/wrapper/ComponentWrapper.java ================================================ /* * Copyright (c) 2014-2017 Kumuluz and/or its affiliates * and other contributors as indicated by the @author tags and * the contributor list. * * Licensed under the MIT License (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://opensource.org/licenses/MIT * * The software is provided "AS IS", WITHOUT WARRANTY OF ANY KIND, express or * implied, including but not limited to the warranties of merchantability, * fitness for a particular purpose and noninfringement. in no event shall the * authors or copyright holders be liable for any claim, damages or other * liability, whether in an action of contract, tort or otherwise, arising from, * out of or in connection with the software or the use or other dealings in the * software. See the License for the specific language governing permissions and * limitations under the License. */ package com.kumuluz.ee.common.wrapper; import com.kumuluz.ee.common.Component; import com.kumuluz.ee.common.dependencies.EeComponentDependency; import com.kumuluz.ee.common.dependencies.EeComponentOptional; /** * @author Tilen Faganel * @since 2.0.0 */ public class ComponentWrapper { private Component component; private String name; private EeComponentDependency[] dependencies; private EeComponentOptional[] optionalDependencies; public ComponentWrapper(Component component, String name, EeComponentDependency[] dependencies, EeComponentOptional[] optionalDependencies) { this.component = component; this.name = name; this.dependencies = dependencies; this.optionalDependencies = optionalDependencies; } public Component getComponent() { return component; } public void setComponent(Component component) { this.component = component; } public EeComponentDependency[] getDependencies() { return dependencies; } public void setDependencies(EeComponentDependency[] dependencies) { this.dependencies = dependencies; } public EeComponentOptional[] getOptionalDependencies() { return optionalDependencies; } public void setOptionalDependencies(EeComponentOptional[] optionalDependencies) { this.optionalDependencies = optionalDependencies; } public String getName() { return name; } public void setName(String name) { this.name = name; } } ================================================ FILE: common/src/main/java/com/kumuluz/ee/common/wrapper/EeComponentWrapper.java ================================================ /* * Copyright (c) 2014-2017 Kumuluz and/or its affiliates * and other contributors as indicated by the @author tags and * the contributor list. * * Licensed under the MIT License (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://opensource.org/licenses/MIT * * The software is provided "AS IS", WITHOUT WARRANTY OF ANY KIND, express or * implied, including but not limited to the warranties of merchantability, * fitness for a particular purpose and noninfringement. in no event shall the * authors or copyright holders be liable for any claim, damages or other * liability, whether in an action of contract, tort or otherwise, arising from, * out of or in connection with the software or the use or other dealings in the * software. See the License for the specific language governing permissions and * limitations under the License. */ package com.kumuluz.ee.common.wrapper; import com.kumuluz.ee.common.Component; import com.kumuluz.ee.common.dependencies.EeComponentDependency; import com.kumuluz.ee.common.dependencies.EeComponentOptional; import com.kumuluz.ee.common.dependencies.EeComponentType; import java.util.List; /** * @author Tilen Faganel * @since 2.0.0 */ public class EeComponentWrapper extends ComponentWrapper { private EeComponentType type; public EeComponentWrapper(Component component, String name, EeComponentDependency[] dependencies, EeComponentOptional[] optionalDependencies) { super(component, name, dependencies, optionalDependencies); } public EeComponentWrapper(Component component, String name, EeComponentType type, EeComponentDependency[] dependencies, EeComponentOptional[] optionalDependencies) { super(component, name, dependencies, optionalDependencies); this.type = type; } public EeComponentType getType() { return type; } public void setType(EeComponentType type) { this.type = type; } } ================================================ FILE: common/src/main/java/com/kumuluz/ee/common/wrapper/ExtensionWrapper.java ================================================ package com.kumuluz.ee.common.wrapper; import com.kumuluz.ee.common.Extension; import com.kumuluz.ee.common.dependencies.EeComponentDependency; import com.kumuluz.ee.common.dependencies.EeComponentOptional; public class ExtensionWrapper { private T extension; private String name; private String group; private EeComponentDependency[] dependencies; private EeComponentOptional[] optionalDependencies; public ExtensionWrapper(T extension, String name, String group, EeComponentDependency[] dependencies, EeComponentOptional[] optionalDependencies) { this.extension = extension; this.name = name; this.group = group; this.dependencies = dependencies; this.optionalDependencies = optionalDependencies; } public T getExtension() { return extension; } public void setExtension(T extension) { this.extension = extension; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getGroup() { return group; } public void setGroup(String group) { this.group = group; } public EeComponentDependency[] getDependencies() { return dependencies; } public void setDependencies(EeComponentDependency[] dependencies) { this.dependencies = dependencies; } public EeComponentOptional[] getOptionalDependencies() { return optionalDependencies; } public void setOptionalDependencies(EeComponentOptional[] optionalDependencies) { this.optionalDependencies = optionalDependencies; } } ================================================ FILE: common/src/main/java/com/kumuluz/ee/common/wrapper/KumuluzServerWrapper.java ================================================ /* * Copyright (c) 2014-2017 Kumuluz and/or its affiliates * and other contributors as indicated by the @author tags and * the contributor list. * * Licensed under the MIT License (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://opensource.org/licenses/MIT * * The software is provided "AS IS", WITHOUT WARRANTY OF ANY KIND, express or * implied, including but not limited to the warranties of merchantability, * fitness for a particular purpose and noninfringement. in no event shall the * authors or copyright holders be liable for any claim, damages or other * liability, whether in an action of contract, tort or otherwise, arising from, * out of or in connection with the software or the use or other dealings in the * software. See the License for the specific language governing permissions and * limitations under the License. */ package com.kumuluz.ee.common.wrapper; import com.kumuluz.ee.common.KumuluzServer; import com.kumuluz.ee.common.dependencies.EeComponentType; import java.util.List; /** * @author Tilen Faganel * @since 2.0.0 */ public class KumuluzServerWrapper { private KumuluzServer server; private String name; private EeComponentType[] providedEeComponents; public KumuluzServerWrapper(KumuluzServer server, String name, EeComponentType[] providedEeComponents) { this.server = server; this.name = name; this.providedEeComponents = providedEeComponents; } public KumuluzServer getServer() { return server; } public void setServer(KumuluzServer server) { this.server = server; } public String getName() { return name; } public void setName(String name) { this.name = name; } public EeComponentType[] getProvidedEeComponents() { return providedEeComponents; } public void setProvidedEeComponents(EeComponentType[] providedEeComponents) { this.providedEeComponents = providedEeComponents; } } ================================================ FILE: common/src/main/java/com/kumuluz/ee/configuration/ConfigurationDecoder.java ================================================ /* * Copyright (c) 2014-2019 Kumuluz and/or its affiliates * and other contributors as indicated by the @author tags and * the contributor list. * * Licensed under the MIT License (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://opensource.org/licenses/MIT * * The software is provided "AS IS", WITHOUT WARRANTY OF ANY KIND, express or * implied, including but not limited to the warranties of merchantability, * fitness for a particular purpose and noninfringement. in no event shall the * authors or copyright holders be liable for any claim, damages or other * liability, whether in an action of contract, tort or otherwise, arising from, * out of or in connection with the software or the use or other dealings in the * software. See the License for the specific language governing permissions and * limitations under the License. */ package com.kumuluz.ee.configuration; /** * Optional implementation of this interface can be registered as * a service provider to implement decoding of certain configuration keys' values. * * @author Jan Meznarič * @since 3.2.1 */ public interface ConfigurationDecoder { /** * Check if key's value should be decoded. * * @param key configuration key to be checked for decoding * @return returns true if key's value should be decoded with the decode(String key, String value) method */ boolean shouldDecode(String key); /** * Decode values of encoded keys. * * @param key encoded key * @param value encoded value * @return decoded value */ String decode(String key, String value); } ================================================ FILE: common/src/main/java/com/kumuluz/ee/configuration/ConfigurationListener.java ================================================ /* * Copyright (c) 2014-2017 Kumuluz and/or its affiliates * and other contributors as indicated by the @author tags and * the contributor list. * * Licensed under the MIT License (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://opensource.org/licenses/MIT * * The software is provided "AS IS", WITHOUT WARRANTY OF ANY KIND, express or * implied, including but not limited to the warranties of merchantability, * fitness for a particular purpose and noninfringement. in no event shall the * authors or copyright holders be liable for any claim, damages or other * liability, whether in an action of contract, tort or otherwise, arising from, * out of or in connection with the software or the use or other dealings in the * software. See the License for the specific language governing permissions and * limitations under the License. */ package com.kumuluz.ee.configuration; /** * @author Tilen Faganel * @since 2.3.0 */ @FunctionalInterface public interface ConfigurationListener { void onChange(String key, String value); } ================================================ FILE: common/src/main/java/com/kumuluz/ee/configuration/ConfigurationSource.java ================================================ /* * Copyright (c) 2014-2017 Kumuluz and/or its affiliates * and other contributors as indicated by the @author tags and * the contributor list. * * Licensed under the MIT License (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://opensource.org/licenses/MIT * * The software is provided "AS IS", WITHOUT WARRANTY OF ANY KIND, express or * implied, including but not limited to the warranties of merchantability, * fitness for a particular purpose and noninfringement. in no event shall the * authors or copyright holders be liable for any claim, damages or other * liability, whether in an action of contract, tort or otherwise, arising from, * out of or in connection with the software or the use or other dealings in the * software. See the License for the specific language governing permissions and * limitations under the License. */ package com.kumuluz.ee.configuration; import com.kumuluz.ee.configuration.utils.ConfigurationDispatcher; import java.util.List; import java.util.Optional; /** * @author Tilen Faganel * @since 2.1.0 */ public interface ConfigurationSource { String CONFIG_ORDINAL = "config_ordinal"; void init(ConfigurationDispatcher configurationDispatcher); Optional get(String key); default Optional getBoolean(String key) { Optional value = get(key); return value.map(Boolean::valueOf); } default Optional getInteger(String key) { Optional value = get(key); if (value.isPresent()) { try { return Optional.of(Integer.valueOf(value.get())); } catch (NumberFormatException e) { return Optional.empty(); } } else { return Optional.empty(); } } default Optional getLong(String key) { Optional value = get(key); if (value.isPresent()) { try { return Optional.of(Long.valueOf(value.get())); } catch (NumberFormatException e) { return Optional.empty(); } } else { return Optional.empty(); } } default Optional getDouble(String key) { Optional value = get(key); if (value.isPresent()) { try { return Optional.of(Double.valueOf(value.get())); } catch (NumberFormatException e) { return Optional.empty(); } } else { return Optional.empty(); } } default Optional getFloat(String key) { Optional value = get(key); if (value.isPresent()) { try { return Optional.of(Float.valueOf(value.get())); } catch (NumberFormatException e) { return Optional.empty(); } } else { return Optional.empty(); } } Optional getListSize(String key); Optional> getMapKeys(String key); void watch(String key); void set(String key, String value); void set(String key, Boolean value); void set(String key, Integer value); void set(String key, Double value); void set(String key, Float value); default Integer getOrdinal() { return getInteger(CONFIG_ORDINAL).orElse(100); } default void postInit() {} default void initProfile(String profileName) {} } ================================================ FILE: common/src/main/java/com/kumuluz/ee/configuration/enums/ConfigurationValueType.java ================================================ /* * Copyright (c) 2014-2017 Kumuluz and/or its affiliates * and other contributors as indicated by the @author tags and * the contributor list. * * Licensed under the MIT License (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://opensource.org/licenses/MIT * * The software is provided "AS IS", WITHOUT WARRANTY OF ANY KIND, express or * implied, including but not limited to the warranties of merchantability, * fitness for a particular purpose and noninfringement. in no event shall the * authors or copyright holders be liable for any claim, damages or other * liability, whether in an action of contract, tort or otherwise, arising from, * out of or in connection with the software or the use or other dealings in the * software. See the License for the specific language governing permissions and * limitations under the License. */ package com.kumuluz.ee.configuration.enums; /** * @author Jan Meznarič * @since 2.3.0 */ public enum ConfigurationValueType { STRING, INTEGER, LONG, DOUBLE, FLOAT, BOOLEAN, LIST, MAP } ================================================ FILE: common/src/main/java/com/kumuluz/ee/configuration/sources/EnvironmentConfigurationSource.java ================================================ /* * Copyright (c) 2014-2017 Kumuluz and/or its affiliates * and other contributors as indicated by the @author tags and * the contributor list. * * Licensed under the MIT License (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://opensource.org/licenses/MIT * * The software is provided "AS IS", WITHOUT WARRANTY OF ANY KIND, express or * implied, including but not limited to the warranties of merchantability, * fitness for a particular purpose and noninfringement. in no event shall the * authors or copyright holders be liable for any claim, damages or other * liability, whether in an action of contract, tort or otherwise, arising from, * out of or in connection with the software or the use or other dealings in the * software. See the License for the specific language governing permissions and * limitations under the License. */ package com.kumuluz.ee.configuration.sources; import com.kumuluz.ee.configuration.ConfigurationSource; import com.kumuluz.ee.configuration.utils.ConfigurationDispatcher; import java.util.*; /** * @author Tilen Faganel * @since 2.1.0 */ public class EnvironmentConfigurationSource implements ConfigurationSource { @Override public void init(ConfigurationDispatcher configurationDispatcher) { } @Override public Optional get(String key) { String value = null; for (String possibleName : getPossibleEnvNames(key)) { value = System.getenv(possibleName); if (value != null) { break; } } return Optional.ofNullable(value); } @Override public Optional getListSize(String key) { for (String possibleKeyName : getPossibleEnvNames(key)) { int maxIndex = -1; for (String envName : System.getenv().keySet()) { if (envName.startsWith(possibleKeyName)) { int openingIndex = possibleKeyName.length(); int closingIndex = envName.indexOf("_", openingIndex + 1); if (closingIndex < 0) { closingIndex = envName.length(); } try { int idx = Integer.parseInt(envName.substring(openingIndex, closingIndex)); maxIndex = Math.max(maxIndex, idx); } catch (NumberFormatException ignored) { } } } if (maxIndex != -1) { return Optional.of(maxIndex + 1); } // retry for legacy key names for (String envName : System.getenv().keySet()) { if (envName.startsWith(possibleKeyName)) { int openingIndex = possibleKeyName.length() + 1; int closingIndex = envName.indexOf("]", openingIndex + 1); if (closingIndex < 0) { closingIndex = envName.indexOf("_", openingIndex + 1); } if (closingIndex < 0) { closingIndex = envName.length() - 1; } if (openingIndex >= closingIndex) { continue; } try { int idx = Integer.parseInt(envName.substring(openingIndex, closingIndex)); maxIndex = Math.max(maxIndex, idx); } catch (NumberFormatException ignored) { } } } if (maxIndex != -1) { return Optional.of(maxIndex + 1); } } return Optional.empty(); } @Override public Optional> getMapKeys(String key) { Set mapKeys = new HashSet<>(); Set envKeys = new HashSet<>(System.getenv().keySet()); List possibleKeyNames = (key.equals("")) ? Collections.singletonList("") : getPossibleEnvNames(key); for (String possibleKeyName : possibleKeyNames) { Set toRemove = new HashSet<>(); for (String envKey : envKeys) { if (!possibleKeyName.equals("") && possibleKeyName.length() + 1 > envKey.length()) { continue; } if (envKey.startsWith(possibleKeyName)) { int separatorIdx; int startIdx; if (possibleKeyName.equals("")) { int dotIdx = envKey.indexOf('.'); int underscoreIdx = envKey.indexOf('_'); if (dotIdx > 0 && underscoreIdx > 0) { // both defined, pick earliest separatorIdx = Math.min(dotIdx, underscoreIdx); } else { // at least one is -1 separatorIdx = Math.max(dotIdx, underscoreIdx); } startIdx = 0; } else { char separator = envKey.charAt(possibleKeyName.length()); if (separator != '.' && separator != '_') { continue; } startIdx = possibleKeyName.length() + 1; separatorIdx = envKey.indexOf(separator, startIdx); } if (separatorIdx < 0) { // no separators left, use full key separatorIdx = envKey.length(); } String mapKey = envKey.substring(startIdx, separatorIdx); if (!mapKey.isEmpty()) { int bracketIndex = mapKey.indexOf("["); if (bracketIndex > 0) { // list bracket present, cut it off mapKey = mapKey.substring(0, bracketIndex); } mapKeys.add(mapKey.toLowerCase()); toRemove.add(envKey); } } } envKeys.removeAll(toRemove); } if (mapKeys.size() == 0) { return Optional.empty(); } else { return Optional.of(new ArrayList<>(mapKeys)); } } @Override public void watch(String key) { } @Override public void set(String key, String value) { } @Override public void set(String key, Boolean value) { } @Override public void set(String key, Integer value) { } @Override public void set(String key, Double value) { } @Override public void set(String key, Float value) { } @Override public Integer getOrdinal() { return getInteger(CONFIG_ORDINAL).orElse(300); } private List getPossibleEnvNames(String key) { List possibleNames = new LinkedList<>(); // MP Config 1.3: raw key possibleNames.add(key); // MP Config 1.3: replaces non alpha-numeric characters with '_' possibleNames.add(replaceNonAlphaNum(key)); // MP Config 1.3: replaces non alpha-numeric characters with '_', to uppercase possibleNames.add(replaceNonAlphaNum(key).toUpperCase()); // legacy 1: removes characters '[]-' and replaces dots with '_', to uppercase possibleNames.add(parseKeyNameForEnvironmentVariables(key)); // legacy 2: replaces dots with '_', to uppercase possibleNames.add(parseKeyNameForEnvironmentVariablesLegacy(key)); return possibleNames; } private String replaceNonAlphaNum(String s) { return s.replaceAll("[^a-zA-Z0-9]", "_"); } private String parseKeyNameForEnvironmentVariables(String key) { return key.toUpperCase().replaceAll("\\[", "").replaceAll("]", "") .replaceAll("-", "").replaceAll("\\.", "_"); } private String parseKeyNameForEnvironmentVariablesLegacy(String key) { return key.toUpperCase().replaceAll("\\.", "_"); } } ================================================ FILE: common/src/main/java/com/kumuluz/ee/configuration/sources/FileConfigurationSource.java ================================================ /* * Copyright (c) 2014-2017 Kumuluz and/or its affiliates * and other contributors as indicated by the @author tags and * the contributor list. * * Licensed under the MIT License (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://opensource.org/licenses/MIT * * The software is provided "AS IS", WITHOUT WARRANTY OF ANY KIND, express or * implied, including but not limited to the warranties of merchantability, * fitness for a particular purpose and noninfringement. in no event shall the * authors or copyright holders be liable for any claim, damages or other * liability, whether in an action of contract, tort or otherwise, arising from, * out of or in connection with the software or the use or other dealings in the * software. See the License for the specific language governing permissions and * limitations under the License. */ package com.kumuluz.ee.configuration.sources; import com.kumuluz.ee.configuration.ConfigurationSource; import com.kumuluz.ee.configuration.utils.ConfigurationDispatcher; import com.kumuluz.ee.configuration.utils.ConfigurationSourceUtils; import com.kumuluz.ee.logs.LogDeferrer; import org.yaml.snakeyaml.Yaml; import java.io.IOException; import java.io.InputStream; import java.nio.file.Files; import java.nio.file.Paths; import java.util.*; import java.util.logging.Logger; import java.util.stream.Collectors; /** * @author Tilen Faganel * @since 2.1.0 */ public class FileConfigurationSource implements ConfigurationSource { private enum Mode { YAML, PROPERTIES } private Logger log; private LogDeferrer logDeferrer; private String ymlFileName; private String yamlFileName; private String propertiesFileName; private final String microProfilePropertiesFileName; private final List> yamlConfigs = new ArrayList<>(); private final List properties = new ArrayList<>(); private Mode mode; public FileConfigurationSource() { this.ymlFileName = "config.yml"; this.yamlFileName = "config.yaml"; this.propertiesFileName = "config.properties"; this.microProfilePropertiesFileName = "META-INF/microprofile-config.properties"; String configurationFileName = System.getProperty("com.kumuluz.ee.configuration.file"); if (configurationFileName != null && !configurationFileName.isEmpty()) { this.ymlFileName = configurationFileName; this.yamlFileName = null; this.propertiesFileName = configurationFileName; } this.logDeferrer = new LogDeferrer<>(); this.logDeferrer.init(() -> Logger.getLogger(FileConfigurationSource.class.getName())); } public void postInit() { logDeferrer.execute(); logDeferrer = null; log = Logger.getLogger(FileConfigurationSource.class.getName()); } @Override public void init(ConfigurationDispatcher configurationDispatcher) { // read yaml file to Map Map yamlConfig = loadYamlFile(this.ymlFileName, this.yamlFileName); if (yamlConfig != null) { this.yamlConfigs.add(yamlConfig); this.mode = Mode.YAML; } else { // parse properties file Properties p = loadProperties(propertiesFileName); if (p == null) { p = loadProperties(microProfilePropertiesFileName); } if (p != null) { this.properties.add(p); this.mode = Mode.PROPERTIES; } } if (!yamlConfigs.isEmpty() || !properties.isEmpty()) { logDeferrer.defer(l -> l.info("Configuration successfully read.")); } else { logDeferrer.defer(l -> l.info("Unable to load configuration from file. " + "No configuration files were found.")); } } @Override public void initProfile(String profileName) { if (mode == Mode.YAML) { Map yamlConfig = loadYamlFile("config-" + profileName + ".yml", "config-" + profileName + ".yaml"); if (yamlConfig != null) { this.yamlConfigs.add(0, yamlConfig); } } else if (mode == Mode.PROPERTIES) { Properties p = loadProperties("config-" + profileName + ".properties"); if (p == null) { p = loadProperties("META-INF/microprofile-config-" + profileName + ".properties"); } if (p != null) { this.properties.add(0, p); } } } @Override public Optional get(String key) { // get key value from yaml configuration if (mode == Mode.YAML) { Object value; for (var config : this.yamlConfigs) { value = getYamlValue(key, config); if (value != null && !(value instanceof Map) && !(value instanceof List)) { return Optional.of(value.toString()); } } return Optional.empty(); // get value from .properties configuration } else if (mode == Mode.PROPERTIES) { for (Properties properties : this.properties) { String value = properties.getProperty(key); if (value != null) { return Optional.of(value); } } return Optional.empty(); } return Optional.empty(); } @Override public Optional getListSize(String key) { if (mode == Mode.YAML) { Integer maxSize = null; for (var config : this.yamlConfigs) { Object value = getYamlValue(key, config); if (value instanceof List) { if (maxSize == null) { maxSize = ((List) value).size(); } else { maxSize = Math.max(((List) value).size(), maxSize); } } } return Optional.ofNullable(maxSize); } else if (mode == Mode.PROPERTIES) { Integer maxSize = null; for (Properties properties : this.properties) { Optional propertyListSize = ConfigurationSourceUtils.getListSize(key, properties.stringPropertyNames()); if (propertyListSize.isPresent()) { if (maxSize == null) { maxSize = propertyListSize.get(); } else { maxSize = Math.max(propertyListSize.get(), maxSize); } } } return Optional.ofNullable(maxSize); } return Optional.empty(); } @Override @SuppressWarnings("unchecked") public Optional> getMapKeys(String key) { if (mode == Mode.YAML) { boolean found = false; Set mergedKeys = new HashSet<>(); for (var config : this.yamlConfigs) { Object o = (key.equals("")) ? config : getYamlValue(key, config); Map map = null; if (o instanceof Map) { map = (Map) o; } if (map != null && !map.isEmpty()) { found = true; mergedKeys.addAll(map.keySet()); } } if (found) { return Optional.of(new ArrayList<>(mergedKeys)); } else { return Optional.empty(); } } else if (mode == Mode.PROPERTIES) { boolean found = false; Set mergedKeys = new HashSet<>(); for (Properties properties : this.properties) { Optional> propertyMapKeys = ConfigurationSourceUtils.getMapKeys(key, properties.stringPropertyNames()); if (propertyMapKeys.isPresent()) { found = true; mergedKeys.addAll(propertyMapKeys.get()); } } if (found) { return Optional.of(new ArrayList<>(mergedKeys)); } else { return Optional.empty(); } } return Optional.empty(); } @Override public void watch(String key) { } @Override public void set(String key, String value) { } @Override public void set(String key, Boolean value) { } @Override public void set(String key, Integer value) { } @Override public void set(String key, Double value) { } @Override public void set(String key, Float value) { } @Override public Integer getOrdinal() { return getInteger(CONFIG_ORDINAL).orElse(100); } /** * Returns true, if key represents an array. * * @param key configuration key * @return true if the config key represents an array, false otherwise. */ private boolean representsArray(String key) { int openingBracket = key.indexOf("["); int closingBracket = key.indexOf("]"); return closingBracket == key.length() - 1 && openingBracket != -1; } /** * Parses configuration map, returns value for given key. * * @param key configuration key * @return Value for given key. */ private Object getYamlValue(String key, Object value) { // iterate over configuration tree String[] splittedKeys = key.split("\\."); for (int i = 0; i < splittedKeys.length; i++) { String splittedKey = splittedKeys[i]; if (value == null) { return null; } // parse arrays if (representsArray(splittedKey)) { // value array support int arrayIndex; int openingBracket = splittedKey.indexOf("["); int closingBracket = splittedKey.indexOf("]"); try { arrayIndex = Integer.parseInt(splittedKey.substring(openingBracket + 1, closingBracket)); } catch (NumberFormatException e) { if (log != null) { log.severe("Cannot cast array index."); } return null; } splittedKey = splittedKey.substring(0, openingBracket); if (value instanceof Map) { value = ((Map) value).get(splittedKey); } else { return null; } if (value instanceof List) { value = (arrayIndex < ((List) value).size()) ? ((List) value).get(arrayIndex) : null; } } else { if (value instanceof Map) { Object tmpValue = ((Map) value).get(splittedKey); if (tmpValue == null && i != splittedKeys.length - 1) { String postfixKey = Arrays.stream(splittedKeys).skip(i) .collect(Collectors.joining(".")); return ((Map) value).get(postfixKey); } else { value = tmpValue; } } else { return null; } } } return value; } private Map loadYamlFile(String fileNameYml, String fileNameYaml) { InputStream file = null; Yaml yaml = new Yaml(); try { file = getClass().getClassLoader().getResourceAsStream(fileNameYml); if (file == null && fileNameYaml != null) { file = getClass().getClassLoader().getResourceAsStream(fileNameYaml); } if (file == null) { try { file = Files.newInputStream(Paths.get(fileNameYml)); } catch (IOException ignored) { } } if (file == null && fileNameYaml != null) { try { file = Files.newInputStream(Paths.get(fileNameYaml)); } catch (IOException ignored) { } } if (file != null) { logDeferrer.defer(l -> l.info("Loading configuration from YAML file.")); Object yamlParsed = yaml.load(file); if (yamlParsed instanceof Map) { //noinspection unchecked return (Map) yamlParsed; } else { logDeferrer.defer(l -> l.info("Configuration YAML is malformed as it contains an array at the " + "root level. Skipping.")); } } return null; } catch (Exception e) { logDeferrer.defer(l -> l.info("Couldn't successfully process the YAML configuration file. " + "All your properties may not be correctly loaded.")); return null; } finally { if (file != null) { try { file.close(); } catch (IOException ignored) { } } } } private Properties loadProperties(String fileName) { InputStream inputStream = null; try { inputStream = getClass().getClassLoader().getResourceAsStream(fileName); if (inputStream == null) { try { inputStream = Files.newInputStream(Paths.get(fileName)); } catch (IOException ignored) { } } if (inputStream != null) { logDeferrer.defer(l -> l.info("Loading configuration from .properties file: " + fileName)); Properties p = new Properties(); p.load(inputStream); return p; } } catch (Exception e) { logDeferrer.defer(l -> l.info("Properties file: " + fileName + " not found.")); } finally { if (inputStream != null) { try { inputStream.close(); } catch (IOException ignored) { } } } return null; } } ================================================ FILE: common/src/main/java/com/kumuluz/ee/configuration/sources/SystemPropertyConfigurationSource.java ================================================ /* * Copyright (c) 2014-2017 Kumuluz and/or its affiliates * and other contributors as indicated by the @author tags and * the contributor list. * * Licensed under the MIT License (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://opensource.org/licenses/MIT * * The software is provided "AS IS", WITHOUT WARRANTY OF ANY KIND, express or * implied, including but not limited to the warranties of merchantability, * fitness for a particular purpose and noninfringement. in no event shall the * authors or copyright holders be liable for any claim, damages or other * liability, whether in an action of contract, tort or otherwise, arising from, * out of or in connection with the software or the use or other dealings in the * software. See the License for the specific language governing permissions and * limitations under the License. */ package com.kumuluz.ee.configuration.sources; import com.kumuluz.ee.configuration.ConfigurationSource; import com.kumuluz.ee.configuration.utils.ConfigurationDispatcher; import com.kumuluz.ee.configuration.utils.ConfigurationSourceUtils; import java.util.List; import java.util.Optional; /** * @author Urban Malc * @since 2.4.0 */ public class SystemPropertyConfigurationSource implements ConfigurationSource { @Override public void init(ConfigurationDispatcher configurationDispatcher) { } @Override public Optional get(String key) { return Optional.ofNullable(System.getProperty(key)); } @Override public Optional getListSize(String key) { return ConfigurationSourceUtils.getListSize(key, System.getProperties().stringPropertyNames()); } @Override public Optional> getMapKeys(String key) { return ConfigurationSourceUtils.getMapKeys(key, System.getProperties().stringPropertyNames()); } @Override public void watch(String key) { } @Override public void set(String key, String value) { } @Override public void set(String key, Boolean value) { } @Override public void set(String key, Integer value) { } @Override public void set(String key, Double value) { } @Override public void set(String key, Float value) { } @Override public Integer getOrdinal() { return getInteger(CONFIG_ORDINAL).orElse(400); } } ================================================ FILE: common/src/main/java/com/kumuluz/ee/configuration/utils/ConfigurationDecoderUtils.java ================================================ /* * Copyright (c) 2014-2019 Kumuluz and/or its affiliates * and other contributors as indicated by the @author tags and * the contributor list. * * Licensed under the MIT License (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://opensource.org/licenses/MIT * * The software is provided "AS IS", WITHOUT WARRANTY OF ANY KIND, express or * implied, including but not limited to the warranties of merchantability, * fitness for a particular purpose and noninfringement. in no event shall the * authors or copyright holders be liable for any claim, damages or other * liability, whether in an action of contract, tort or otherwise, arising from, * out of or in connection with the software or the use or other dealings in the * software. See the License for the specific language governing permissions and * limitations under the License. */ package com.kumuluz.ee.configuration.utils; import com.kumuluz.ee.configuration.ConfigurationDecoder; /** * Util methods for decoding encoded configuration keys. * * @author Jan Meznarič * @since 3.2.1 */ public class ConfigurationDecoderUtils { public static String decodeConfigValueIfEncoded(String key, String value) { ConfigurationDecoder configurationDecoder = ConfigurationUtil.getInstance().getConfigurationDecoder(); if (configurationDecoder != null && configurationDecoder.shouldDecode(key)) { return configurationDecoder.decode(key, value); } return value; } } ================================================ FILE: common/src/main/java/com/kumuluz/ee/configuration/utils/ConfigurationDispatcher.java ================================================ /* * Copyright (c) 2014-2017 Kumuluz and/or its affiliates * and other contributors as indicated by the @author tags and * the contributor list. * * Licensed under the MIT License (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://opensource.org/licenses/MIT * * The software is provided "AS IS", WITHOUT WARRANTY OF ANY KIND, express or * implied, including but not limited to the warranties of merchantability, * fitness for a particular purpose and noninfringement. in no event shall the * authors or copyright holders be liable for any claim, damages or other * liability, whether in an action of contract, tort or otherwise, arising from, * out of or in connection with the software or the use or other dealings in the * software. See the License for the specific language governing permissions and * limitations under the License. */ package com.kumuluz.ee.configuration.utils; import com.kumuluz.ee.configuration.ConfigurationListener; import java.util.ArrayList; import java.util.List; /** * @author Tilen Faganel * @since 2.3.0 */ // Fire configuration events and notify subscription public class ConfigurationDispatcher { private List subscriptions = new ArrayList<>(); public void notifyChange(String key, String value) { for (ConfigurationListener subscription : subscriptions) { subscription.onChange(key, value); } } public void subscribe(ConfigurationListener listener) { subscriptions.add(listener); } public void unsubscribe(ConfigurationListener listener) { subscriptions.remove(listener); } } ================================================ FILE: common/src/main/java/com/kumuluz/ee/configuration/utils/ConfigurationImpl.java ================================================ /* * Copyright (c) 2014-2019 Kumuluz and/or its affiliates * and other contributors as indicated by the @author tags and * the contributor list. * * Licensed under the MIT License (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://opensource.org/licenses/MIT * * The software is provided "AS IS", WITHOUT WARRANTY OF ANY KIND, express or * implied, including but not limited to the warranties of merchantability, * fitness for a particular purpose and noninfringement. in no event shall the * authors or copyright holders be liable for any claim, damages or other * liability, whether in an action of contract, tort or otherwise, arising from, * out of or in connection with the software or the use or other dealings in the * software. See the License for the specific language governing permissions and * limitations under the License. */ package com.kumuluz.ee.configuration.utils; import java.util.ArrayList; import java.util.List; import java.util.ServiceLoader; import java.util.logging.Logger; import com.kumuluz.ee.configuration.ConfigurationDecoder; import com.kumuluz.ee.configuration.ConfigurationSource; /** * @author Tilen Faganel * @since 2.1.0 */ public class ConfigurationImpl { private Logger utilLogger; private ConfigurationDispatcher dispatcher; private List configurationSources; private ConfigurationDecoder configurationDecoder; public ConfigurationImpl() { init(); } private void init() { // specify sources configurationSources = new ArrayList<>(); ServiceLoader.load(ConfigurationSource.class).forEach(configurationSources::add); dispatcher = new ConfigurationDispatcher(); configurationSources.forEach(configurationSource -> configurationSource.init(dispatcher)); // initialise configuration decoder List configurationDecoders = new ArrayList<>(); ServiceLoader.load(ConfigurationDecoder.class).forEach(configurationDecoders::add); if (configurationDecoders.size() > 1) { throw new IllegalStateException( "There is more than one service provider defined for the ConfigurationDecoder interface."); } else if (configurationDecoders.size() == 1) { configurationDecoder = configurationDecoders.get(0); } } public void postInit() { configurationSources.forEach(ConfigurationSource::postInit); utilLogger = Logger.getLogger(ConfigurationUtil.class.getName()); } public Boolean isUtilLoggerAvailable() { return utilLogger != null; } public Logger getUtilLogger() { return utilLogger; } public ConfigurationDispatcher getDispatcher() { return dispatcher; } public List getConfigurationSources() { return configurationSources; } public ConfigurationDecoder getConfigurationDecoder() { return configurationDecoder; } } ================================================ FILE: common/src/main/java/com/kumuluz/ee/configuration/utils/ConfigurationInterpolationUtil.java ================================================ package com.kumuluz.ee.configuration.utils; import java.util.NoSuchElementException; import java.util.Optional; import java.util.function.Function; import java.util.regex.Matcher; /** * Utility for performing configuration value interpolation. Independent from the actual config resolver, since it can * be used in kumuluzee-config-mp. The interpolation (syntax, default values, etc.) is performed according to the * MicroProfile Config specification. * * @author Urban Malc * @since 4.1.0 */ public class ConfigurationInterpolationUtil { public static String interpolateString(String value, Function> configResolver) { int numberOfReplacements = 0; InterpolationLocation interpolationLocation = getInnermostInterpolation(value); while (interpolationLocation != null) { if (numberOfReplacements > 10) { throw new IllegalArgumentException("Reached maximum limit of interpolations when interpolating value: " + value); } String interpolationKey = value.substring(interpolationLocation.startIndex + 2, interpolationLocation.endIndex); String defaultValue = null; if (interpolationKey.contains(":")) { String[] tokens = interpolationKey.split(":", 2); interpolationKey = tokens[0]; defaultValue = tokens[1]; } String finalDefaultValue = defaultValue; Optional replacement = configResolver .apply(interpolationKey) .or(() -> Optional.ofNullable(finalDefaultValue)); if (replacement.isEmpty()) { throw new NoSuchElementException("Could not resolve interpolation: " + interpolationKey); } value = value.substring(0, interpolationLocation.startIndex) + replacement.get() + value.substring(interpolationLocation.endIndex + 1); numberOfReplacements++; interpolationLocation = getInnermostInterpolation(value); } return value.replaceAll("\\\\\\$\\{", Matcher.quoteReplacement("${")); // replace \${ with ${ } private static InterpolationLocation getInnermostInterpolation(String value) { Integer startIndex = null; for (int i = 0; i < value.length(); i++) { if (value.charAt(i) == '}' && startIndex != null) { return new InterpolationLocation(startIndex, i); } if (i < value.length() - 1 && value.charAt(i) == '$' && value.charAt(i + 1) == '{' && (i == 0 || value.charAt(i - 1) != '\\')) { startIndex = i; } } return null; } private static class InterpolationLocation { private final int startIndex; private final int endIndex; public InterpolationLocation(int startIndex, int endIndex) { this.startIndex = startIndex; this.endIndex = endIndex; } } } ================================================ FILE: common/src/main/java/com/kumuluz/ee/configuration/utils/ConfigurationSourceUtils.java ================================================ /* * Copyright (c) 2014-2017 Kumuluz and/or its affiliates * and other contributors as indicated by the @author tags and * the contributor list. * * Licensed under the MIT License (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://opensource.org/licenses/MIT * * The software is provided "AS IS", WITHOUT WARRANTY OF ANY KIND, express or * implied, including but not limited to the warranties of merchantability, * fitness for a particular purpose and noninfringement. in no event shall the * authors or copyright holders be liable for any claim, damages or other * liability, whether in an action of contract, tort or otherwise, arising from, * out of or in connection with the software or the use or other dealings in the * software. See the License for the specific language governing permissions and * limitations under the License. */ package com.kumuluz.ee.configuration.utils; import java.util.*; /** * @author Urban Malc * @since 2.5.0 */ public class ConfigurationSourceUtils { public static Optional getListSize(String key, Collection allKeys) { int maxIndex = -1; for (String propertyKey : allKeys) { if (propertyKey.startsWith(key + "[")) { int openingIndex = key.length() + 1; int closingIndex = propertyKey.indexOf("]", openingIndex + 1); try { int idx = Integer.parseInt(propertyKey.substring(openingIndex, closingIndex)); maxIndex = Math.max(maxIndex, idx); } catch (NumberFormatException ignored) { } } } if (maxIndex != -1) { return Optional.of(maxIndex + 1); } return Optional.empty(); } public static Optional> getMapKeys(String key, Collection allKeys) { Set mapKeys = new HashSet<>(); for (String propertyKey : allKeys) { String mapKey = ""; if (key.isEmpty()) { mapKey = propertyKey; } else if (propertyKey.startsWith(key)) { int index = key.length() + 1; if (index < propertyKey.length() && propertyKey.charAt(index - 1) == '.') { mapKey = propertyKey.substring(index); } } if (!mapKey.isEmpty()) { int endIndex = mapKey.indexOf("."); if (endIndex > 0) { mapKey = mapKey.substring(0, endIndex); } int bracketIndex = mapKey.indexOf("["); if (bracketIndex > 0) { mapKey = mapKey.substring(0, bracketIndex); } mapKeys.add(mapKey); } } if (mapKeys.isEmpty()) { return Optional.empty(); } return Optional.of(new ArrayList<>(mapKeys)); } } ================================================ FILE: common/src/main/java/com/kumuluz/ee/configuration/utils/ConfigurationUtil.java ================================================ /* * Copyright (c) 2014-2019 Kumuluz and/or its affiliates * and other contributors as indicated by the @author tags and * the contributor list. * * Licensed under the MIT License (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://opensource.org/licenses/MIT * * The software is provided "AS IS", WITHOUT WARRANTY OF ANY KIND, express or * implied, including but not limited to the warranties of merchantability, * fitness for a particular purpose and noninfringement. in no event shall the * authors or copyright holders be liable for any claim, damages or other * liability, whether in an action of contract, tort or otherwise, arising from, * out of or in connection with the software or the use or other dealings in the * software. See the License for the specific language governing permissions and * limitations under the License. */ package com.kumuluz.ee.configuration.utils; import com.kumuluz.ee.configuration.ConfigurationDecoder; import com.kumuluz.ee.configuration.ConfigurationListener; import com.kumuluz.ee.configuration.ConfigurationSource; import com.kumuluz.ee.configuration.enums.ConfigurationValueType; import java.util.*; /** * @author Tilen Faganel * @since 2.1.0 */ public class ConfigurationUtil { private static ConfigurationUtil instance; private ConfigurationImpl config; protected ConfigurationUtil() { } private ConfigurationUtil(ConfigurationImpl config) { this.config = config; } public static void initialize(ConfigurationImpl config) { if (instance != null) { throw new IllegalStateException("The ConfigurationUtil was already initialized."); } instance = new ConfigurationUtil(config); } public static ConfigurationUtil getInstance() { if (instance == null) { throw new IllegalStateException("The ConfigurationUtil was not yet initialized."); } return instance; } public Optional get(String key) { for (ConfigurationSource configurationSource : config.getConfigurationSources()) { Optional value = configurationSource.get(key); if (value.isPresent()) { return Optional.of(ConfigurationInterpolationUtil.interpolateString( ConfigurationDecoderUtils.decodeConfigValueIfEncoded(key, value.get()), this::get)); } } return Optional.empty(); } public Optional getRaw(String key) { for (ConfigurationSource configurationSource : config.getConfigurationSources()) { Optional value = configurationSource.get(key); if (value.isPresent()) { return value; } } return Optional.empty(); } public Optional getBoolean(String key) { for (ConfigurationSource configurationSource : config.getConfigurationSources()) { Optional value = configurationSource.getBoolean(key); if (value.isPresent()) { return value; } } return Optional.empty(); } public Optional getInteger(String key) { for (ConfigurationSource configurationSource : config.getConfigurationSources()) { Optional value = configurationSource.getInteger(key); if (value.isPresent()) { return value; } } return Optional.empty(); } public Optional getLong(String key) { for (ConfigurationSource configurationSource : config.getConfigurationSources()) { Optional value = configurationSource.getLong(key); if (value.isPresent()) { return value; } } return Optional.empty(); } public Optional getDouble(String key) { for (ConfigurationSource configurationSource : config.getConfigurationSources()) { Optional value = configurationSource.getDouble(key); if (value.isPresent()) { return value; } } return Optional.empty(); } public Optional getFloat(String key) { for (ConfigurationSource configurationSource : config.getConfigurationSources()) { Optional value = configurationSource.getFloat(key); if (value.isPresent()) { return value; } } return Optional.empty(); } public Optional getListSize(String key) { int listSize = -1; for (ConfigurationSource configurationSource : config.getConfigurationSources()) { Optional currentListSize = configurationSource.getListSize(key); if (currentListSize.isPresent() && currentListSize.get() > listSize) { listSize = currentListSize.get(); } } if (listSize == -1) { return Optional.empty(); } else { return Optional.of(listSize); } } public Optional> getList(String key) { Optional listSize = getListSize(key); if (!listSize.isPresent()) { return Optional.empty(); } List list = new ArrayList<>(); for (int i = 0; i < listSize.get(); i++) { Optional value = get(key + "[" + i + "]"); value.ifPresent(list::add); } return Optional.of(list); } public void set(String key, String value) { config.getConfigurationSources().get(0).set(key, value); } public void set(String key, Boolean value) { config.getConfigurationSources().get(0).set(key, value); } public void set(String key, Integer value) { config.getConfigurationSources().get(0).set(key, value); } public void set(String key, Double value) { config.getConfigurationSources().get(0).set(key, value); } public void set(String key, Float value) { config.getConfigurationSources().get(0).set(key, value); } public Optional getType(String key) { // check if key type is a list or a map if (getListSize(key).isPresent()) { return Optional.of(ConfigurationValueType.LIST); } if (getMapKeys(key).isPresent()) { return Optional.of(ConfigurationValueType.MAP); } // get the key value from sources according to priorities and determine its type Optional value = get(key); if (!value.isPresent()) { return Optional.empty(); } if ("true".equals(value.get().toLowerCase()) || "false".equals(value.get().toLowerCase())) { return Optional.of(ConfigurationValueType.BOOLEAN); } try { Integer.valueOf(value.get()); return Optional.of(ConfigurationValueType.INTEGER); } catch (NumberFormatException ignored) { } try { Long.valueOf(value.get()); return Optional.of(ConfigurationValueType.LONG); } catch (NumberFormatException ignored) { } try { Float f = Float.valueOf(value.get()); if (!f.isInfinite()) { return Optional.of(ConfigurationValueType.FLOAT); } } catch (NumberFormatException ignored) { } try { Double.valueOf(value.get()); return Optional.of(ConfigurationValueType.DOUBLE); } catch (NumberFormatException ignored) { } return Optional.of(ConfigurationValueType.STRING); } public Optional> getMapKeys(String key) { Set mapKeys = new HashSet<>(); for (ConfigurationSource configurationSource : config.getConfigurationSources()) { Optional> value = configurationSource.getMapKeys(key); if (value.isPresent()) { for (String s : value.get()) { if (!mapKeys.contains(s.replace("-", ""))) { mapKeys.add(s); } } } } if (mapKeys.isEmpty()) { return Optional.empty(); } return Optional.of(new ArrayList<>(mapKeys)); } public void subscribe(String key, ConfigurationListener listener) { config.getDispatcher().subscribe(listener); for (ConfigurationSource configurationSource : config.getConfigurationSources()) { configurationSource.watch(key); } } public void unsubscribe(ConfigurationListener listener) { config.getDispatcher().unsubscribe(listener); } public List getConfigurationSources() { return Collections.unmodifiableList(this.config.getConfigurationSources()); } public ConfigurationDecoder getConfigurationDecoder() { return config.getConfigurationDecoder(); } } ================================================ FILE: common/src/main/java/com/kumuluz/ee/logs/LogDeferrer.java ================================================ package com.kumuluz.ee.logs; import java.util.ArrayList; import java.util.List; import java.util.function.Consumer; import java.util.function.Supplier; public class LogDeferrer { private Supplier logger; private List> logs = new ArrayList<>(); private Boolean finished = false; public void init(Supplier logger) { if (this.logger != null) { throw new IllegalStateException("The LogDeferrer was already initiated with a logger instance"); } this.logger = logger; } public void defer(Consumer log) { this.logs.add(log); } public void execute() { if (finished) { throw new IllegalStateException("The LogDeferrer was already executed. Please create a new one."); } T loggerInstance = logger.get(); for (Consumer log : logs) { log.accept(loggerInstance); } this.logger = null; this.logs.clear(); this.finished = true; } } ================================================ FILE: common/src/main/java/com/kumuluz/ee/logs/impl/JavaUtilConsoleHandler.java ================================================ package com.kumuluz.ee.logs.impl; import java.io.UnsupportedEncodingException; import java.util.logging.*; public class JavaUtilConsoleHandler extends StreamHandler { /** * Create a {@link JavaUtilConsoleHandler} for {@link System#out}. */ public JavaUtilConsoleHandler() { setLevel(Level.INFO); setFormatter(new JavaUtilFormatter()); setOutputStream(System.out); try { setEncoding(null); } catch (UnsupportedEncodingException ignored) { } } /** * Publish a {@link LogRecord}. *

* The logging request was made initially to a {@link Logger} object, * which initialized the {@link LogRecord} and forwarded it here. *

* @param record description of the log event. A null record is * silently ignored and is not published */ @Override public void publish(LogRecord record) { super.publish(record); flush(); } /** * Override {@link StreamHandler#close} to do a flush but not * to close the output stream. That is, we do not * close {@link System#out}. */ @Override public void close() { flush(); } } ================================================ FILE: common/src/main/java/com/kumuluz/ee/logs/impl/JavaUtilDefaultLogConfigurator.java ================================================ package com.kumuluz.ee.logs.impl; import java.io.IOException; import java.io.InputStream; import java.util.logging.*; public class JavaUtilDefaultLogConfigurator { public static void init() { String javaUtilConfig = System.getProperty("java.util.logging.config.file"); if (javaUtilConfig == null) { LogManager.getLogManager().reset(); Logger rootLogger = LogManager.getLogManager().getLogger(""); JavaUtilConsoleHandler handler = new JavaUtilConsoleHandler(); rootLogger.addHandler(handler); } else { InputStream javaUtilConfigStream = JavaUtilDefaultLogConfigurator.class.getClassLoader() .getResourceAsStream(javaUtilConfig); if (javaUtilConfigStream != null) { try { LogManager.getLogManager().readConfiguration(javaUtilConfigStream); } catch (IOException ignored) { } } } } public static void initSoleHandler(Handler handler) { LogManager.getLogManager().reset(); Logger rootLogger = LogManager.getLogManager().getLogger(""); rootLogger.addHandler(handler); } } ================================================ FILE: common/src/main/java/com/kumuluz/ee/logs/impl/JavaUtilFormatter.java ================================================ package com.kumuluz.ee.logs.impl; import java.io.PrintWriter; import java.io.StringWriter; import java.time.Instant; import java.time.ZoneId; import java.time.ZonedDateTime; import java.time.format.DateTimeFormatter; import java.util.Date; import java.util.logging.Formatter; import java.util.logging.LogRecord; public class JavaUtilFormatter extends Formatter { private static final DateTimeFormatter timestampFormat = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS"); @Override public String format(LogRecord record) { ZonedDateTime zonedDateTime = Instant.ofEpochMilli(record.getMillis()).atZone(ZoneId.systemDefault()); String source = record.getSourceClassName() != null ? record.getSourceClassName() : record.getLoggerName(); String message = formatMessage(record); String throwable = ""; if (record.getThrown() != null) { StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); pw.println(); record.getThrown().printStackTrace(pw); pw.close(); throwable = sw.toString(); } return zonedDateTime.format(timestampFormat) + " " + record.getLevel().getName() + " -- " + source + " -- " + message + throwable + "\n"; } } ================================================ FILE: common/src/main/resources/META-INF/kumuluzee/versions.properties ================================================ version=${project.version} ================================================ FILE: common/src/main/resources/META-INF/services/com.kumuluz.ee.configuration.ConfigurationSource ================================================ com.kumuluz.ee.configuration.sources.EnvironmentConfigurationSource com.kumuluz.ee.configuration.sources.FileConfigurationSource com.kumuluz.ee.configuration.sources.SystemPropertyConfigurationSource ================================================ FILE: common/src/test/java/com/kumuluz/ee/configuration/utils/ConfigurationInterpolationUtilTest.java ================================================ package com.kumuluz.ee.configuration.utils; import org.junit.Test; import java.util.Map; import java.util.Optional; import java.util.function.Function; import static org.junit.Assert.*; /** * Tests for {@link ConfigurationInterpolationUtil}. More tests of interpolation (expressions) are in * kumuluzee-config-mp. * * @author Urban Malc * @since 4.1.0 */ public class ConfigurationInterpolationUtilTest { private static final String TEST_VALUE = "TEST_VALUE"; private Optional identityResolver(String s) { return Optional.ofNullable(s); } private Optional testValueResolver(String s) { return Optional.of(TEST_VALUE); } private Optional emptyResolver(String s) { return Optional.empty(); } private Function> createMapResolver(Map entries) { return s -> Optional.ofNullable(entries.get(s)); } @Test public void noInterpolationTest() { assertEquals("test", ConfigurationInterpolationUtil.interpolateString("test", this::emptyResolver)); assertEquals("", ConfigurationInterpolationUtil.interpolateString("", this::emptyResolver)); assertEquals("${}", ConfigurationInterpolationUtil.interpolateString("\\${}", this::emptyResolver)); assertEquals("${test}", ConfigurationInterpolationUtil.interpolateString("\\${test}", this::emptyResolver)); assertEquals("${}${}", ConfigurationInterpolationUtil.interpolateString("\\${}\\${}", this::emptyResolver)); assertEquals("${${}}", ConfigurationInterpolationUtil.interpolateString("\\${\\${}}", this::emptyResolver)); assertEquals("${", ConfigurationInterpolationUtil.interpolateString("\\${", this::emptyResolver)); assertEquals("abc${}", ConfigurationInterpolationUtil.interpolateString("abc\\${}", this::emptyResolver)); assertEquals("${}def", ConfigurationInterpolationUtil.interpolateString("\\${}def", this::emptyResolver)); assertEquals("abc${}def", ConfigurationInterpolationUtil.interpolateString("abc\\${}def", this::emptyResolver)); } @Test public void simpleInterpolationTest() { assertEquals(TEST_VALUE, ConfigurationInterpolationUtil.interpolateString("${replaceme}", this::testValueResolver)); assertEquals("abc" + TEST_VALUE, ConfigurationInterpolationUtil.interpolateString("abc${replaceme}", this::testValueResolver)); assertEquals(TEST_VALUE + "def", ConfigurationInterpolationUtil.interpolateString("${replaceme}def", this::testValueResolver)); assertEquals("abc" + TEST_VALUE + "def", ConfigurationInterpolationUtil.interpolateString("abc${replaceme}def", this::testValueResolver)); assertEquals(TEST_VALUE + TEST_VALUE, ConfigurationInterpolationUtil.interpolateString("${replaceme}${replaceme}", this::testValueResolver)); assertEquals(TEST_VALUE + " " + TEST_VALUE, ConfigurationInterpolationUtil.interpolateString("${replaceme} ${replaceme}", this::testValueResolver)); } @Test public void nestedInterpolationTest() { assertEquals("i1", ConfigurationInterpolationUtil.interpolateString("${${i1}}", this::identityResolver)); assertEquals("i1i2", ConfigurationInterpolationUtil.interpolateString("${i1${i2}}", this::identityResolver)); assertEquals("i1i2i1", ConfigurationInterpolationUtil.interpolateString("${i1${i2}i1}", this::identityResolver)); assertEquals("finalValue", ConfigurationInterpolationUtil.interpolateString("${prefix.${inner}.postfix}", this.createMapResolver(Map.of( "inner", "innerval", "prefix.innerval.postfix", "finalValue" )))); } @Test public void defaultValueInterpolationTest() { assertEquals("defaultValue", ConfigurationInterpolationUtil.interpolateString("${test:defaultValue}", this::emptyResolver)); assertEquals("defaultValue", ConfigurationInterpolationUtil.interpolateString("${:defaultValue}", this::emptyResolver)); assertEquals("", ConfigurationInterpolationUtil.interpolateString("${test:}", this::emptyResolver)); assertEquals("", ConfigurationInterpolationUtil.interpolateString("${:}", this::emptyResolver)); assertEquals("abc.defaultValue", ConfigurationInterpolationUtil.interpolateString("abc.${test:defaultValue}", this::emptyResolver)); assertEquals("defaultValue.def", ConfigurationInterpolationUtil.interpolateString("${test:defaultValue}.def", this::emptyResolver)); assertEquals("abc.defaultValue.def", ConfigurationInterpolationUtil.interpolateString("abc.${test:defaultValue}.def", this::emptyResolver)); } @Test public void defaultValueAndNestedInterpolationTest() { assertEquals("defaultValue", ConfigurationInterpolationUtil.interpolateString("${first:${second:defaultValue}}", this::emptyResolver)); assertEquals("secondValue", ConfigurationInterpolationUtil.interpolateString("${first:${second:defaultValue}}", this.createMapResolver(Map.of( "second", "secondValue" )))); assertEquals("firstValue", ConfigurationInterpolationUtil.interpolateString("${first:${second:defaultValue}}", this.createMapResolver(Map.of( "first", "firstValue" )))); assertEquals("secondDefault", ConfigurationInterpolationUtil.interpolateString("${${inner:firstDefault}:secondDefault}", this::emptyResolver)); assertEquals("firstValue", ConfigurationInterpolationUtil.interpolateString("${${inner:firstDefault}:secondDefault}", this.createMapResolver(Map.of( "firstDefault", "firstValue" )))); assertEquals("secondValue", ConfigurationInterpolationUtil.interpolateString("${${inner:firstDefault}:secondDefault}", this.createMapResolver(Map.of( "inner", "second", "second", "secondValue" )))); } } ================================================ FILE: components/bean-validation/hibernate-validator/pom.xml ================================================ kumuluzee-bean-validation com.kumuluz.ee 4.2.0-SNAPSHOT 4.0.0 kumuluzee-bean-validation-hibernate-validator KumuluzEE Bean Validation Hibernate Validator KumuluzEE Bean Validation component implemented by Hibernate Validator com.kumuluz.ee kumuluzee-common org.hibernate.validator hibernate-validator ${hibernate.validator.version} org.jboss.logging jboss-logging com.fasterxml classmate org.hibernate.validator hibernate-validator-cdi ${hibernate.validator.version} org.hibernate.validator hibernate-validator org.jboss.logging jboss-logging com.fasterxml classmate org.glassfish.jersey.ext jersey-bean-validation ${jersey.version} org.glassfish.hk2.external javax.inject org.glassfish.jersey.core jersey-common org.glassfish.jersey.core jersey-server jakarta.validation jakarta.validation-api org.hibernate hibernate-validator javax.el javax.el-api org.glassfish.web javax.el javax.ws.rs javax.ws.rs-api junit junit test com.kumuluz.ee kumuluzee-el-uel test ================================================ FILE: components/bean-validation/hibernate-validator/src/main/java/com/kumuluz/ee/beanvalidation/BeanValidationComponent.java ================================================ /* * Copyright (c) 2014-2017 Kumuluz and/or its affiliates * and other contributors as indicated by the @author tags and * the contributor list. * * Licensed under the MIT License (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://opensource.org/licenses/MIT * * The software is provided "AS IS", WITHOUT WARRANTY OF ANY KIND, express or * implied, including but not limited to the warranties of merchantability, * fitness for a particular purpose and noninfringement. in no event shall the * authors or copyright holders be liable for any claim, damages or other * liability, whether in an action of contract, tort or otherwise, arising from, * out of or in connection with the software or the use or other dealings in the * software. See the License for the specific language governing permissions and * limitations under the License. */ package com.kumuluz.ee.beanvalidation; import com.kumuluz.ee.common.Component; import com.kumuluz.ee.common.config.EeConfig; import com.kumuluz.ee.common.dependencies.EeComponentDef; import com.kumuluz.ee.common.dependencies.EeComponentDependency; import com.kumuluz.ee.common.dependencies.EeComponentType; import com.kumuluz.ee.common.wrapper.KumuluzServerWrapper; import java.util.logging.Logger; /** * @author Tilen Faganel * @since 1.0.0 */ @EeComponentDef(name = "Hibernate Validator", type = EeComponentType.BEAN_VALIDATION) @EeComponentDependency(value = EeComponentType.EL) public class BeanValidationComponent implements Component { private Logger log = Logger.getLogger(BeanValidationComponent.class.getSimpleName()); @Override public void init(KumuluzServerWrapper server, EeConfig eeConfig) { } @Override public void load() { log.info("Initiating Hibernate Validator"); } } ================================================ FILE: components/bean-validation/hibernate-validator/src/main/resources/META-INF/services/com.kumuluz.ee.common.Component ================================================ com.kumuluz.ee.beanvalidation.BeanValidationComponent ================================================ FILE: components/bean-validation/hibernate-validator/src/test/java/com/kumuluz/ee/beanvalidation/test/HibernateValidatorTest.java ================================================ /* * Copyright (c) 2014-2017 Kumuluz and/or its affiliates * and other contributors as indicated by the @author tags and * the contributor list. * * Licensed under the MIT License (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://opensource.org/licenses/MIT * * The software is provided "AS IS", WITHOUT WARRANTY OF ANY KIND, express or * implied, including but not limited to the warranties of merchantability, * fitness for a particular purpose and noninfringement. in no event shall the * authors or copyright holders be liable for any claim, damages or other * liability, whether in an action of contract, tort or otherwise, arising from, * out of or in connection with the software or the use or other dealings in the * software. See the License for the specific language governing permissions and * limitations under the License. */ package com.kumuluz.ee.beanvalidation.test; import com.kumuluz.ee.beanvalidation.test.beans.Project; import com.kumuluz.ee.beanvalidation.test.beans.User; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; import javax.validation.ConstraintViolation; import javax.validation.Validation; import javax.validation.Validator; import javax.validation.ValidatorFactory; import java.util.ArrayList; import java.util.Date; import java.util.Set; /** * @author Tilen */ public class HibernateValidatorTest { private static Validator validator; @BeforeClass public static void setUp() { ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); validator = factory.getValidator(); } @Test public void testCorrectEntities() { Project p1 = new Project(); p1.setName("Test project"); p1.setDescription("Sample description of a project"); User u1 = new User(); u1.setUsername("ahughes"); u1.setEmail("amy.hughes@mac.com"); u1.setFirstname("Amy"); u1.setLastname("Hughes"); u1.setAge(20); u1.setSalary(100000d); u1.setCreatedAt(new Date()); u1.setProjects(new ArrayList<>()); u1.getProjects().add(p1); p1.setUser(u1); Set> constraintViolations = validator.validate(u1); Assert.assertNotNull(constraintViolations); Assert.assertEquals(0, constraintViolations.size()); } @Test public void testWrongEntities() { Project p1 = new Project(); p1.setName("T"); User u1 = new User(); u1.setUsername("ahughes"); u1.setEmail("amy.hughesmac.com"); u1.setFirstname(""); u1.setLastname("Hughes"); u1.setAge(-10); u1.setSalary(100000d); u1.setCreatedAt(new Date()); u1.setProjects(new ArrayList<>()); u1.getProjects().add(p1); p1.setUser(u1); Set> constraintViolations = validator.validate(u1); Assert.assertNotNull(constraintViolations); Assert.assertEquals(4, constraintViolations.size()); } } ================================================ FILE: components/bean-validation/hibernate-validator/src/test/java/com/kumuluz/ee/beanvalidation/test/beans/Project.java ================================================ /* * Copyright (c) 2014-2017 Kumuluz and/or its affiliates * and other contributors as indicated by the @author tags and * the contributor list. * * Licensed under the MIT License (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://opensource.org/licenses/MIT * * The software is provided "AS IS", WITHOUT WARRANTY OF ANY KIND, express or * implied, including but not limited to the warranties of merchantability, * fitness for a particular purpose and noninfringement. in no event shall the * authors or copyright holders be liable for any claim, damages or other * liability, whether in an action of contract, tort or otherwise, arising from, * out of or in connection with the software or the use or other dealings in the * software. See the License for the specific language governing permissions and * limitations under the License. */ package com.kumuluz.ee.beanvalidation.test.beans; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; /** * @author Tilen */ public class Project { @NotNull @Size(min = 2, max = 30) private String name; @Size(min = 1, max = 3000) private String description; @NotNull private User user; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public User getUser() { return user; } public void setUser(User user) { this.user = user; } } ================================================ FILE: components/bean-validation/hibernate-validator/src/test/java/com/kumuluz/ee/beanvalidation/test/beans/User.java ================================================ /* * Copyright (c) 2014-2017 Kumuluz and/or its affiliates * and other contributors as indicated by the @author tags and * the contributor list. * * Licensed under the MIT License (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://opensource.org/licenses/MIT * * The software is provided "AS IS", WITHOUT WARRANTY OF ANY KIND, express or * implied, including but not limited to the warranties of merchantability, * fitness for a particular purpose and noninfringement. in no event shall the * authors or copyright holders be liable for any claim, damages or other * liability, whether in an action of contract, tort or otherwise, arising from, * out of or in connection with the software or the use or other dealings in the * software. See the License for the specific language governing permissions and * limitations under the License. */ package com.kumuluz.ee.beanvalidation.test.beans; import javax.validation.Valid; import javax.validation.constraints.Email; import javax.validation.constraints.Min; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; import java.util.Date; import java.util.List; /** * @author Tilen */ public class User { @NotNull @Size(min = 2, max = 30) private String username; @NotNull @Email private String email; @Size(min = 2, max = 20) private String firstname; @Size(min = 2, max = 20) private String lastname; @NotNull @Min(0) private Integer age; @NotNull @Min(0) private Double salary; @NotNull private Date createdAt; @Valid private List projects; public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getFirstname() { return firstname; } public void setFirstname(String firstname) { this.firstname = firstname; } public String getLastname() { return lastname; } public void setLastname(String lastname) { this.lastname = lastname; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } public Double getSalary() { return salary; } public void setSalary(Double salary) { this.salary = salary; } public Date getCreatedAt() { return createdAt; } public void setCreatedAt(Date createdAt) { this.createdAt = createdAt; } public List getProjects() { return projects; } public void setProjects(List projects) { this.projects = projects; } } ================================================ FILE: components/bean-validation/pom.xml ================================================ kumuluzee-components com.kumuluz.ee 4.2.0-SNAPSHOT 4.0.0 pom KumuluzEE Bean Validation KumuluzEE Bean Validation component hibernate-validator kumuluzee-bean-validation ================================================ FILE: components/cdi/pom.xml ================================================ kumuluzee-components com.kumuluz.ee 4.2.0-SNAPSHOT 4.0.0 pom KumuluzEE CDI KumuluzEE CDI component weld kumuluzee-cdi ================================================ FILE: components/cdi/weld/pom.xml ================================================ kumuluzee-cdi com.kumuluz.ee 4.2.0-SNAPSHOT 4.0.0 KumuluzEE CDI Weld KumuluzEE CDI component implemented by Weld kumuluzee-cdi-weld com.kumuluz.ee kumuluzee-common jakarta.interceptor jakarta.interceptor-api jakarta.ejb jakarta.ejb-api jakarta.el jakarta.el-api org.jboss.weld.servlet weld-servlet-core ${weld.version} org.jboss.spec.javax.annotation jboss-annotations-api_1.3_spec org.jboss.spec.javax.el jboss-el-api_3.0_spec org.jboss.spec.javax.interceptor jboss-interceptors-api_1.2_spec org.jboss.logging jboss-logging org.jboss jandex org.jboss.logging jboss-logging org.glassfish.jersey.ext.cdi jersey-cdi1x-ban-custom-hk2-binding ${jersey.version} javax.ws.rs javax.ws.rs-api ================================================ FILE: components/cdi/weld/src/main/java/com/kumuluz/ee/cdi/CdiComponent.java ================================================ /* * Copyright (c) 2014-2017 Kumuluz and/or its affiliates * and other contributors as indicated by the @author tags and * the contributor list. * * Licensed under the MIT License (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://opensource.org/licenses/MIT * * The software is provided "AS IS", WITHOUT WARRANTY OF ANY KIND, express or * implied, including but not limited to the warranties of merchantability, * fitness for a particular purpose and noninfringement. in no event shall the * authors or copyright holders be liable for any claim, damages or other * liability, whether in an action of contract, tort or otherwise, arising from, * out of or in connection with the software or the use or other dealings in the * software. See the License for the specific language governing permissions and * limitations under the License. */ package com.kumuluz.ee.cdi; import com.kumuluz.ee.common.Component; import com.kumuluz.ee.common.config.EeConfig; import com.kumuluz.ee.common.dependencies.EeComponentDef; import com.kumuluz.ee.common.dependencies.EeComponentType; import com.kumuluz.ee.common.wrapper.KumuluzServerWrapper; import java.util.logging.Logger; /** * @author Tilen Faganel * @since 1.0.0 */ @EeComponentDef(name = "Weld", type = EeComponentType.CDI) public class CdiComponent implements Component { private Logger log = Logger.getLogger(CdiComponent.class.getSimpleName()); @Override public void init(KumuluzServerWrapper server, EeConfig eeConfig) { } @Override public void load() { log.info("Initiating Weld"); } } ================================================ FILE: components/cdi/weld/src/main/java/com/kumuluz/ee/configuration/cdi/ConfigBundle.java ================================================ /* * Copyright (c) 2014-2017 Kumuluz and/or its affiliates * and other contributors as indicated by the @author tags and * the contributor list. * * Licensed under the MIT License (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://opensource.org/licenses/MIT * * The software is provided "AS IS", WITHOUT WARRANTY OF ANY KIND, express or * implied, including but not limited to the warranties of merchantability, * fitness for a particular purpose and noninfringement. in no event shall the * authors or copyright holders be liable for any claim, damages or other * liability, whether in an action of contract, tort or otherwise, arising from, * out of or in connection with the software or the use or other dealings in the * software. See the License for the specific language governing permissions and * limitations under the License. */ package com.kumuluz.ee.configuration.cdi; import javax.enterprise.util.Nonbinding; import javax.interceptor.InterceptorBinding; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * @author Tilen Faganel * @since 2.1.0 */ @InterceptorBinding @Target({ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME) public @interface ConfigBundle { @Nonbinding String value() default ""; @Nonbinding boolean watch() default false; } ================================================ FILE: components/cdi/weld/src/main/java/com/kumuluz/ee/configuration/cdi/ConfigValue.java ================================================ /* * Copyright (c) 2014-2017 Kumuluz and/or its affiliates * and other contributors as indicated by the @author tags and * the contributor list. * * Licensed under the MIT License (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://opensource.org/licenses/MIT * * The software is provided "AS IS", WITHOUT WARRANTY OF ANY KIND, express or * implied, including but not limited to the warranties of merchantability, * fitness for a particular purpose and noninfringement. in no event shall the * authors or copyright holders be liable for any claim, damages or other * liability, whether in an action of contract, tort or otherwise, arising from, * out of or in connection with the software or the use or other dealings in the * software. See the License for the specific language governing permissions and * limitations under the License. */ package com.kumuluz.ee.configuration.cdi; import javax.enterprise.util.Nonbinding; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Annotation specifies key name for automatic initialisation of a field from configuration. If attribute watch is * set to true, key is subscribed to dynamic configuration events. * * @author Tilen Faganel * @since 2.1.0 */ @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.FIELD}) public @interface ConfigValue { @Nonbinding String value() default ""; @Nonbinding boolean watch() default false; } ================================================ FILE: components/cdi/weld/src/main/java/com/kumuluz/ee/configuration/cdi/interceptors/ConfigBundleInterceptor.java ================================================ /* * Copyright (c) 2014-2017 Kumuluz and/or its affiliates * and other contributors as indicated by the @author tags and * the contributor list. * * Licensed under the MIT License (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://opensource.org/licenses/MIT * * The software is provided "AS IS", WITHOUT WARRANTY OF ANY KIND, express or * implied, including but not limited to the warranties of merchantability, * fitness for a particular purpose and noninfringement. in no event shall the * authors or copyright holders be liable for any claim, damages or other * liability, whether in an action of contract, tort or otherwise, arising from, * out of or in connection with the software or the use or other dealings in the * software. See the License for the specific language governing permissions and * limitations under the License. */ package com.kumuluz.ee.configuration.cdi.interceptors; import com.kumuluz.ee.common.utils.StringUtils; import com.kumuluz.ee.configuration.cdi.ConfigBundle; import com.kumuluz.ee.configuration.cdi.ConfigValue; import com.kumuluz.ee.configuration.utils.ConfigurationUtil; import javax.annotation.PostConstruct; import javax.annotation.Priority; import javax.interceptor.Interceptor; import javax.interceptor.InvocationContext; import java.lang.reflect.Array; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.*; import java.util.logging.Logger; /** * Interceptor class for ConfigBundle annotation. * * @author Tilen Faganel * @author Jan Meznaric * @since 2.1.0 */ @Interceptor @ConfigBundle @Priority(Interceptor.Priority.LIBRARY_BEFORE) public class ConfigBundleInterceptor { private static final Logger log = Logger.getLogger(ConfigBundleInterceptor.class.getName()); private static final ConfigurationUtil configurationUtil = ConfigurationUtil.getInstance(); private final Class[] primitives = {String.class, Boolean.class, Float.class, Double.class, Integer.class, Long .class, boolean.class, float.class, double.class, int.class, long.class}; /** * Method initialises class fields from configuration. */ @PostConstruct public Object loadConfiguration(InvocationContext ic) throws Exception { Object target = ic.getTarget(); Class targetClass = target.getClass(); if (targetClassIsProxied(targetClass)) { targetClass = targetClass.getSuperclass(); } ConfigBundle configBundleAnnotation = (ConfigBundle) targetClass.getDeclaredAnnotation(ConfigBundle.class); processConfigBundleBeanSetters(target, targetClass, getKeyPrefix(targetClass), new HashMap<>(), configBundleAnnotation.watch()); return ic.proceed(); } /** * Processes and invokes all setters in Bean annotated with @ConfigBundle * * @param target target object * @param targetClass target class * @param keyPrefix a prefix for generating key names * @param processedClassRelations class pairs that have already been processed (for cycle detection) * @param watchAllFields if true, enable watch on all fields * @return returns true, if at least one field was successfully populated from configuration sources * @throws Exception */ private boolean processConfigBundleBeanSetters(Object target, Class targetClass, String keyPrefix, Map processedClassRelations, boolean watchAllFields) throws Exception { boolean isConfigBundleEmpty = true; // invoke setters for (Method method : targetClass.getMethods()) { if (method.getName().substring(0, 3).equals("set") && method.getParameters().length == 1) { Class parameterType = method.getParameters()[0].getType(); // get field annotation - @ConfigValue Field field = targetClass.getDeclaredField(setterToField(method.getName())); ConfigValue fieldAnnotation = null; if (field != null) { fieldAnnotation = field.getAnnotation(ConfigValue.class); } // watch nested class or list if all fields in the bean are annotated with watch or if a field is // annotated with watch boolean watchNestedClass = watchAllFields; if (watchNestedClass == false) { if (fieldAnnotation != null) { watchNestedClass = fieldAnnotation.watch(); } } // process primitives if (Arrays.asList(primitives).contains(parameterType)) { Optional value = getValueOfPrimitive(parameterType, getKeyName(targetClass, method .getName(), keyPrefix)); if (value.isPresent()) { isConfigBundleEmpty = false; method.invoke(target, value.get()); } if (watchAllFields || (fieldAnnotation != null && fieldAnnotation.watch())) { deployWatcher(target, method, getKeyName(targetClass, method.getName(), keyPrefix)); } // process nested objeccts } else if (!parameterType.isArray()) { processedClassRelations.put(targetClass, parameterType); Object nestedTarget = processNestedObject(targetClass, method, parameterType, keyPrefix, processedClassRelations, -1, watchNestedClass); // invoke setter method with initialised instance if (nestedTarget != null) { method.invoke(target, nestedTarget); } // process arrays } else { Class componentType = parameterType.getComponentType(); Object array = Array.newInstance(componentType, configurationUtil.getListSize(getKeyName (targetClass, method.getName(), keyPrefix)).orElse(0)); // process list of primitives if (Arrays.asList(primitives).contains(componentType)) { for (int i = 0; i < Array.getLength(array); i++) { Optional valueOfPrimitive = getValueOfPrimitive(componentType, getKeyName(targetClass, method.getName(), keyPrefix) + "[" + i + "]"); if (valueOfPrimitive.isPresent()) { Array.set(array, i, valueOfPrimitive.get()); } } // process list of nested classes } else { for (int i = 0; i < Array.getLength(array); i++) { Object nestedTarget = processNestedObject(targetClass, method, componentType, keyPrefix, processedClassRelations, i, watchNestedClass); if (nestedTarget != null) { Array.set(array, i, nestedTarget); } } } method.invoke(target, array); } } } return isConfigBundleEmpty; } /** * Returns a value of a primitive configuration type * * @param type configuration value type * @param key configuration value key * @return */ private Optional getValueOfPrimitive(Class type, String key) { if (type.equals(String.class)) { return configurationUtil.get(key); } else if (type.equals(Boolean.class) || type.equals(boolean.class)) { return configurationUtil.getBoolean(key); } else if (type.equals(Float.class) || type.equals(float.class)) { return configurationUtil.getFloat(key); } else if (type.equals(Double.class) || type.equals(double.class)) { return configurationUtil.getDouble(key); } else if (type.equals(Integer.class) || type.equals(int.class)) { return configurationUtil.getInteger(key); } else if (type.equals(Long.class) || type.equals(long.class)) { return configurationUtil.getLong(key); } else { return Optional.empty(); } } /** * Create a new instance for nested class, check for cycles and populate nested instance. * * @param targetClass target class * @param method processed method * @param parameterType parameter type * @param keyPrefix prefix used for generation of a configuration key * @param processedClassRelations class pairs that have already been processed (for cycle detection) * @param arrayIndex array index for arrays of nested objects * @param watchAllFields if true, enable watch on all fields * @return * @throws Exception */ private Object processNestedObject(Class targetClass, Method method, Class parameterType, String keyPrefix, Map processedClassRelations, int arrayIndex, boolean watchAllFields) throws Exception { Object nestedTarget = parameterType.getConstructor().newInstance(); Class nestedTargetClass = nestedTarget.getClass(); // check for cycles if (processedClassRelations.containsKey(nestedTargetClass) && processedClassRelations.get(nestedTargetClass) .equals(targetClass)) { log.warning("There is a cycle in the configuration class tree. ConfigBundle class may not " + "be populated as expected."); } else { String key = getKeyName(targetClass, method.getName(), keyPrefix); if (arrayIndex >= 0) { key += "[" + arrayIndex + "]"; } boolean isEmpty = processConfigBundleBeanSetters(nestedTarget, nestedTargetClass, key, processedClassRelations, watchAllFields); if (isEmpty) { return null; } } return nestedTarget; } /** * Construct key name from prefix and field name or ConfigValue value (if present) * * @param targetClass target class * @param setter name of the setter method * @param keyPrefix prefix used for generation of a configuration key * @return key in format prefix.key-name */ private String getKeyName(Class targetClass, String setter, String keyPrefix) throws Exception { StringBuilder key = new StringBuilder(); key.append(keyPrefix); if (!key.toString().isEmpty()) { key.append("."); } // get ConfigValue Field field = targetClass.getDeclaredField(setterToField(setter)); ConfigValue fieldAnnotation = null; if (field != null) { fieldAnnotation = field.getAnnotation(ConfigValue.class); } if (fieldAnnotation != null && !fieldAnnotation.value().isEmpty()) { key.append(StringUtils.camelCaseToHyphenCase(fieldAnnotation.value())); } else { key.append(StringUtils.camelCaseToHyphenCase(setter.substring(3))); } return key.toString(); } /** * Generate a key prefix from annotation, class name, or parent prefix in case of nested classes. * * @param targetClass target class * @return key prefix */ private String getKeyPrefix(Class targetClass) { String prefix = ((ConfigBundle) targetClass.getAnnotation(ConfigBundle.class)).value(); if (prefix.isEmpty()) { prefix = StringUtils.camelCaseToHyphenCase(targetClass.getSimpleName()); } if (".".equals(prefix)) { prefix = ""; } return prefix; } /** * Parse setter name to field name. * * @param setter name of the setter method * @return field name */ private String setterToField(String setter) { return Character.toLowerCase(setter.charAt(3)) + setter.substring(4); } /** * Check if target class is proxied. * * @param targetClass target class * @return true if target class is proxied */ private boolean targetClassIsProxied(Class targetClass) { return targetClass.getCanonicalName().contains("$Proxy"); } /** * Subscribes to an event dispatcher and starts a watch for a given key. * * @param target target instance * @param method method to invoke * @param watchedKey watched key * @throws Exception */ private void deployWatcher(Object target, Method method, String watchedKey) throws Exception { configurationUtil.subscribe(watchedKey, (key, value) -> { if (Objects.equals(watchedKey, key)) { try { if (String.class.equals(method.getParameters()[0].getType())) { method.invoke(target, value); } else if (Boolean.class.equals(method.getParameters()[0].getType()) || boolean.class.equals(method .getParameters()[0].getType())) { method.invoke(target, Boolean.parseBoolean(value)); } else if (Float.class.equals(method.getParameters()[0].getType()) || float.class.equals(method .getParameters()[0].getType())) { try { method.invoke(target, Float.parseFloat(value)); } catch (NumberFormatException e) { log.severe("Exception while storing new value: Number format exception. " + "Expected: Float. Value: " + value); } } else if (Double.class.equals(method.getParameters()[0].getType()) || double.class.equals(method .getParameters()[0].getType())) { try { method.invoke(target, Double.parseDouble(value)); } catch (NumberFormatException e) { log.severe("Exception while storing new value: Number format exception. Expected:" + " Double. Value: " + value); } } else if (Integer.class.equals(method.getParameters()[0].getType()) || int.class.equals(method .getParameters()[0].getType())) { try { method.invoke(target, Integer.parseInt(value)); } catch (NumberFormatException e) { log.severe("Exception while storing new value: Number format exception. Expected:" + " Integer. Value: " + value); } } else if (Long.class.equals(method.getParameters()[0].getType()) || long.class.equals(method .getParameters()[0].getType())) { try { method.invoke(target, Long.parseLong(value)); } catch (NumberFormatException e) { log.severe("Exception while storing new value: Number format exception. Expected:" + " Long. Value: " + value); } } } catch (IllegalAccessException e) { log.severe("Illegal access exception: " + e.toString()); } catch (InvocationTargetException e) { log.severe("Invocation target exception: " + e.toString()); } } }); } } ================================================ FILE: components/cdi/weld/src/main/java/com/kumuluz/ee/configuration/cdi/producers/ConfigurationUtilProducer.java ================================================ /* * Copyright (c) 2014-2017 Kumuluz and/or its affiliates * and other contributors as indicated by the @author tags and * the contributor list. * * Licensed under the MIT License (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://opensource.org/licenses/MIT * * The software is provided "AS IS", WITHOUT WARRANTY OF ANY KIND, express or * implied, including but not limited to the warranties of merchantability, * fitness for a particular purpose and noninfringement. in no event shall the * authors or copyright holders be liable for any claim, damages or other * liability, whether in an action of contract, tort or otherwise, arising from, * out of or in connection with the software or the use or other dealings in the * software. See the License for the specific language governing permissions and * limitations under the License. */ package com.kumuluz.ee.configuration.cdi.producers; import com.kumuluz.ee.configuration.utils.ConfigurationUtil; import javax.enterprise.context.ApplicationScoped; import javax.enterprise.inject.Produces; /** * @author Tilen Faganel * @since 2.1.0 */ public class ConfigurationUtilProducer { @Produces @ApplicationScoped public ConfigurationUtil getConfigurationUtil() { return ConfigurationUtil.getInstance(); } } ================================================ FILE: components/cdi/weld/src/main/java/com/kumuluz/ee/configuration/cdi/producers/EeConfigProducer.java ================================================ /* * Copyright (c) 2014-2017 Kumuluz and/or its affiliates * and other contributors as indicated by the @author tags and * the contributor list. * * Licensed under the MIT License (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://opensource.org/licenses/MIT * * The software is provided "AS IS", WITHOUT WARRANTY OF ANY KIND, express or * implied, including but not limited to the warranties of merchantability, * fitness for a particular purpose and noninfringement. in no event shall the * authors or copyright holders be liable for any claim, damages or other * liability, whether in an action of contract, tort or otherwise, arising from, * out of or in connection with the software or the use or other dealings in the * software. See the License for the specific language governing permissions and * limitations under the License. */ package com.kumuluz.ee.configuration.cdi.producers; import com.kumuluz.ee.common.config.EeConfig; import javax.enterprise.context.ApplicationScoped; import javax.enterprise.inject.Produces; /** * @author Tilen Faganel * @since 2.4.0 */ public class EeConfigProducer { @Produces @ApplicationScoped public EeConfig getConfigurationUtil() { return EeConfig.getInstance(); } } ================================================ FILE: components/cdi/weld/src/main/java/com/kumuluz/ee/runtime/cdi/producers/EeRuntimeProducer.java ================================================ /* * Copyright (c) 2014-2017 Kumuluz and/or its affiliates * and other contributors as indicated by the @author tags and * the contributor list. * * Licensed under the MIT License (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://opensource.org/licenses/MIT * * The software is provided "AS IS", WITHOUT WARRANTY OF ANY KIND, express or * implied, including but not limited to the warranties of merchantability, * fitness for a particular purpose and noninfringement. in no event shall the * authors or copyright holders be liable for any claim, damages or other * liability, whether in an action of contract, tort or otherwise, arising from, * out of or in connection with the software or the use or other dealings in the * software. See the License for the specific language governing permissions and * limitations under the License. */ package com.kumuluz.ee.runtime.cdi.producers; import com.kumuluz.ee.common.runtime.EeRuntime; import javax.enterprise.context.ApplicationScoped; import javax.enterprise.inject.Produces; /** * @author Tilen Faganel * @since 2.4.0 */ public class EeRuntimeProducer { @Produces @ApplicationScoped public EeRuntime getConfigurationUtil() { return EeRuntime.getInstance(); } } ================================================ FILE: components/cdi/weld/src/main/resources/META-INF/beans.xml ================================================ ================================================ FILE: components/cdi/weld/src/main/resources/META-INF/services/com.kumuluz.ee.common.Component ================================================ com.kumuluz.ee.cdi.CdiComponent ================================================ FILE: components/el/pom.xml ================================================ kumuluzee-components com.kumuluz.ee 4.2.0-SNAPSHOT 4.0.0 pom KumuluzEE EL KumuluzEE EL component uel kumuluzee-el ================================================ FILE: components/el/uel/pom.xml ================================================ kumuluzee-el com.kumuluz.ee 4.2.0-SNAPSHOT 4.0.0 KumuluzEE EL UEL KumuluzEE EL component implemented by UEL kumuluzee-el-uel com.kumuluz.ee kumuluzee-common org.glassfish jakarta.el ${uel.version} ================================================ FILE: components/el/uel/src/main/java/com/kumuluz/ee/el/ElComponent.java ================================================ /* * Copyright (c) 2014-2017 Kumuluz and/or its affiliates * and other contributors as indicated by the @author tags and * the contributor list. * * Licensed under the MIT License (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://opensource.org/licenses/MIT * * The software is provided "AS IS", WITHOUT WARRANTY OF ANY KIND, express or * implied, including but not limited to the warranties of merchantability, * fitness for a particular purpose and noninfringement. in no event shall the * authors or copyright holders be liable for any claim, damages or other * liability, whether in an action of contract, tort or otherwise, arising from, * out of or in connection with the software or the use or other dealings in the * software. See the License for the specific language governing permissions and * limitations under the License. */ package com.kumuluz.ee.el; import com.kumuluz.ee.common.Component; import com.kumuluz.ee.common.config.EeConfig; import com.kumuluz.ee.common.dependencies.EeComponentDef; import com.kumuluz.ee.common.dependencies.EeComponentType; import com.kumuluz.ee.common.wrapper.KumuluzServerWrapper; import java.util.logging.Logger; /** * @author Tilen Faganel * @since 1.0.0 */ @EeComponentDef(name = "UEL", type = EeComponentType.EL) public class ElComponent implements Component { private Logger log = Logger.getLogger(ElComponent.class.getSimpleName()); @Override public void init(KumuluzServerWrapper server, EeConfig eeConfig) { } @Override public void load() { log.info("Initiating UEL"); } } ================================================ FILE: components/el/uel/src/main/resources/META-INF/services/com.kumuluz.ee.common.Component ================================================ com.kumuluz.ee.el.ElComponent ================================================ FILE: components/javamail/pom.xml ================================================ kumuluzee-components com.kumuluz.ee 4.2.0-SNAPSHOT 4.0.0 pom KumuluzEE JavaMail KumuluzEE JavaMail component ri kumuluzee-javamail ================================================ FILE: components/javamail/ri/pom.xml ================================================ kumuluzee-javamail com.kumuluz.ee 4.2.0-SNAPSHOT 4.0.0 KumuluzEE JavaMail KumuluzEE JavaMail component implemented by JavaMail RI kumuluzee-javamail-ri com.kumuluz.ee kumuluzee-common com.sun.mail javax.mail ${javamail-ri.version} ================================================ FILE: components/javamail/ri/src/main/java/com/kumuluz/ee/javamail/ri/JavaMailComponent.java ================================================ package com.kumuluz.ee.javamail.ri; import com.kumuluz.ee.common.Component; import com.kumuluz.ee.common.ServletServer; import com.kumuluz.ee.common.config.EeConfig; import com.kumuluz.ee.common.config.MailSessionConfig; import com.kumuluz.ee.common.dependencies.EeComponentDef; import com.kumuluz.ee.common.dependencies.EeComponentType; import com.kumuluz.ee.common.wrapper.KumuluzServerWrapper; import javax.mail.Session; import java.util.logging.Logger; /** * @author Tilen Faganel * @since 2.6.0 */ @EeComponentDef(name = "JavaMailRI", type = EeComponentType.MAIL) public class JavaMailComponent implements Component { private Logger log = Logger.getLogger(JavaMailComponent.class.getSimpleName()); @Override public void init(KumuluzServerWrapper server, EeConfig eeConfig) { if (eeConfig.getMailSessions() != null && eeConfig.getMailSessions().size() > 0 && server.getServer() instanceof ServletServer) { ServletServer servletServer = (ServletServer) server.getServer(); for (MailSessionConfig cfg : eeConfig.getMailSessions()) { Session session = MailSessionFactory.create(cfg); servletServer.registerResource(session, cfg.getJndiName()); } } } @Override public void load() { log.info("Initiating JavaMailRi"); } } ================================================ FILE: components/javamail/ri/src/main/java/com/kumuluz/ee/javamail/ri/MailSessionFactory.java ================================================ package com.kumuluz.ee.javamail.ri; import com.kumuluz.ee.common.config.MailServiceConfig; import com.kumuluz.ee.common.config.MailSessionConfig; import javax.mail.Session; import java.util.Map; import java.util.Properties; import java.util.logging.Logger; public class MailSessionFactory { private final static Logger LOG = Logger.getLogger(MailSessionFactory.class.getSimpleName()); private final static String TRANSPORT_PROTOCOL_KEY = "mail.transport.protocol"; private final static String STORE_PROTOCOL_KEY = "mail.store.protocol"; static Session create(MailSessionConfig cfg) { Properties properties = new Properties(); if (cfg.getDebug() != null) { properties.setProperty("mail.debug", cfg.getDebug().toString()); } if (cfg.getTransport() != null) { if (cfg.getTransport().getProtocol() != null) { String protocol = cfg.getTransport().getProtocol(); properties.setProperty(TRANSPORT_PROTOCOL_KEY, protocol); configureService(properties, cfg.getTransport(), protocol); } else { LOG.warning("The transport protocol for the Java Mail session is not defined. Please check your configuration."); } } if (cfg.getStore() != null) { if (cfg.getStore().getProtocol() != null) { String protocol = cfg.getStore().getProtocol(); properties.setProperty(STORE_PROTOCOL_KEY, protocol); configureService(properties, cfg.getStore(), protocol); } else { LOG.warning("The store protocol for the Java Mail session is not defined. Please check your configuration."); } } if (cfg.getProps() != null && cfg.getProps().size() > 0) { for (Map.Entry prop : cfg.getProps().entrySet()) { properties.setProperty(prop.getKey(), prop.getValue()); } } return Session.getInstance(properties, new ManagedPasswordAuthenticator(cfg)); } private static void configureService(Properties properties, MailServiceConfig serviceConfig, String protocol) { String prefix = "mail." + protocol; if (serviceConfig.getHost() != null) { properties.setProperty(prefix + ".host", serviceConfig.getHost()); } if (serviceConfig.getPort() != null) { properties.setProperty(prefix + ".port", serviceConfig.getPort().toString()); } if (serviceConfig.getStarttls() != null) { properties.setProperty(prefix + ".starttls.enable", serviceConfig.getStarttls().toString()); } if (serviceConfig.getConnectionTimeout() != null) { properties.setProperty(prefix + ".connectiontimeout", serviceConfig.getConnectionTimeout().toString()); } if (serviceConfig.getTimeout() != null) { properties.setProperty(prefix + ".timeout", serviceConfig.getTimeout().toString()); } if (serviceConfig.getPassword() != null) { properties.setProperty(prefix + ".auth", Boolean.TRUE.toString()); } } } ================================================ FILE: components/javamail/ri/src/main/java/com/kumuluz/ee/javamail/ri/ManagedPasswordAuthenticator.java ================================================ package com.kumuluz.ee.javamail.ri; import com.kumuluz.ee.common.config.MailServiceConfig; import com.kumuluz.ee.common.config.MailSessionConfig; import javax.mail.Authenticator; import javax.mail.PasswordAuthentication; public class ManagedPasswordAuthenticator extends Authenticator { private MailSessionConfig mailSessionConfig; ManagedPasswordAuthenticator(MailSessionConfig mailSessionConfig) { this.mailSessionConfig = mailSessionConfig; } @Override protected PasswordAuthentication getPasswordAuthentication() { String protocol = getRequestingProtocol(); MailServiceConfig requestingConfig = null; if (mailSessionConfig.getTransport() != null && protocol.equals(mailSessionConfig.getTransport().getProtocol())) { requestingConfig = mailSessionConfig.getTransport(); } else if (mailSessionConfig.getStore() != null && protocol.equals(mailSessionConfig.getStore().getProtocol())) { requestingConfig = mailSessionConfig.getStore(); } if (requestingConfig != null && requestingConfig.getPassword() != null) { return new PasswordAuthentication(requestingConfig.getUsername(), requestingConfig.getPassword()); } return null; } } ================================================ FILE: components/javamail/ri/src/main/resources/META-INF/services/com.kumuluz.ee.common.Component ================================================ com.kumuluz.ee.javamail.ri.JavaMailComponent ================================================ FILE: components/jax-rs/jersey/pom.xml ================================================ kumuluzee-jax-rs com.kumuluz.ee 4.2.0-SNAPSHOT 4.0.0 KumuluzEE JAX-RS Jersey KumuluzEE JAX-RS component implemented by Jersey kumuluzee-jax-rs-jersey com.kumuluz.ee kumuluzee-common org.glassfish.jersey.containers jersey-container-servlet ${jersey.version} org.glassfish.hk2.external javax.inject org.glassfish.jersey.media jersey-media-sse ${jersey.version} org.glassfish.hk2.external javax.inject org.glassfish.jersey.media jersey-media-json-jackson ${jersey.version} org.glassfish.jersey.inject jersey-hk2 ${jersey.version} org.glassfish.hk2.external javax.inject org.javassist javassist org.glassfish.jersey.ext.cdi jersey-cdi1x-servlet ${jersey.version} jakarta.enterprise jakarta.enterprise.cdi-api org.javassist javassist com.fasterxml.jackson.jaxrs jackson-jaxrs-json-provider org.glassfish.jersey.connectors jersey-jetty-connector ${jersey.version} org.eclipse.jetty jetty-client org.glassfish.jersey.core jersey-common org.glassfish.jersey.core jersey-client javax.ws.rs javax.ws.rs-api org.eclipse.jetty jetty-client ${jetty.version} provided javax.activation activation ${activation.version} javax.xml.bind jaxb-api ${jaxb-api.version} ================================================ FILE: components/jax-rs/jersey/src/main/java/com/kumuluz/ee/jaxrs/JaxRsComponent.java ================================================ /* * Copyright (c) 2014-2017 Kumuluz and/or its affiliates * and other contributors as indicated by the @author tags and * the contributor list. * * Licensed under the MIT License (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://opensource.org/licenses/MIT * * The software is provided "AS IS", WITHOUT WARRANTY OF ANY KIND, express or * implied, including but not limited to the warranties of merchantability, * fitness for a particular purpose and noninfringement. in no event shall the * authors or copyright holders be liable for any claim, damages or other * liability, whether in an action of contract, tort or otherwise, arising from, * out of or in connection with the software or the use or other dealings in the * software. See the License for the specific language governing permissions and * limitations under the License. */ package com.kumuluz.ee.jaxrs; import com.kumuluz.ee.common.Component; import com.kumuluz.ee.common.config.EeConfig; import com.kumuluz.ee.common.dependencies.EeComponentDef; import com.kumuluz.ee.common.dependencies.EeComponentDependency; import com.kumuluz.ee.common.dependencies.EeComponentType; import com.kumuluz.ee.common.wrapper.KumuluzServerWrapper; import java.util.logging.Logger; /** * @author Tilen Faganel * @since 1.0.0 */ @EeComponentDef(name = "Jersey", type = EeComponentType.JAX_RS) @EeComponentDependency(value = EeComponentType.SERVLET) public class JaxRsComponent implements Component { private Logger log = Logger.getLogger(JaxRsComponent.class.getSimpleName()); @Override public void init(KumuluzServerWrapper server, EeConfig eeConfig) { } @Override public void load() { log.info("Initiating Jersey"); } } ================================================ FILE: components/jax-rs/jersey/src/main/java/com/kumuluz/ee/jaxrs/Jetty10ConnectorProvider.java ================================================ /* * Copyright (c) 2014-2017 Kumuluz and/or its affiliates * and other contributors as indicated by the @author tags and * the contributor list. * * Licensed under the MIT License (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://opensource.org/licenses/MIT * * The software is provided "AS IS", WITHOUT WARRANTY OF ANY KIND, express or * implied, including but not limited to the warranties of merchantability, * fitness for a particular purpose and noninfringement. in no event shall the * authors or copyright holders be liable for any claim, damages or other * liability, whether in an action of contract, tort or otherwise, arising from, * out of or in connection with the software or the use or other dealings in the * software. See the License for the specific language governing permissions and * limitations under the License. */ package com.kumuluz.ee.jaxrs; import org.glassfish.jersey.client.spi.Connector; import org.glassfish.jersey.client.spi.ConnectorProvider; import org.glassfish.jersey.jetty.connector.Jetty10Connector; import javax.ws.rs.client.Client; import javax.ws.rs.core.Configuration; /** * Jersey connection provider for Jetty 10. * * @author Urban Malc * @since 4.0.0 */ public class Jetty10ConnectorProvider implements ConnectorProvider { @Override public Connector getConnector(Client client, Configuration runtimeConfig) { return new Jetty10Connector(client, runtimeConfig); } } ================================================ FILE: components/jax-rs/jersey/src/main/java/org/glassfish/jersey/jetty/connector/Jetty10Connector.java ================================================ /* * Copyright (c) 2013, 2021 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v. 2.0, which is available at * http://www.eclipse.org/legal/epl-2.0. * * This Source Code may also be made available under the following Secondary * Licenses when the conditions for such availability set forth in the * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, * version 2 with the GNU Classpath Exception, which is available at * https://www.gnu.org/software/classpath/license.html. * * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 */ package org.glassfish.jersey.jetty.connector; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.FilterInputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.CookieStore; import java.net.URI; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.concurrent.CancellationException; import java.util.concurrent.CompletableFuture; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicReference; import java.util.logging.Level; import java.util.logging.Logger; import javax.ws.rs.ProcessingException; import javax.ws.rs.client.Client; import javax.ws.rs.core.Configuration; import javax.ws.rs.core.MultivaluedMap; import javax.net.ssl.SSLContext; import org.eclipse.jetty.client.dynamic.HttpClientTransportDynamic; import org.eclipse.jetty.client.util.BasicAuthentication; import org.eclipse.jetty.client.util.BytesContentProvider; import org.eclipse.jetty.client.util.FutureResponseListener; import org.eclipse.jetty.client.util.OutputStreamContentProvider; import org.eclipse.jetty.io.ClientConnector; import org.glassfish.jersey.client.ClientProperties; import org.glassfish.jersey.client.ClientRequest; import org.glassfish.jersey.client.ClientResponse; import org.glassfish.jersey.client.spi.AsyncConnectorCallback; import org.glassfish.jersey.client.spi.Connector; import org.glassfish.jersey.internal.util.collection.ByteBufferInputStream; import org.glassfish.jersey.internal.util.collection.NonBlockingInputStream; import org.glassfish.jersey.message.internal.HeaderUtils; import org.glassfish.jersey.message.internal.OutboundMessageContext; import org.glassfish.jersey.message.internal.Statuses; import org.eclipse.jetty.client.HttpClient; import org.eclipse.jetty.client.HttpProxy; import org.eclipse.jetty.client.ProxyConfiguration; import org.eclipse.jetty.client.api.AuthenticationStore; import org.eclipse.jetty.client.api.ContentProvider; import org.eclipse.jetty.client.api.ContentResponse; import org.eclipse.jetty.client.api.Request; import org.eclipse.jetty.client.api.Response; import org.eclipse.jetty.client.api.Result; import org.eclipse.jetty.http.HttpField; import org.eclipse.jetty.http.HttpFields; import org.eclipse.jetty.http.HttpHeader; import org.eclipse.jetty.util.HttpCookieStore; import org.eclipse.jetty.util.Jetty; import org.eclipse.jetty.util.ssl.SslContextFactory; import org.eclipse.jetty.util.thread.QueuedThreadPool; /** * A {@link Connector} that utilizes the Jetty HTTP Client to send and receive * HTTP request and responses. *

* The following properties are only supported at construction of this class: *

    *
  • {@link ClientProperties#ASYNC_THREADPOOL_SIZE}
  • *
  • {@link ClientProperties#CONNECT_TIMEOUT}
  • *
  • {@link ClientProperties#FOLLOW_REDIRECTS}
  • *
  • {@link ClientProperties#PROXY_URI}
  • *
  • {@link ClientProperties#PROXY_USERNAME}
  • *
  • {@link ClientProperties#PROXY_PASSWORD}
  • *
  • {@link ClientProperties#PROXY_PASSWORD}
  • *
  • {@link JettyClientProperties#PREEMPTIVE_BASIC_AUTHENTICATION}
  • *
  • {@link JettyClientProperties#DISABLE_COOKIES}
  • *
*

* This transport supports both synchronous and asynchronous processing of client requests. * The following methods are supported: GET, POST, PUT, DELETE, HEAD, OPTIONS, TRACE, CONNECT and MOVE. *

* Typical usage: *

*

 * {@code
 * ClientConfig config = new ClientConfig();
 * Connector connector = new JettyConnector(config);
 * config.connector(connector);
 * Client client = ClientBuilder.newClient(config);
 *
 * // async request
 * WebTarget target = client.target("http://localhost:8080");
 * Future future = target.path("resource").request().async().get();
 *
 * // wait for 3 seconds
 * Response response = future.get(3, TimeUnit.SECONDS);
 * String entity = response.readEntity(String.class);
 * client.close();
 * }
 * 
*

* This connector supports only {@link org.glassfish.jersey.client.RequestEntityProcessing#BUFFERED entity buffering}. * Defining the property {@link ClientProperties#REQUEST_ENTITY_PROCESSING} has no effect on this connector. *

* * Adapted from org.glassfish.jersey.jetty.connector.JettyConnector for Jetty 10: * - updated SSL context initialization * - updated header handling * * @author Arul Dhesiaseelan (aruld at acm.org) * @author Marek Potociar */ public class Jetty10Connector implements Connector { private static final Logger LOGGER = Logger.getLogger(Jetty10Connector.class.getName()); private final HttpClient client; private final CookieStore cookieStore; private final Configuration configuration; private final Optional syncListenerResponseMaxSize; /** * Create the new Jetty client connector. * * @param jaxrsClient JAX-RS client instance, for which the connector is created. * @param config client configuration. */ public Jetty10Connector(final Client jaxrsClient, final Configuration config) { this.configuration = config; HttpClient httpClient = null; if (config.isRegistered(JettyHttpClientSupplier.class)) { Optional contract = config.getInstances().stream() .filter(a-> JettyHttpClientSupplier.class.isInstance(a)).findFirst(); if (contract.isPresent()) { httpClient = ((JettyHttpClientSupplier) contract.get()).getHttpClient(); } } if (httpClient == null) { final SSLContext sslContext = jaxrsClient.getSslContext(); final SslContextFactory.Client sslContextFactory = new SslContextFactory.Client(); sslContextFactory.setSslContext(sslContext); ClientConnector clientConnector = new ClientConnector(); clientConnector.setSslContextFactory(sslContextFactory); httpClient = new HttpClient(new HttpClientTransportDynamic(clientConnector)); } this.client = httpClient; Boolean enableHostnameVerification = (Boolean) config.getProperties() .get(JettyClientProperties.ENABLE_SSL_HOSTNAME_VERIFICATION); if (enableHostnameVerification != null && enableHostnameVerification) { client.getSslContextFactory().setEndpointIdentificationAlgorithm("https"); } final Object connectTimeout = config.getProperties().get(ClientProperties.CONNECT_TIMEOUT); if (connectTimeout != null && connectTimeout instanceof Integer && (Integer) connectTimeout > 0) { client.setConnectTimeout((Integer) connectTimeout); } final Object threadPoolSize = config.getProperties().get(ClientProperties.ASYNC_THREADPOOL_SIZE); if (threadPoolSize != null && threadPoolSize instanceof Integer && (Integer) threadPoolSize > 0) { final String name = HttpClient.class.getSimpleName() + "@" + hashCode(); final QueuedThreadPool threadPool = new QueuedThreadPool((Integer) threadPoolSize); threadPool.setName(name); client.setExecutor(threadPool); } Boolean disableCookies = (Boolean) config.getProperties().get(JettyClientProperties.DISABLE_COOKIES); disableCookies = (disableCookies != null) ? disableCookies : false; final AuthenticationStore auth = client.getAuthenticationStore(); final Object basicAuthProvider = config.getProperty(JettyClientProperties.PREEMPTIVE_BASIC_AUTHENTICATION); if (basicAuthProvider != null && (basicAuthProvider instanceof BasicAuthentication)) { auth.addAuthentication((BasicAuthentication) basicAuthProvider); } final Object proxyUri = config.getProperties().get(ClientProperties.PROXY_URI); if (proxyUri != null) { final URI u = getProxyUri(proxyUri); final ProxyConfiguration proxyConfig = client.getProxyConfiguration(); proxyConfig.getProxies().add(new HttpProxy(u.getHost(), u.getPort())); final Object proxyUsername = config.getProperties().get(ClientProperties.PROXY_USERNAME); if (proxyUsername != null) { final Object proxyPassword = config.getProperties().get(ClientProperties.PROXY_PASSWORD); auth.addAuthentication(new BasicAuthentication(u, "<>", String.valueOf(proxyUsername), String.valueOf(proxyPassword))); } } if (disableCookies) { client.setCookieStore(new HttpCookieStore.Empty()); } final Object slResponseMaxSize = configuration.getProperties() .get(JettyClientProperties.SYNC_LISTENER_RESPONSE_MAX_SIZE); if (slResponseMaxSize != null && slResponseMaxSize instanceof Integer && (Integer) slResponseMaxSize > 0) { this.syncListenerResponseMaxSize = Optional.of((Integer) slResponseMaxSize); } else { this.syncListenerResponseMaxSize = Optional.empty(); } try { client.start(); } catch (final Exception e) { throw new ProcessingException("Failed to start the client.", e); } this.cookieStore = client.getCookieStore(); } @SuppressWarnings("ChainOfInstanceofChecks") private static URI getProxyUri(final Object proxy) { if (proxy instanceof URI) { return (URI) proxy; } else if (proxy instanceof String) { return URI.create((String) proxy); } else { throw new ProcessingException(LocalizationMessages.WRONG_PROXY_URI_TYPE(ClientProperties.PROXY_URI)); } } /** * Get the {@link HttpClient}. * * @return the {@link HttpClient}. */ @SuppressWarnings("UnusedDeclaration") public HttpClient getHttpClient() { return client; } /** * Get the {@link CookieStore}. * * @return the {@link CookieStore} instance or null when * JettyClientProperties.DISABLE_COOKIES set to true. */ public CookieStore getCookieStore() { return cookieStore; } @Override public ClientResponse apply(final ClientRequest jerseyRequest) throws ProcessingException { final Request jettyRequest = translateRequest(jerseyRequest); final Map clientHeadersSnapshot = writeOutBoundHeaders(jerseyRequest.getHeaders(), jettyRequest); final ContentProvider entity = getBytesProvider(jerseyRequest); if (entity != null) { jettyRequest.content(entity); } try { final ContentResponse jettyResponse; if (!syncListenerResponseMaxSize.isPresent()) { jettyResponse = jettyRequest.send(); } else { final FutureResponseListener listener = new FutureResponseListener(jettyRequest, syncListenerResponseMaxSize.get()); jettyRequest.send(listener); jettyResponse = listener.get(); } HeaderUtils.checkHeaderChanges(clientHeadersSnapshot, jerseyRequest.getHeaders(), Jetty10Connector.this.getClass().getName(), jerseyRequest.getConfiguration()); final javax.ws.rs.core.Response.StatusType status = jettyResponse.getReason() == null ? Statuses.from(jettyResponse.getStatus()) : Statuses.from(jettyResponse.getStatus(), jettyResponse.getReason()); final ClientResponse jerseyResponse = new ClientResponse(status, jerseyRequest); processResponseHeaders(jettyResponse.getHeaders(), jerseyResponse); try { jerseyResponse.setEntityStream(new Jetty10Connector.HttpClientResponseInputStream(jettyResponse)); } catch (final IOException e) { LOGGER.log(Level.SEVERE, null, e); } return jerseyResponse; } catch (final Exception e) { throw new ProcessingException(e); } } private static void processResponseHeaders(final HttpFields respHeaders, final ClientResponse jerseyResponse) { for (final HttpField header : respHeaders) { final String headerName = header.getName(); final MultivaluedMap headers = jerseyResponse.getHeaders(); List list = headers.get(headerName); if (list == null) { list = new ArrayList<>(); } list.add(header.getValue()); headers.put(headerName, list); } } private static final class HttpClientResponseInputStream extends FilterInputStream { HttpClientResponseInputStream(final ContentResponse jettyResponse) throws IOException { super(getInputStream(jettyResponse)); } private static InputStream getInputStream(final ContentResponse response) { return new ByteArrayInputStream(response.getContent()); } } private Request translateRequest(final ClientRequest clientRequest) { final URI uri = clientRequest.getUri(); final Request request = client.newRequest(uri); request.method(clientRequest.getMethod()); request.followRedirects(clientRequest.resolveProperty(ClientProperties.FOLLOW_REDIRECTS, true)); final Object readTimeout = clientRequest.resolveProperty(ClientProperties.READ_TIMEOUT, -1); if (readTimeout != null && readTimeout instanceof Integer && (Integer) readTimeout > 0) { request.timeout((Integer) readTimeout, TimeUnit.MILLISECONDS); } return request; } private Map writeOutBoundHeaders(final MultivaluedMap headers, final Request request) { final Map stringHeaders = HeaderUtils.asStringHeadersSingleValue(headers, configuration); // remove User-agent header set by Jetty; Jersey already sets this in its request (incl. Jetty version) request.headers(httpFields -> { httpFields.remove(HttpHeader.USER_AGENT); for (final Map.Entry e : stringHeaders.entrySet()) { httpFields.add(e.getKey(), e.getValue()); } }); return stringHeaders; } private ContentProvider getBytesProvider(final ClientRequest clientRequest) { final Object entity = clientRequest.getEntity(); if (entity == null) { return null; } final ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); clientRequest.setStreamProvider(new OutboundMessageContext.StreamProvider() { @Override public OutputStream getOutputStream(final int contentLength) throws IOException { return outputStream; } }); try { clientRequest.writeEntity(); } catch (final IOException e) { throw new ProcessingException("Failed to write request entity.", e); } return new BytesContentProvider(outputStream.toByteArray()); } private ContentProvider getStreamProvider(final ClientRequest clientRequest) { final Object entity = clientRequest.getEntity(); if (entity == null) { return null; } final OutputStreamContentProvider streamContentProvider = new OutputStreamContentProvider(); clientRequest.setStreamProvider(new OutboundMessageContext.StreamProvider() { @Override public OutputStream getOutputStream(final int contentLength) throws IOException { return streamContentProvider.getOutputStream(); } }); return streamContentProvider; } private void processContent(final ClientRequest clientRequest, final ContentProvider entity) throws IOException { if (entity == null) { return; } final OutputStreamContentProvider streamContentProvider = (OutputStreamContentProvider) entity; try (final OutputStream output = streamContentProvider.getOutputStream()) { clientRequest.writeEntity(); } } @Override public Future apply(final ClientRequest jerseyRequest, final AsyncConnectorCallback callback) { final Request jettyRequest = translateRequest(jerseyRequest); final Map clientHeadersSnapshot = writeOutBoundHeaders(jerseyRequest.getHeaders(), jettyRequest); final ContentProvider entity = getStreamProvider(jerseyRequest); if (entity != null) { jettyRequest.content(entity); } final AtomicBoolean callbackInvoked = new AtomicBoolean(false); final Throwable failure; try { final CompletableFuture responseFuture = new CompletableFuture().whenComplete( (clientResponse, throwable) -> { if (throwable != null && throwable instanceof CancellationException) { // take care of future cancellation jettyRequest.abort(throwable); } }); final AtomicReference jerseyResponse = new AtomicReference<>(); final ByteBufferInputStream entityStream = new ByteBufferInputStream(); jettyRequest.send(new Response.Listener.Adapter() { @Override public void onHeaders(final Response jettyResponse) { HeaderUtils.checkHeaderChanges(clientHeadersSnapshot, jerseyRequest.getHeaders(), Jetty10Connector.this.getClass().getName(), jerseyRequest.getConfiguration()); if (responseFuture.isDone()) { if (!callbackInvoked.compareAndSet(false, true)) { return; } } final ClientResponse response = translateResponse(jerseyRequest, jettyResponse, entityStream); jerseyResponse.set(response); } @Override public void onContent(final Response jettyResponse, final ByteBuffer content) { try { // content must be consumed before returning from this method. if (content.hasArray()) { byte[] array = content.array(); byte[] buff = new byte[content.remaining()]; System.arraycopy(array, content.arrayOffset(), buff, 0, content.remaining()); entityStream.put(ByteBuffer.wrap(buff)); } else { byte[] buff = new byte[content.remaining()]; content.get(buff); entityStream.put(ByteBuffer.wrap(buff)); } } catch (final InterruptedException ex) { final ProcessingException pe = new ProcessingException(ex); entityStream.closeQueue(pe); // try to complete the future with an exception responseFuture.completeExceptionally(pe); Thread.currentThread().interrupt(); } } @Override public void onComplete(final Result result) { entityStream.closeQueue(); if (!callbackInvoked.get()) { callback.response(jerseyResponse.get()); } responseFuture.complete(jerseyResponse.get()); } @Override public void onFailure(final Response response, final Throwable t) { entityStream.closeQueue(t); // try to complete the future with an exception responseFuture.completeExceptionally(t); if (callbackInvoked.compareAndSet(false, true)) { callback.failure(t); } } }); processContent(jerseyRequest, entity); return responseFuture; } catch (final Throwable t) { failure = t; } if (callbackInvoked.compareAndSet(false, true)) { callback.failure(failure); } CompletableFuture future = new CompletableFuture<>(); future.completeExceptionally(failure); return future; } private static ClientResponse translateResponse(final ClientRequest jerseyRequest, final org.eclipse.jetty.client.api.Response jettyResponse, final NonBlockingInputStream entityStream) { final ClientResponse jerseyResponse = new ClientResponse(Statuses.from(jettyResponse.getStatus()), jerseyRequest); processResponseHeaders(jettyResponse.getHeaders(), jerseyResponse); jerseyResponse.setEntityStream(entityStream); return jerseyResponse; } @Override public String getName() { return "Jetty HttpClient " + Jetty.VERSION; } @Override public void close() { try { client.stop(); } catch (final Exception e) { throw new ProcessingException("Failed to stop the client.", e); } } } ================================================ FILE: components/jax-rs/jersey/src/main/resources/META-INF/services/com.kumuluz.ee.common.Component ================================================ com.kumuluz.ee.jaxrs.JaxRsComponent ================================================ FILE: components/jax-rs/jersey/src/main/resources/META-INF/services/org.glassfish.jersey.client.spi.ConnectorProvider ================================================ com.kumuluz.ee.jaxrs.Jetty10ConnectorProvider ================================================ FILE: components/jax-rs/pom.xml ================================================ kumuluzee-components com.kumuluz.ee 4.2.0-SNAPSHOT 4.0.0 pom KumuluzEE JAX-RS KumuluzEE JAX-RS component jersey kumuluzee-jax-rs ================================================ FILE: components/jax-ws/cxf/pom.xml ================================================ kumuluzee-jax-ws com.kumuluz.ee 4.2.0-SNAPSHOT 4.0.0 KumuluzEE JAX-WS CXF KumuluzEE JAX-WS component implemented by CXF kumuluzee-jax-ws-cxf com.kumuluz.ee kumuluzee-common com.kumuluz.ee kumuluzee-cdi-weld provided org.apache.cxf cxf ${cxf.version} pom org.apache.cxf cxf-rt-frontend-jaxws ${cxf.version} org.apache.cxf cxf-rt-transports-http ${cxf.version} com.sun.xml.ws jaxws-tools ${jaxws-tools.version} javax.activation activation ${activation.version} junit junit test maven-compiler-plugin ${maven-compiler-plugin.version} default-compile compile none compile-important-processor process-test-sources testCompile none com/kumuluz/ee/jaxws/cxf/processor/* ================================================ FILE: components/jax-ws/cxf/src/main/java/com/kumuluz/ee/jaxws/cxf/JaxWsComponent.java ================================================ /* * Copyright (c) 2014-2018 Kumuluz and/or its affiliates * and other contributors as indicated by the @author tags and * the contributor list. * * Licensed under the MIT License (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://opensource.org/licenses/MIT * * The software is provided "AS IS", WITHOUT WARRANTY OF ANY KIND, express or * implied, including but not limited to the warranties of merchantability, * fitness for a particular purpose and noninfringement. in no event shall the * authors or copyright holders be liable for any claim, damages or other * liability, whether in an action of contract, tort or otherwise, arising from, * out of or in connection with the software or the use or other dealings in the * software. See the License for the specific language governing permissions and * limitations under the License. */ package com.kumuluz.ee.jaxws.cxf; import com.kumuluz.ee.common.Component; import com.kumuluz.ee.common.ServletServer; import com.kumuluz.ee.common.config.EeConfig; import com.kumuluz.ee.common.dependencies.EeComponentDef; import com.kumuluz.ee.common.dependencies.EeComponentDependency; import com.kumuluz.ee.common.dependencies.EeComponentType; import com.kumuluz.ee.common.runtime.EeRuntime; import com.kumuluz.ee.common.wrapper.KumuluzServerWrapper; import com.kumuluz.ee.jaxws.cxf.processor.JaxWsAnnotationProcessorUtil; import java.util.HashMap; import java.util.Map; import java.util.logging.Logger; /** * @author gpor89 * @since 3.0.0 */ @EeComponentDef(name = "CXF", type = EeComponentType.JAX_WS) @EeComponentDependency(value = EeComponentType.SERVLET) public class JaxWsComponent implements Component { private static final Logger LOG = Logger.getLogger(JaxWsComponent.class.getSimpleName()); @Override public void init(KumuluzServerWrapper server, EeConfig eeConfig) { LOG.info("Initiating CXF"); // Check if CDI is present in the runtime Boolean cdiPresent = EeRuntime.getInstance().getEeComponents().stream().anyMatch(c -> c.getType().equals(EeComponentType.CDI)); LOG.fine("CXF component will run with" + (cdiPresent ? "" : "out") + " CDI"); final ServletServer kumuluzServer = (ServletServer) server.getServer(); final String baseUrl = server.getServer().getServerConfig().getBaseUrl(); final JaxWsAnnotationProcessorUtil wsInstance = JaxWsAnnotationProcessorUtil.getInstance(); wsInstance.setContextRoot(baseUrl); final Map servletParams = new HashMap<>(); servletParams.put(KumuluzCXFServlet.CDI_INIT_PARAM, cdiPresent.toString()); String contextRoot = wsInstance.getContextRoot(); LOG.fine(KumuluzCXFServlet.class.getName() + " mapping set to " + contextRoot); kumuluzServer.registerServlet(KumuluzCXFServlet.class, contextRoot, servletParams); } @Override public void load() { LOG.info("CXF component initialized"); } } ================================================ FILE: components/jax-ws/cxf/src/main/java/com/kumuluz/ee/jaxws/cxf/KumuluzCXFServlet.java ================================================ /* * Copyright (c) 2014-2018 Kumuluz and/or its affiliates * and other contributors as indicated by the @author tags and * the contributor list. * * Licensed under the MIT License (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://opensource.org/licenses/MIT * * The software is provided "AS IS", WITHOUT WARRANTY OF ANY KIND, express or * implied, including but not limited to the warranties of merchantability, * fitness for a particular purpose and noninfringement. in no event shall the * authors or copyright holders be liable for any claim, damages or other * liability, whether in an action of contract, tort or otherwise, arising from, * out of or in connection with the software or the use or other dealings in the * software. See the License for the specific language governing permissions and * limitations under the License. */ package com.kumuluz.ee.jaxws.cxf; import com.kumuluz.ee.jaxws.cxf.processor.JaxWsAnnotationProcessorUtil; import com.kumuluz.ee.jaxws.cxf.ws.CXFWebservicePublisher; import com.kumuluz.ee.jaxws.cxf.ws.Endpoint; import org.apache.cxf.transport.servlet.CXFNonSpringServlet; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import java.util.List; /** * @author gpor89 * @since 3.0.0 */ public class KumuluzCXFServlet extends CXFNonSpringServlet { protected static final String CDI_INIT_PARAM = "useCdi"; private List endpoints; public void init() throws ServletException { super.init(); final JaxWsAnnotationProcessorUtil wsInstance = JaxWsAnnotationProcessorUtil.getInstance(); this.endpoints = wsInstance.getEndpointList(); } @Override protected void loadBus(ServletConfig sc) { super.loadBus(sc); boolean cdiPresent = "true".equalsIgnoreCase(getInitParameter(CDI_INIT_PARAM)); final CXFWebservicePublisher publisher = new CXFWebservicePublisher(); endpoints.stream().forEach(e -> publisher.publish(e, bus, cdiPresent)); publisher.close(); } } ================================================ FILE: components/jax-ws/cxf/src/main/java/com/kumuluz/ee/jaxws/cxf/annotations/WsContext.java ================================================ /* * Copyright (c) 2014-2018 Kumuluz and/or its affiliates * and other contributors as indicated by the @author tags and * the contributor list. * * Licensed under the MIT License (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://opensource.org/licenses/MIT * * The software is provided "AS IS", WITHOUT WARRANTY OF ANY KIND, express or * implied, including but not limited to the warranties of merchantability, * fitness for a particular purpose and noninfringement. in no event shall the * authors or copyright holders be liable for any claim, damages or other * liability, whether in an action of contract, tort or otherwise, arising from, * out of or in connection with the software or the use or other dealings in the * software. See the License for the specific language governing permissions and * limitations under the License. */ package com.kumuluz.ee.jaxws.cxf.annotations; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * @author gpor89 * @since 3.0.0 */ @Retention(value = RetentionPolicy.RUNTIME) @Target(value = {ElementType.TYPE}) public @interface WsContext { /** * Root path where webservice is about to be published */ String contextRoot() default "/*"; /** * Relative path, appended to contextRoot provided */ String urlPattern() default ""; } ================================================ FILE: components/jax-ws/cxf/src/main/java/com/kumuluz/ee/jaxws/cxf/processor/AnnotationProcessorUtil.java ================================================ /* * Copyright (c) 2014-2018 Kumuluz and/or its affiliates * and other contributors as indicated by the @author tags and * the contributor list. * * Licensed under the MIT License (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://opensource.org/licenses/MIT * * The software is provided "AS IS", WITHOUT WARRANTY OF ANY KIND, express or * implied, including but not limited to the warranties of merchantability, * fitness for a particular purpose and noninfringement. in no event shall the * authors or copyright holders be liable for any claim, damages or other * liability, whether in an action of contract, tort or otherwise, arising from, * out of or in connection with the software or the use or other dealings in the * software. See the License for the specific language governing permissions and * limitations under the License. */ package com.kumuluz.ee.jaxws.cxf.processor; import javax.annotation.processing.Filer; import javax.tools.FileObject; import javax.tools.StandardLocation; import java.io.*; import java.nio.file.NoSuchFileException; import java.util.Set; /** * @author gpor89 * @since 3.0.0 */ public class AnnotationProcessorUtil { public static void writeFile(Set content, String resourceName, Filer filer) throws IOException { FileObject file = readOldFile(content, resourceName, filer); if (file != null) { try { writeFile(content, resourceName, file, filer); return; } catch (IllegalStateException ignored) { } } writeFile(content, resourceName, null, filer); } private static void writeFile(Set content, String resourceName, FileObject overrideFile, Filer filer) throws IOException { FileObject file = overrideFile; if (file == null) { file = filer.createResource(StandardLocation.CLASS_OUTPUT, "", resourceName); } try (Writer writer = file.openWriter()) { for (String serviceClassName : content) { writer.write(serviceClassName); writer.write(System.lineSeparator()); } } } private static FileObject readOldFile(Set content, String resourceName, Filer filer) throws IOException { Reader reader = null; try { final FileObject resource = filer.getResource(StandardLocation.CLASS_OUTPUT, "", resourceName); reader = resource.openReader(true); readOldFile(content, reader); return resource; } catch (NoSuchFileException | FileNotFoundException e) { // close reader, return null } finally { if (reader != null) { reader.close(); } } return null; } private static void readOldFile(Set content, Reader reader) throws IOException { try (BufferedReader bufferedReader = new BufferedReader(reader)) { String line = bufferedReader.readLine(); while (line != null) { content.add(line); line = bufferedReader.readLine(); } } } } ================================================ FILE: components/jax-ws/cxf/src/main/java/com/kumuluz/ee/jaxws/cxf/processor/JaxWsAnnotationProcessor.java ================================================ /* * Copyright (c) 2014-2018 Kumuluz and/or its affiliates * and other contributors as indicated by the @author tags and * the contributor list. * * Licensed under the MIT License (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://opensource.org/licenses/MIT * * The software is provided "AS IS", WITHOUT WARRANTY OF ANY KIND, express or * implied, including but not limited to the warranties of merchantability, * fitness for a particular purpose and noninfringement. in no event shall the * authors or copyright holders be liable for any claim, damages or other * liability, whether in an action of contract, tort or otherwise, arising from, * out of or in connection with the software or the use or other dealings in the * software. See the License for the specific language governing permissions and * limitations under the License. */ package com.kumuluz.ee.jaxws.cxf.processor; import javax.annotation.processing.AbstractProcessor; import javax.annotation.processing.Filer; import javax.annotation.processing.ProcessingEnvironment; import javax.annotation.processing.RoundEnvironment; import javax.jws.WebService; import javax.lang.model.SourceVersion; import javax.lang.model.element.Element; import javax.lang.model.element.ElementKind; import javax.lang.model.element.TypeElement; import java.io.IOException; import java.util.Collections; import java.util.HashSet; import java.util.Set; import java.util.logging.Logger; /** * @author gpor89 * @since 3.0.0 */ public class JaxWsAnnotationProcessor extends AbstractProcessor { private static final Logger LOG = Logger.getLogger(JaxWsAnnotationProcessor.class.getName()); private Filer filer; @Override public SourceVersion getSupportedSourceVersion() { return SourceVersion.latest(); } @Override public Set getSupportedAnnotationTypes() { return Collections.singleton("*"); } @Override public synchronized void init(ProcessingEnvironment processingEnv) { super.init(processingEnv); filer = processingEnv.getFiler(); } @Override public boolean process(Set annotations, RoundEnvironment roundEnv) { Set elements = roundEnv.getElementsAnnotatedWith(WebService.class); Set wsElementNames = new HashSet<>(); for (Element e : elements) { getElementName(wsElementNames, e); } try { if (!wsElementNames.isEmpty()) { AnnotationProcessorUtil.writeFile(wsElementNames, "META-INF/ws/java.lang.Object", filer); } } catch (IOException e) { LOG.warning(e.getMessage()); } return false; } private void getElementName(Set corsElementNames, Element e) { ElementKind elementKind = e.getKind(); if (elementKind.equals(ElementKind.CLASS)) { corsElementNames.add(e.toString()); } } } ================================================ FILE: components/jax-ws/cxf/src/main/java/com/kumuluz/ee/jaxws/cxf/processor/JaxWsAnnotationProcessorUtil.java ================================================ /* * Copyright (c) 2014-2018 Kumuluz and/or its affiliates * and other contributors as indicated by the @author tags and * the contributor list. * * Licensed under the MIT License (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://opensource.org/licenses/MIT * * The software is provided "AS IS", WITHOUT WARRANTY OF ANY KIND, express or * implied, including but not limited to the warranties of merchantability, * fitness for a particular purpose and noninfringement. in no event shall the * authors or copyright holders be liable for any claim, damages or other * liability, whether in an action of contract, tort or otherwise, arising from, * out of or in connection with the software or the use or other dealings in the * software. See the License for the specific language governing permissions and * limitations under the License. */ package com.kumuluz.ee.jaxws.cxf.processor; import com.kumuluz.ee.jaxws.cxf.annotations.WsContext; import com.kumuluz.ee.jaxws.cxf.ws.Endpoint; import javax.jws.WebService; import java.io.InputStream; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import java.util.Scanner; import java.util.logging.Logger; /** * @author gpor89 * @since 3.0.0 */ public class JaxWsAnnotationProcessorUtil { private static final Logger LOG = Logger.getLogger(JaxWsAnnotationProcessorUtil.class.getName()); private static final JaxWsAnnotationProcessorUtil INSTANCE = new JaxWsAnnotationProcessorUtil(); private static final String DEFAULT_CTX_ROOT = "/*"; private boolean initialized; private List endpointList; private String contextRoot; private JaxWsAnnotationProcessorUtil() { } public static synchronized JaxWsAnnotationProcessorUtil getInstance() { if (!INSTANCE.isInitialized()) { INSTANCE.init(); } return INSTANCE; } private void init() { contextRoot = DEFAULT_CTX_ROOT; endpointList = new LinkedList<>(); List> wsClasses = getWsClasses(); for (Class wsClass : wsClasses) { if (targetClassIsProxied(wsClass)) { wsClass = wsClass.getSuperclass(); } final WebService wsAnnotation = wsClass.getAnnotation(WebService.class); if (wsAnnotation == null) { continue; } WsContext wsContext = wsClass.getAnnotation(WsContext.class); String url = null; if (wsContext != null) { String annCtx = wsContext.contextRoot(); url = wsContext.urlPattern(); setContextRoot(annCtx); } endpointList.add(new Endpoint(wsClass, url, wsAnnotation)); } initialized = true; } private List> getWsClasses() { List> wsClasses = new ArrayList<>(); ClassLoader classLoader = getClass().getClassLoader(); InputStream is = classLoader.getResourceAsStream("META-INF/ws/java.lang.Object"); if (is != null) { Scanner scanner = new Scanner(is); while (scanner.hasNextLine()) { String className = scanner.nextLine(); try { Class resourceClass = Class.forName(className); wsClasses.add(resourceClass); } catch (ClassNotFoundException e) { e.printStackTrace(); } } scanner.close(); } return wsClasses; } private boolean targetClassIsProxied(Class targetClass) { return targetClass.getCanonicalName().contains("$Proxy"); } private boolean isInitialized() { return initialized; } public String getContextRoot() { return contextRoot; } public void setContextRoot(String contextRoot) { if (contextRoot != null) { if (!contextRoot.startsWith("/")) { contextRoot = "/" + contextRoot; } if (!contextRoot.endsWith("/*")) { contextRoot = contextRoot.endsWith("/") ? contextRoot + "*" : contextRoot + "/*"; } this.contextRoot = contextRoot; } } public List getEndpointList() { return endpointList; } protected void reinitialize() { init(); } } ================================================ FILE: components/jax-ws/cxf/src/main/java/com/kumuluz/ee/jaxws/cxf/ws/CXFWebservicePublisher.java ================================================ /* * Copyright (c) 2014-2018 Kumuluz and/or its affiliates * and other contributors as indicated by the @author tags and * the contributor list. * * Licensed under the MIT License (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://opensource.org/licenses/MIT * * The software is provided "AS IS", WITHOUT WARRANTY OF ANY KIND, express or * implied, including but not limited to the warranties of merchantability, * fitness for a particular purpose and noninfringement. in no event shall the * authors or copyright holders be liable for any claim, damages or other * liability, whether in an action of contract, tort or otherwise, arising from, * out of or in connection with the software or the use or other dealings in the * software. See the License for the specific language governing permissions and * limitations under the License. */ package com.kumuluz.ee.jaxws.cxf.ws; import org.apache.cxf.Bus; import org.apache.cxf.endpoint.Server; import org.apache.cxf.jaxws.JaxWsServerFactoryBean; import org.apache.cxf.jaxws.handler.AnnotationHandlerChainBuilder; import org.apache.cxf.service.invoker.Invoker; import javax.annotation.Resource; import javax.enterprise.inject.spi.CDI; import javax.naming.Context; import javax.naming.InitialContext; import javax.naming.NameAlreadyBoundException; import javax.naming.NamingException; import javax.xml.ws.WebServiceContext; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.util.logging.Logger; import java.util.stream.Stream; /** * @author gpor89 * @since 3.0.0 */ public class CXFWebservicePublisher { protected static final String JNDI_NAME_PREFIX = "java:comp/env/"; private static Logger LOG = Logger.getLogger(CXFWebservicePublisher.class.getSimpleName()); private Context context; public Server publish(final Endpoint endpoint, final Bus bus, final boolean cdiPresent) { final Class clazz = endpoint.getImplementationClass(); final String url = endpoint.getUrl(); //inject resources into WS instance Stream.of(clazz.getDeclaredFields()) .filter(f -> f.getType() == WebServiceContext.class) .forEach(f -> injectWebServiceResource(f, clazz)); final Object targetBean = getBean(clazz, cdiPresent); AnnotationHandlerChainBuilder builder = new AnnotationHandlerChainBuilder(bus); InjectionHelper.injectWebServiceContext(targetBean, KumuluzWebServiceContext.getInstance()); final Invoker invoker = new KumuluzWSInvoker(clazz, targetBean); final JaxWsServerFactoryBean fb = new JaxWsServerFactoryBean(); fb.setBlockPostConstruct(true); fb.setAddress(url); fb.setBus(bus); fb.setServiceClass(clazz); fb.setInvoker(invoker); fb.setHandlers(builder.buildHandlerChainFromClass(clazz, fb.getEndpointName(), fb.getServiceName(), fb.getBindingId())); if (endpoint.wsdlLocation() != null) { //top-down approach fb.setWsdlLocation(endpoint.wsdlLocation()); } Server server = fb.create(); LOG.info("Webservice endpoint published with address=" + fb.getAddress() + ", wsdlLocation=" + fb.getWsdlURL() + ", implementor=" + clazz.getName() + ", serviceName=" + endpoint.serviceName() + ", portName=" + endpoint.portName()); return server; } protected void injectWebServiceResource(final Field f, final Class clazz) { Resource annotation = f.getAnnotation(Resource.class); if (annotation != null) { String name = annotation.name(); String fieldName = f.getName(); if (context == null) { open(); } String bindName = null; try { if (name != null && !name.isEmpty()) { bindName = JNDI_NAME_PREFIX + name; } else { context.createSubcontext(JNDI_NAME_PREFIX + clazz.getName()); bindName = JNDI_NAME_PREFIX + clazz.getName() + "/" + fieldName; } context.bind(bindName, KumuluzWebServiceContext.getInstance()); } catch (NameAlreadyBoundException e) { } catch (NamingException e) { throw new RuntimeException("Unable to register jndi context for " + bindName, e); } } } private Object getBean(Class clazz, boolean cdiPresent) { //cdi if (cdiPresent) { return CDI.current().select(clazz).get(); } //pojo instance try { return clazz.getConstructor().newInstance(); } catch (InstantiationException | IllegalAccessException | InvocationTargetException | NoSuchMethodException e) { throw new RuntimeException("Unable to instantiate bean from " + clazz, e); } } private void open() { if (context == null) { try { context = new InitialContext(); } catch (NamingException e) { throw new RuntimeException("Unable to register jndi context", e); } } } public void close() { if (context != null) { try { context.close(); } catch (NamingException e) { LOG.severe("Cannot close context"); } } } } ================================================ FILE: components/jax-ws/cxf/src/main/java/com/kumuluz/ee/jaxws/cxf/ws/Endpoint.java ================================================ /* * Copyright (c) 2014-2018 Kumuluz and/or its affiliates * and other contributors as indicated by the @author tags and * the contributor list. * * Licensed under the MIT License (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://opensource.org/licenses/MIT * * The software is provided "AS IS", WITHOUT WARRANTY OF ANY KIND, express or * implied, including but not limited to the warranties of merchantability, * fitness for a particular purpose and noninfringement. in no event shall the * authors or copyright holders be liable for any claim, damages or other * liability, whether in an action of contract, tort or otherwise, arising from, * out of or in connection with the software or the use or other dealings in the * software. See the License for the specific language governing permissions and * limitations under the License. */ package com.kumuluz.ee.jaxws.cxf.ws; import javax.jws.WebService; /** * @author gpor89 * @since 3.0.0 */ public class Endpoint { private String url; private Class implementationClass; private WebService ws; public Endpoint(Class implementationClass, String url, WebService webService) { this.url = url; this.implementationClass = implementationClass; this.ws = webService; } public String getUrl() { return url != null ? url : defaultEndpointUrl(); } public Class getImplementationClass() { return implementationClass; } public String wsdlLocation() { if (ws == null) { return null; } return ws.wsdlLocation() != null && ws.wsdlLocation().isEmpty() ? null : ws.wsdlLocation(); } private String defaultEndpointUrl() { if (ws == null || implementationClass == null) { return null; } return "/" + implementationClass.getName(); } public String serviceName() { if (ws == null) { return null; } return ws.serviceName() != null && ws.serviceName().isEmpty() ? null : ws.serviceName(); } public String portName() { if (ws == null) { return null; } return ws.portName() != null && ws.portName().isEmpty() ? null : ws.portName(); } } ================================================ FILE: components/jax-ws/cxf/src/main/java/com/kumuluz/ee/jaxws/cxf/ws/InjectionHelper.java ================================================ /* * Copyright (c) 2014-2018 Kumuluz and/or its affiliates * and other contributors as indicated by the @author tags and * the contributor list. * * Licensed under the MIT License (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://opensource.org/licenses/MIT * * The software is provided "AS IS", WITHOUT WARRANTY OF ANY KIND, express or * implied, including but not limited to the warranties of merchantability, * fitness for a particular purpose and noninfringement. in no event shall the * authors or copyright holders be liable for any claim, damages or other * liability, whether in an action of contract, tort or otherwise, arising from, * out of or in connection with the software or the use or other dealings in the * software. See the License for the specific language governing permissions and * limitations under the License. */ package com.kumuluz.ee.jaxws.cxf.ws; import javax.annotation.Resource; import javax.xml.ws.WebServiceContext; import java.lang.reflect.Field; /** * @author gpor89 * @since 3.0.0 */ public final class InjectionHelper { private InjectionHelper() { } public static void injectWebServiceContext(final Object instance, final WebServiceContext ctx) { final Class instanceClass = instance.getClass(); //method injection not supported! // inject @Resource final Field[] resourceAnnotatedFields = instanceClass.getDeclaredFields(); for (Field field : resourceAnnotatedFields) { try { if (field.getDeclaredAnnotation(Resource.class) != null && field.getType() == WebServiceContext.class) { setField(instance, field, ctx); } } catch (Exception e) { throw new RuntimeException("Cannot inject @Resource annotated field: " + field, e); } } } private static void setField(final Object instance, final Field field, final Object value) { try { field.setAccessible(true); field.set(instance, value); } catch (Exception e) { throw new RuntimeException(e); } finally { field.setAccessible(field.isAccessible()); } } } ================================================ FILE: components/jax-ws/cxf/src/main/java/com/kumuluz/ee/jaxws/cxf/ws/KumuluzWSInvoker.java ================================================ /* * Copyright (c) 2014-2018 Kumuluz and/or its affiliates * and other contributors as indicated by the @author tags and * the contributor list. * * Licensed under the MIT License (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://opensource.org/licenses/MIT * * The software is provided "AS IS", WITHOUT WARRANTY OF ANY KIND, express or * implied, including but not limited to the warranties of merchantability, * fitness for a particular purpose and noninfringement. in no event shall the * authors or copyright holders be liable for any claim, damages or other * liability, whether in an action of contract, tort or otherwise, arising from, * out of or in connection with the software or the use or other dealings in the * software. See the License for the specific language governing permissions and * limitations under the License. */ package com.kumuluz.ee.jaxws.cxf.ws; import org.apache.cxf.helpers.CastUtils; import org.apache.cxf.jaxws.JAXWSMethodInvoker; import org.apache.cxf.jaxws.context.WebServiceContextImpl; import org.apache.cxf.message.Exchange; import org.apache.cxf.message.MessageContentsList; import org.apache.cxf.service.Service; import org.apache.cxf.service.invoker.Factory; import org.apache.cxf.service.invoker.Invoker; import org.apache.cxf.service.invoker.MethodDispatcher; import org.apache.cxf.service.model.BindingOperationInfo; import javax.xml.ws.WebServiceContext; import java.lang.reflect.Method; import java.util.List; /** * @author gpor89 * @since 3.0.0 */ public class KumuluzWSInvoker extends JAXWSMethodInvoker implements Invoker { private Class targetClass; private Object targetBean; public KumuluzWSInvoker(final Class targetClass, final Object targetBean) { super((Factory) null); this.targetClass = targetClass; this.targetBean = targetBean; } @Override public Object invoke(Exchange exchange, Object o) { BindingOperationInfo bop = exchange.get(BindingOperationInfo.class); MethodDispatcher md = (MethodDispatcher) exchange.get(Service.class).get(MethodDispatcher.class.getName()); List params = null; if (o instanceof List) { params = CastUtils.cast((List) o); } else if (o != null) { params = new MessageContentsList(o); } final Method method = adjustMethodAndParams(md.getMethod(bop), exchange, params, targetClass); return invoke(exchange, targetBean, method, params); } @Override protected Object performInvocation(Exchange exchange, final Object serviceObject, Method m, Object[] paramArray) throws Exception { WebServiceContext wsContext = new WebServiceContextImpl(null); try { KumuluzWebServiceContext.getInstance().setMessageContext(wsContext); return super.performInvocation(exchange, serviceObject, m, paramArray); } finally { KumuluzWebServiceContext.getInstance().setMessageContext(null); } } } ================================================ FILE: components/jax-ws/cxf/src/main/java/com/kumuluz/ee/jaxws/cxf/ws/KumuluzWebServiceContext.java ================================================ /* * Copyright (c) 2014-2018 Kumuluz and/or its affiliates * and other contributors as indicated by the @author tags and * the contributor list. * * Licensed under the MIT License (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://opensource.org/licenses/MIT * * The software is provided "AS IS", WITHOUT WARRANTY OF ANY KIND, express or * implied, including but not limited to the warranties of merchantability, * fitness for a particular purpose and noninfringement. in no event shall the * authors or copyright holders be liable for any claim, damages or other * liability, whether in an action of contract, tort or otherwise, arising from, * out of or in connection with the software or the use or other dealings in the * software. See the License for the specific language governing permissions and * limitations under the License. */ package com.kumuluz.ee.jaxws.cxf.ws; import org.w3c.dom.Element; import javax.xml.ws.EndpointReference; import javax.xml.ws.WebServiceContext; import javax.xml.ws.handler.MessageContext; import java.io.Serializable; import java.security.Principal; /** * @author gpor89 * @since 3.0.0 */ public final class KumuluzWebServiceContext implements WebServiceContext, Serializable { private static final long serialVersionUID = 6874657983243689841L; private static final KumuluzWebServiceContext WS_CONTEXT_SINGLETON = new KumuluzWebServiceContext(); private final transient ThreadLocal contexts = new InheritableThreadLocal<>(); public static KumuluzWebServiceContext getInstance() { return WS_CONTEXT_SINGLETON; } public EndpointReference getEndpointReference(final Element... referenceParameters) { return getWebServiceContext().getEndpointReference(referenceParameters); } public T getEndpointReference(final Class clazz, final Element... referenceParameters) { return getWebServiceContext().getEndpointReference(clazz, referenceParameters); } public MessageContext getMessageContext() { return getWebServiceContext().getMessageContext(); } public void setMessageContext(final WebServiceContext ctx) { this.contexts.set(ctx); } public Principal getUserPrincipal() { return getWebServiceContext().getUserPrincipal(); } public boolean isUserInRole(String role) { return getWebServiceContext().isUserInRole(role); } private WebServiceContext getWebServiceContext() { final WebServiceContext delegate = contexts.get(); if (delegate == null) { throw new IllegalStateException(); } return delegate; } } ================================================ FILE: components/jax-ws/cxf/src/main/resources/META-INF/services/com.kumuluz.ee.common.Component ================================================ com.kumuluz.ee.jaxws.cxf.JaxWsComponent ================================================ FILE: components/jax-ws/cxf/src/main/resources/META-INF/services/javax.annotation.processing.Processor ================================================ com.kumuluz.ee.jaxws.cxf.processor.JaxWsAnnotationProcessor ================================================ FILE: components/jax-ws/cxf/src/test/java/com/kumuluz/ee/jaxws/cxf/impl/NoWsContextAnnotatedEndpointBean.java ================================================ package com.kumuluz.ee.jaxws.cxf.impl; import javax.jws.WebService; @WebService public class NoWsContextAnnotatedEndpointBean { } ================================================ FILE: components/jax-ws/cxf/src/test/java/com/kumuluz/ee/jaxws/cxf/impl/WebServiceContextBean.java ================================================ package com.kumuluz.ee.jaxws.cxf.impl; import org.apache.cxf.jaxws.handler.logical.LogicalMessageContextImpl; import org.apache.cxf.message.MessageImpl; import org.w3c.dom.Element; import javax.xml.ws.EndpointReference; import javax.xml.ws.WebServiceContext; import javax.xml.ws.handler.MessageContext; import java.security.Principal; public class WebServiceContextBean implements WebServiceContext { MessageContext messageContext; public WebServiceContextBean(String id) { MessageImpl message = new MessageImpl(); message.put("id", id); messageContext = new LogicalMessageContextImpl(message); } @Override public MessageContext getMessageContext() { return messageContext; } @Override public Principal getUserPrincipal() { return null; } @Override public boolean isUserInRole(String role) { return false; } @Override public EndpointReference getEndpointReference(Element... referenceParameters) { return null; } @Override public T getEndpointReference(Class clazz, Element... referenceParameters) { return null; } } ================================================ FILE: components/jax-ws/cxf/src/test/java/com/kumuluz/ee/jaxws/cxf/impl/WsContextAnnotatedEndpoint.java ================================================ package com.kumuluz.ee.jaxws.cxf.impl; public interface WsContextAnnotatedEndpoint { } ================================================ FILE: components/jax-ws/cxf/src/test/java/com/kumuluz/ee/jaxws/cxf/impl/WsContextAnnotatedEndpointBean.java ================================================ package com.kumuluz.ee.jaxws.cxf.impl; import com.kumuluz.ee.jaxws.cxf.annotations.WsContext; import javax.jws.WebService; @WsContext(contextRoot = WsContextAnnotatedEndpointBean.CTX_ROOT, urlPattern = WsContextAnnotatedEndpointBean.URL_PATTERN) @WebService(wsdlLocation = WsContextAnnotatedEndpointBean.WSDL_URL, portName = WsContextAnnotatedEndpointBean.PORT, serviceName = WsContextAnnotatedEndpointBean.SERVICE, endpointInterface = WsContextAnnotatedEndpointBean.INTERFACE) public class WsContextAnnotatedEndpointBean implements WsContextAnnotatedEndpoint { public static final String WSDL_URL = "http://cloud.si/example.wsdl"; public static final String CTX_ROOT = "/ws/*"; public static final String URL_PATTERN = "/endpoint"; public static final String PORT = "EndpointPort"; public static final String SERVICE = "ServiceName"; public static final String INTERFACE = "com.kumuluz.ee.jaxws.cxf.impl.WsContextAnnotatedEndpoint"; } ================================================ FILE: components/jax-ws/cxf/src/test/java/com/kumuluz/ee/jaxws/cxf/processor/JaxWsAnnotationProcessorUtilTest.java ================================================ package com.kumuluz.ee.jaxws.cxf.processor; import com.kumuluz.ee.jaxws.cxf.impl.NoWsContextAnnotatedEndpointBean; import com.kumuluz.ee.jaxws.cxf.impl.WsContextAnnotatedEndpointBean; import org.junit.Test; import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.net.URL; import java.net.URLDecoder; import java.util.stream.Stream; import static org.junit.Assert.*; public class JaxWsAnnotationProcessorUtilTest { private JaxWsAnnotationProcessorUtil instance = JaxWsAnnotationProcessorUtil.getInstance(); @Test public void shouldReturnDefaultWsInfo() { String className = NoWsContextAnnotatedEndpointBean.class.getName(); Class clazz = NoWsContextAnnotatedEndpointBean.class; prepareEndpointList(className); instance.reinitialize(); String expectedContextRoot = "/*"; String expectedUrl = "/" + className; //check implementation class assertEquals("Ws endpoint returned wrong implementation value", clazz, instance.getEndpointList().get(0).getImplementationClass()); //assert @WsContext assertEquals("Ws endpoint without defined contextRoot returned wrong value", expectedContextRoot, instance.getContextRoot()); assertFalse(instance.getEndpointList().isEmpty()); assertEquals("Ws endpoint without defined url returned wrong value", expectedUrl, instance.getEndpointList().get(0).getUrl()); //assert @Webservice assertNull("Ws endpoint without defined wsdlLocation returned wrong value", instance.getEndpointList().get(0).wsdlLocation()); assertNull("Ws endpoint without defined wsdlLocation returned wrong value", instance.getEndpointList().get(0).portName()); assertNull("Ws endpoint without defined wsdlLocation returned wrong value", instance.getEndpointList().get(0).serviceName()); } @Test public void shouldReturnConfiguredWsInfo() { String className = WsContextAnnotatedEndpointBean.class.getName(); Class clazz = WsContextAnnotatedEndpointBean.class; prepareEndpointList(className); instance.reinitialize(); //check implementation class assertEquals("Ws endpoint returned wrong implementation value", clazz, instance.getEndpointList().get(0).getImplementationClass()); //assert @WsContext assertEquals("Ws endpoint without defined contextRoot returned wrong value", WsContextAnnotatedEndpointBean.CTX_ROOT, instance.getContextRoot()); assertFalse(instance.getEndpointList().isEmpty()); assertEquals("Ws endpoint without defined url returned wrong value", WsContextAnnotatedEndpointBean.URL_PATTERN, instance.getEndpointList().get(0) .getUrl()); //assert @Webservice assertEquals("Ws endpoint without defined wsdlLocation returned wrong value", WsContextAnnotatedEndpointBean.WSDL_URL, instance.getEndpointList() .get(0).wsdlLocation()); assertEquals("Ws endpoint without defined wsdlLocation returned wrong value", WsContextAnnotatedEndpointBean.PORT, instance.getEndpointList() .get(0).portName()); assertEquals("Ws endpoint without defined wsdlLocation returned wrong value", WsContextAnnotatedEndpointBean.SERVICE, instance.getEndpointList() .get(0).serviceName()); } //helper method private void prepareEndpointList(String... endpoints) { URL url = this.getClass().getClassLoader().getResource("META-INF/ws/java.lang.Object"); if (url == null) { throw new RuntimeException("Service file not found."); } try (PrintWriter out = new PrintWriter(new File(URLDecoder.decode(url.getFile(), "UTF-8")))) { Stream.of(endpoints).forEach(out::print); out.flush(); } catch (IOException fe) { fe.printStackTrace(); } } } ================================================ FILE: components/jax-ws/cxf/src/test/java/com/kumuluz/ee/jaxws/cxf/ws/KumuluzWebServiceContextTest.java ================================================ package com.kumuluz.ee.jaxws.cxf.ws; import com.kumuluz.ee.jaxws.cxf.impl.WebServiceContextBean; import org.junit.Test; import static org.junit.Assert.assertTrue; public class KumuluzWebServiceContextTest { @Test public void shouldUseRightContext() throws InterruptedException { WsThread one = new WsThread(); WsThread two = new WsThread(); one.start(); two.start(); one.join(); two.join(); assertTrue("Thread 1 context not properly propagated", one.isSuccessful()); assertTrue("Thread 2 context not properly propagated", two.isSuccessful()); } public static class WsThread extends Thread { private boolean successful = true; public void run() { String threadName = Thread.currentThread().getName(); KumuluzWebServiceContext.getInstance().setMessageContext(new WebServiceContextBean(threadName)); for (int i = 0; i < 1000; i++) { //hoping for race condition to occur in 1k iterations successful &= threadName.equals(KumuluzWebServiceContext.getInstance().getMessageContext().get("id")); } } public boolean isSuccessful() { return successful; } } } ================================================ FILE: components/jax-ws/cxf/src/test/resources/META-INF/ws/java.lang.Object ================================================ ================================================ FILE: components/jax-ws/metro/pom.xml ================================================ kumuluzee-jax-ws com.kumuluz.ee 4.2.0-SNAPSHOT 4.0.0 KumuluzEE JAX-WS Metro KumuluzEE JAX-WS component implemented by Metro kumuluzee-jax-ws-metro com.kumuluz.ee kumuluzee-common org.glassfish.metro webservices-rt ${metro.version} org.glassfish.metro webservices-extra ${metro.version} javax.activation activation ${activation.version} ================================================ FILE: components/jax-ws/metro/src/main/java/com/kumuluz/ee/jaxws/metro/JaxWsComponent.java ================================================ /* * Copyright (c) 2014-2017 Kumuluz and/or its affiliates * and other contributors as indicated by the @author tags and * the contributor list. * * Licensed under the MIT License (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://opensource.org/licenses/MIT * * The software is provided "AS IS", WITHOUT WARRANTY OF ANY KIND, express or * implied, including but not limited to the warranties of merchantability, * fitness for a particular purpose and noninfringement. in no event shall the * authors or copyright holders be liable for any claim, damages or other * liability, whether in an action of contract, tort or otherwise, arising from, * out of or in connection with the software or the use or other dealings in the * software. See the License for the specific language governing permissions and * limitations under the License. */ package com.kumuluz.ee.jaxws.metro; import com.kumuluz.ee.common.Component; import com.kumuluz.ee.common.config.EeConfig; import com.kumuluz.ee.common.dependencies.EeComponentDef; import com.kumuluz.ee.common.dependencies.EeComponentType; import com.kumuluz.ee.common.wrapper.KumuluzServerWrapper; import java.util.logging.Logger; /** * @author Tilen Faganel * @since 2.0.0 */ @EeComponentDef(name = "Metro", type = EeComponentType.JAX_WS) public class JaxWsComponent implements Component { private Logger log = Logger.getLogger(JaxWsComponent.class.getSimpleName()); @Override public void init(KumuluzServerWrapper server, EeConfig eeConfig) { } @Override public void load() { log.info("Initiating Metro"); } } ================================================ FILE: components/jax-ws/metro/src/main/resources/META-INF/services/com.kumuluz.ee.common.Component ================================================ com.kumuluz.ee.jaxws.metro.JaxWsComponent ================================================ FILE: components/jax-ws/pom.xml ================================================ kumuluzee-components com.kumuluz.ee 4.2.0-SNAPSHOT 4.0.0 pom kumuluzee-jax-ws metro cxf KumuluzEE JAX-WS KumuluzEE JAX-WS component ================================================ FILE: components/jpa/common/pom.xml ================================================ kumuluzee-jpa com.kumuluz.ee 4.2.0-SNAPSHOT 4.0.0 KumuluzEE JPA Common KumuluzEE JPA component common utilities, configs and exceptions kumuluzee-jpa-common com.kumuluz.ee kumuluzee-common jakarta.persistence jakarta.persistence-api provided com.kumuluz.ee kumuluzee-cdi-weld provided com.kumuluz.ee kumuluzee-jta-common provided ================================================ FILE: components/jpa/common/src/main/java/com/kumuluz/ee/jpa/common/PersistenceSettings.java ================================================ /* * Copyright (c) 2014-2017 Kumuluz and/or its affiliates * and other contributors as indicated by the @author tags and * the contributor list. * * Licensed under the MIT License (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://opensource.org/licenses/MIT * * The software is provided "AS IS", WITHOUT WARRANTY OF ANY KIND, express or * implied, including but not limited to the warranties of merchantability, * fitness for a particular purpose and noninfringement. in no event shall the * authors or copyright holders be liable for any claim, damages or other * liability, whether in an action of contract, tort or otherwise, arising from, * out of or in connection with the software or the use or other dealings in the * software. See the License for the specific language governing permissions and * limitations under the License. */ package com.kumuluz.ee.jpa.common; import java.util.Map; /** * @author Tilen Faganel * @since 2.3.0 */ public interface PersistenceSettings { Map getPersistenceUnitProperties(); } ================================================ FILE: components/jpa/common/src/main/java/com/kumuluz/ee/jpa/common/PersistenceUnitHolder.java ================================================ /* * Copyright (c) 2014-2017 Kumuluz and/or its affiliates * and other contributors as indicated by the @author tags and * the contributor list. * * Licensed under the MIT License (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://opensource.org/licenses/MIT * * The software is provided "AS IS", WITHOUT WARRANTY OF ANY KIND, express or * implied, including but not limited to the warranties of merchantability, * fitness for a particular purpose and noninfringement. in no event shall the * authors or copyright holders be liable for any claim, damages or other * liability, whether in an action of contract, tort or otherwise, arising from, * out of or in connection with the software or the use or other dealings in the * software. See the License for the specific language governing permissions and * limitations under the License. */ package com.kumuluz.ee.jpa.common; import com.kumuluz.ee.jpa.common.utils.PersistenceUtils; import javax.persistence.EntityManagerFactory; import javax.persistence.Persistence; import java.util.HashMap; import java.util.Map; import java.util.Properties; /** * @author Tilen Faganel * @since 1.0.0 */ public class PersistenceUnitHolder { private PersistenceSettings providerProperties; private String defaultUnitName; private Map factories = new HashMap<>(); private static final PersistenceUnitHolder instance = new PersistenceUnitHolder(); private PersistenceUnitHolder() { defaultUnitName = PersistenceUtils.getDefaultUnitName().orElse(""); } public static PersistenceUnitHolder getInstance() { return instance; } public synchronized PersistenceWrapper getEntityManagerFactory(String unitName) { PersistenceWrapper wrapper = factories.get(unitName); if (wrapper == null) { Properties properties = new Properties(); if (providerProperties != null && providerProperties.getPersistenceUnitProperties() != null) { properties.putAll(providerProperties.getPersistenceUnitProperties()); } EntityManagerFactory factory = Persistence.createEntityManagerFactory(unitName, properties); TransactionType transactionType = PersistenceUtils.getEntityManagerFactoryTransactionType(factory); wrapper = new PersistenceWrapper(factory, transactionType); factories.put(unitName, wrapper); } return wrapper; } public String getDefaultUnitName() { return defaultUnitName; } public void setProviderProperties(PersistenceSettings providerProperties) { this.providerProperties = providerProperties; } } ================================================ FILE: components/jpa/common/src/main/java/com/kumuluz/ee/jpa/common/PersistenceWrapper.java ================================================ /* * Copyright (c) 2014-2017 Kumuluz and/or its affiliates * and other contributors as indicated by the @author tags and * the contributor list. * * Licensed under the MIT License (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://opensource.org/licenses/MIT * * The software is provided "AS IS", WITHOUT WARRANTY OF ANY KIND, express or * implied, including but not limited to the warranties of merchantability, * fitness for a particular purpose and noninfringement. in no event shall the * authors or copyright holders be liable for any claim, damages or other * liability, whether in an action of contract, tort or otherwise, arising from, * out of or in connection with the software or the use or other dealings in the * software. See the License for the specific language governing permissions and * limitations under the License. */ package com.kumuluz.ee.jpa.common; import javax.persistence.EntityManagerFactory; /** * @author Tilen Faganel * @since 2.3.0 */ public class PersistenceWrapper { private EntityManagerFactory entityManagerFactory; private TransactionType transactionType; public PersistenceWrapper(EntityManagerFactory entityManagerFactory, TransactionType transactionType) { this.entityManagerFactory = entityManagerFactory; this.transactionType = transactionType; } public EntityManagerFactory getEntityManagerFactory() { return entityManagerFactory; } public TransactionType getTransactionType() { return transactionType; } } ================================================ FILE: components/jpa/common/src/main/java/com/kumuluz/ee/jpa/common/TransactionType.java ================================================ /* * Copyright (c) 2014-2017 Kumuluz and/or its affiliates * and other contributors as indicated by the @author tags and * the contributor list. * * Licensed under the MIT License (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://opensource.org/licenses/MIT * * The software is provided "AS IS", WITHOUT WARRANTY OF ANY KIND, express or * implied, including but not limited to the warranties of merchantability, * fitness for a particular purpose and noninfringement. in no event shall the * authors or copyright holders be liable for any claim, damages or other * liability, whether in an action of contract, tort or otherwise, arising from, * out of or in connection with the software or the use or other dealings in the * software. See the License for the specific language governing permissions and * limitations under the License. */ package com.kumuluz.ee.jpa.common; /** * @author Tilen Faganel * @since 2.3.0 */ public enum TransactionType { RESOURCE_LOCAL, JTA } ================================================ FILE: components/jpa/common/src/main/java/com/kumuluz/ee/jpa/common/exceptions/NoDefaultPersistenceUnit.java ================================================ /* * Copyright (c) 2014-2017 Kumuluz and/or its affiliates * and other contributors as indicated by the @author tags and * the contributor list. * * Licensed under the MIT License (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://opensource.org/licenses/MIT * * The software is provided "AS IS", WITHOUT WARRANTY OF ANY KIND, express or * implied, including but not limited to the warranties of merchantability, * fitness for a particular purpose and noninfringement. in no event shall the * authors or copyright holders be liable for any claim, damages or other * liability, whether in an action of contract, tort or otherwise, arising from, * out of or in connection with the software or the use or other dealings in the * software. See the License for the specific language governing permissions and * limitations under the License. */ package com.kumuluz.ee.jpa.common.exceptions; /** * @author Tilen Faganel * @since 2.3.0 */ public class NoDefaultPersistenceUnit extends RuntimeException { public NoDefaultPersistenceUnit() { super("Cannot determine a default persistence unit. Either the configuration does not exist or " + "there are more then one configurations or units defined"); } } ================================================ FILE: components/jpa/common/src/main/java/com/kumuluz/ee/jpa/common/injection/EntityManagerWrapper.java ================================================ /* * Copyright (c) 2014-2017 Kumuluz and/or its affiliates * and other contributors as indicated by the @author tags and * the contributor list. * * Licensed under the MIT License (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://opensource.org/licenses/MIT * * The software is provided "AS IS", WITHOUT WARRANTY OF ANY KIND, express or * implied, including but not limited to the warranties of merchantability, * fitness for a particular purpose and noninfringement. in no event shall the * authors or copyright holders be liable for any claim, damages or other * liability, whether in an action of contract, tort or otherwise, arising from, * out of or in connection with the software or the use or other dealings in the * software. See the License for the specific language governing permissions and * limitations under the License. */ package com.kumuluz.ee.jpa.common.injection; import javax.persistence.EntityManager; /** * @author Tilen Faganel * @since 2.4.0 */ public interface EntityManagerWrapper { EntityManager getEntityManager(); void close(); } ================================================ FILE: components/jpa/common/src/main/java/com/kumuluz/ee/jpa/common/injection/JpaService.java ================================================ /* * Copyright (c) 2014-2017 Kumuluz and/or its affiliates * and other contributors as indicated by the @author tags and * the contributor list. * * Licensed under the MIT License (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://opensource.org/licenses/MIT * * The software is provided "AS IS", WITHOUT WARRANTY OF ANY KIND, express or * implied, including but not limited to the warranties of merchantability, * fitness for a particular purpose and noninfringement. in no event shall the * authors or copyright holders be liable for any claim, damages or other * liability, whether in an action of contract, tort or otherwise, arising from, * out of or in connection with the software or the use or other dealings in the * software. See the License for the specific language governing permissions and * limitations under the License. */ package com.kumuluz.ee.jpa.common.injection; import com.kumuluz.ee.configuration.utils.ConfigurationUtil; import com.kumuluz.ee.jpa.common.PersistenceUnitHolder; import com.kumuluz.ee.jpa.common.PersistenceWrapper; import com.kumuluz.ee.jpa.common.exceptions.NoDefaultPersistenceUnit; import org.jboss.weld.injection.spi.JpaInjectionServices; import org.jboss.weld.injection.spi.ResourceReferenceFactory; import javax.annotation.Priority; import javax.enterprise.inject.spi.InjectionPoint; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.PersistenceContext; import javax.persistence.PersistenceUnit; import java.util.Optional; import java.util.logging.Logger; /** * @author Tilen Faganel * @since 1.0.0 */ @Priority(1) public class JpaService implements JpaInjectionServices { private static final Logger LOG = Logger.getLogger(JpaService.class.getSimpleName()); @Override public ResourceReferenceFactory registerPersistenceContextInjectionPoint (InjectionPoint injectionPoint) { PersistenceUnitHolder holder = PersistenceUnitHolder.getInstance(); PersistenceContext pc = injectionPoint.getAnnotated().getAnnotation(PersistenceContext .class); String unitName = pc.unitName(); if (unitName.isEmpty()) { unitName = holder.getDefaultUnitName(); if (unitName.isEmpty()) { throw new NoDefaultPersistenceUnit(); } } //If database is unreachable, by default, framework will fail-early and not initialize due to unhandled exception. //Error can be ignored with config override per PU, however EntityManager for that connection will be null. boolean continueOnError = false; ConfigurationUtil cfg = ConfigurationUtil.getInstance(); Optional puSizeOpt = cfg.getListSize("kumuluzee.persistence-units"); if (puSizeOpt.isPresent()) { for (int i = 0; i < puSizeOpt.get(); i++) { Optional puName = cfg.get("kumuluzee.persistence-units[" + i + "].name"); if (puName.isPresent() && puName.get().equals(unitName)) { Optional continueOnErrorCfg = cfg.getBoolean("kumuluzee.persistence-units[" + i + "].continue-on-error"); if (continueOnErrorCfg.isPresent() && continueOnErrorCfg.get()!=null) { continueOnError = continueOnErrorCfg.get(); } break; } } } try { PersistenceWrapper wrapper = holder.getEntityManagerFactory(unitName); return new PersistenceContextResourceFactory(unitName, wrapper.getEntityManagerFactory(), wrapper.getTransactionType(), pc.synchronization()); } catch (Exception e) { if (!continueOnError) { LOG.severe("EntityManager for pu "+unitName+" failed to initialize. KumuluzEE initialization failed."); throw e; } } LOG.warning("EntityManager for pu "+unitName+" failed to initialize. KumuluzEE will continue the startup regardless due to config override."); return null; } @Override public ResourceReferenceFactory registerPersistenceUnitInjectionPoint (InjectionPoint injectionPoint) { PersistenceUnitHolder holder = PersistenceUnitHolder.getInstance(); PersistenceUnit pu = injectionPoint.getAnnotated().getAnnotation(PersistenceUnit.class); String unitName = pu.unitName(); if (unitName.isEmpty()) { unitName = holder.getDefaultUnitName(); if (unitName.isEmpty()) { throw new NoDefaultPersistenceUnit(); } } PersistenceWrapper wrapper = holder.getEntityManagerFactory(unitName); return new PersistenceUnitResourceFactory(wrapper.getEntityManagerFactory()); } @Override public void cleanup() { } } ================================================ FILE: components/jpa/common/src/main/java/com/kumuluz/ee/jpa/common/injection/NonTxEntityManagerWrapper.java ================================================ package com.kumuluz.ee.jpa.common.injection; import javax.persistence.EntityManager; /** * @author Tilen Faganel * @since 2.4.0 */ public class NonTxEntityManagerWrapper implements EntityManagerWrapper { private EntityManager em; public NonTxEntityManagerWrapper(EntityManager em) { this.em = em; } @Override public EntityManager getEntityManager() { return em; } @Override public void close() { if (em.isOpen()) { em.close(); } } } ================================================ FILE: components/jpa/common/src/main/java/com/kumuluz/ee/jpa/common/injection/PersistenceContextResource.java ================================================ /* * Copyright (c) 2014-2017 Kumuluz and/or its affiliates * and other contributors as indicated by the @author tags and * the contributor list. * * Licensed under the MIT License (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://opensource.org/licenses/MIT * * The software is provided "AS IS", WITHOUT WARRANTY OF ANY KIND, express or * implied, including but not limited to the warranties of merchantability, * fitness for a particular purpose and noninfringement. in no event shall the * authors or copyright holders be liable for any claim, damages or other * liability, whether in an action of contract, tort or otherwise, arising from, * out of or in connection with the software or the use or other dealings in the * software. See the License for the specific language governing permissions and * limitations under the License. */ package com.kumuluz.ee.jpa.common.injection; import org.jboss.weld.injection.spi.ResourceReference; import javax.persistence.EntityManager; /** * @author Tilen Faganel * @since 1.0.0 */ public class PersistenceContextResource implements ResourceReference { private EntityManagerWrapper entityManagerWrapper; public PersistenceContextResource(EntityManagerWrapper entityManagerWrapper) { this.entityManagerWrapper = entityManagerWrapper; } @Override public EntityManager getInstance() { return entityManagerWrapper.getEntityManager(); } @Override public void release() { entityManagerWrapper.close(); } } ================================================ FILE: components/jpa/common/src/main/java/com/kumuluz/ee/jpa/common/injection/PersistenceContextResourceFactory.java ================================================ /* * Copyright (c) 2014-2017 Kumuluz and/or its affiliates * and other contributors as indicated by the @author tags and * the contributor list. * * Licensed under the MIT License (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://opensource.org/licenses/MIT * * The software is provided "AS IS", WITHOUT WARRANTY OF ANY KIND, express or * implied, including but not limited to the warranties of merchantability, * fitness for a particular purpose and noninfringement. in no event shall the * authors or copyright holders be liable for any claim, damages or other * liability, whether in an action of contract, tort or otherwise, arising from, * out of or in connection with the software or the use or other dealings in the * software. See the License for the specific language governing permissions and * limitations under the License. */ package com.kumuluz.ee.jpa.common.injection; import com.kumuluz.ee.jpa.common.TransactionType; import com.kumuluz.ee.jpa.common.jta.TxScopedEntityManagerFactory; import org.jboss.weld.injection.spi.ResourceReference; import org.jboss.weld.injection.spi.ResourceReferenceFactory; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.SynchronizationType; /** * @author Tilen Faganel * @since 1.0.0 */ public class PersistenceContextResourceFactory implements ResourceReferenceFactory { private String unitName; private EntityManagerFactory emf; private SynchronizationType sync; private TransactionType transactionType; public PersistenceContextResourceFactory(String unitName, EntityManagerFactory emf, TransactionType transactionType, SynchronizationType sync) { this.unitName = unitName; this.emf = emf; this.sync = sync; this.transactionType = transactionType; } @Override public ResourceReference createResource() { EntityManagerWrapper emWrapper; if (transactionType == TransactionType.JTA) { emWrapper = TxScopedEntityManagerFactory.buildEntityManagerWrapper(unitName, emf, sync); } else { emWrapper = new NonTxEntityManagerWrapper(emf.createEntityManager()); } return new PersistenceContextResource(emWrapper); } } ================================================ FILE: components/jpa/common/src/main/java/com/kumuluz/ee/jpa/common/injection/PersistenceUnitResource.java ================================================ /* * Copyright (c) 2014-2017 Kumuluz and/or its affiliates * and other contributors as indicated by the @author tags and * the contributor list. * * Licensed under the MIT License (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://opensource.org/licenses/MIT * * The software is provided "AS IS", WITHOUT WARRANTY OF ANY KIND, express or * implied, including but not limited to the warranties of merchantability, * fitness for a particular purpose and noninfringement. in no event shall the * authors or copyright holders be liable for any claim, damages or other * liability, whether in an action of contract, tort or otherwise, arising from, * out of or in connection with the software or the use or other dealings in the * software. See the License for the specific language governing permissions and * limitations under the License. */ package com.kumuluz.ee.jpa.common.injection; import org.jboss.weld.injection.spi.ResourceReference; import javax.persistence.EntityManagerFactory; /** * @author Tilen Faganel * @since 1.0.0 */ public class PersistenceUnitResource implements ResourceReference { private EntityManagerFactory emf; public PersistenceUnitResource(EntityManagerFactory emf) { this.emf = emf; } @Override public EntityManagerFactory getInstance() { return emf; } @Override public void release() { } } ================================================ FILE: components/jpa/common/src/main/java/com/kumuluz/ee/jpa/common/injection/PersistenceUnitResourceFactory.java ================================================ /* * Copyright (c) 2014-2017 Kumuluz and/or its affiliates * and other contributors as indicated by the @author tags and * the contributor list. * * Licensed under the MIT License (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://opensource.org/licenses/MIT * * The software is provided "AS IS", WITHOUT WARRANTY OF ANY KIND, express or * implied, including but not limited to the warranties of merchantability, * fitness for a particular purpose and noninfringement. in no event shall the * authors or copyright holders be liable for any claim, damages or other * liability, whether in an action of contract, tort or otherwise, arising from, * out of or in connection with the software or the use or other dealings in the * software. See the License for the specific language governing permissions and * limitations under the License. */ package com.kumuluz.ee.jpa.common.injection; import org.jboss.weld.injection.spi.ResourceReference; import org.jboss.weld.injection.spi.ResourceReferenceFactory; import javax.persistence.EntityManagerFactory; /** * @author Tilen Faganel * @since 1.0.0 */ public class PersistenceUnitResourceFactory implements ResourceReferenceFactory { private EntityManagerFactory emf; public PersistenceUnitResourceFactory(EntityManagerFactory emf) { this.emf = emf; } @Override public ResourceReference createResource() { return new PersistenceUnitResource(emf); } } ================================================ FILE: components/jpa/common/src/main/java/com/kumuluz/ee/jpa/common/jta/NonTxEntityManagerHolder.java ================================================ /* * Copyright (c) 2014-2017 Kumuluz and/or its affiliates * and other contributors as indicated by the @author tags and * the contributor list. * * Licensed under the MIT License (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://opensource.org/licenses/MIT * * The software is provided "AS IS", WITHOUT WARRANTY OF ANY KIND, express or * implied, including but not limited to the warranties of merchantability, * fitness for a particular purpose and noninfringement. in no event shall the * authors or copyright holders be liable for any claim, damages or other * liability, whether in an action of contract, tort or otherwise, arising from, * out of or in connection with the software or the use or other dealings in the * software. See the License for the specific language governing permissions and * limitations under the License. */ package com.kumuluz.ee.jpa.common.jta; import javax.persistence.EntityManager; /** * @author Tilen Faganel * @since 2.4.0 */ public class NonTxEntityManagerHolder { private EntityManager em; public EntityManager getEntityManager() { return em; } public void setEntityManager(EntityManager em) { this.em = em; } } ================================================ FILE: components/jpa/common/src/main/java/com/kumuluz/ee/jpa/common/jta/NonTxQueryWrapper.java ================================================ /* * Copyright (c) 2014-2017 Kumuluz and/or its affiliates * and other contributors as indicated by the @author tags and * the contributor list. * * Licensed under the MIT License (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://opensource.org/licenses/MIT * * The software is provided "AS IS", WITHOUT WARRANTY OF ANY KIND, express or * implied, including but not limited to the warranties of merchantability, * fitness for a particular purpose and noninfringement. in no event shall the * authors or copyright holders be liable for any claim, damages or other * liability, whether in an action of contract, tort or otherwise, arising from, * out of or in connection with the software or the use or other dealings in the * software. See the License for the specific language governing permissions and * limitations under the License. */ package com.kumuluz.ee.jpa.common.jta; import javax.persistence.*; import java.util.*; /** * @author Tilen Faganel * @since 2.4.0 */ public class NonTxQueryWrapper implements Query { private Query query; private EntityManager em; public NonTxQueryWrapper(Query query, EntityManager em) { this.query = query; this.em = em; } @Override public List getResultList() { List resultList = query.getResultList(); em.clear(); return resultList; } @Override public Object getSingleResult() { Object singleResult = query.getSingleResult(); em.clear(); return singleResult; } @Override public int executeUpdate() { return query.executeUpdate(); } @Override public Query setMaxResults(int maxResult) { query.setMaxResults(maxResult); return this; } @Override public int getMaxResults() { return query.getMaxResults(); } @Override public Query setFirstResult(int startPosition) { query.setFirstResult(startPosition); return this; } @Override public int getFirstResult() { return query.getFirstResult(); } @Override public Query setHint(String hintName, Object value) { query.setHint(hintName, value); return this; } @Override public Map getHints() { return query.getHints(); } @Override public Query setParameter(Parameter param, T value) { query.setParameter(param, value); return this; } @Override public Query setParameter(Parameter param, Calendar value, TemporalType temporalType) { query.setParameter(param, value, temporalType); return this; } @Override public Query setParameter(Parameter param, Date value, TemporalType temporalType) { query.setParameter(param, value, temporalType); return this; } @Override public Query setParameter(String name, Object value) { query.setParameter(name, value); return this; } @Override public Query setParameter(String name, Calendar value, TemporalType temporalType) { query.setParameter(name, value, temporalType); return this; } @Override public Query setParameter(String name, Date value, TemporalType temporalType) { query.setParameter(name, value, temporalType); return this; } @Override public Query setParameter(int position, Object value) { query.setParameter(position, value); return this; } @Override public Query setParameter(int position, Calendar value, TemporalType temporalType) { query.setParameter(position, value, temporalType); return this; } @Override public Query setParameter(int position, Date value, TemporalType temporalType) { query.setParameter(position, value, temporalType); return this; } @Override public Set> getParameters() { return query.getParameters(); } @Override public Parameter getParameter(String name) { return query.getParameter(name); } @Override public Parameter getParameter(String name, Class type) { return query.getParameter(name, type); } @Override public Parameter getParameter(int position) { return query.getParameter(position); } @Override public Parameter getParameter(int position, Class type) { return query.getParameter(position, type); } @Override public boolean isBound(Parameter param) { return query.isBound(param); } @Override public T getParameterValue(Parameter param) { return query.getParameterValue(param); } @Override public Object getParameterValue(String name) { return query.getParameterValue(name); } @Override public Object getParameterValue(int position) { return query.getParameterValue(position); } @Override public Query setFlushMode(FlushModeType flushMode) { query.setFlushMode(flushMode); return this; } @Override public FlushModeType getFlushMode() { return query.getFlushMode(); } @Override public Query setLockMode(LockModeType lockMode) { query.setLockMode(lockMode); return this; } @Override public LockModeType getLockMode() { return query.getLockMode(); } @Override public T unwrap(Class cls) { return query.unwrap(cls); } } ================================================ FILE: components/jpa/common/src/main/java/com/kumuluz/ee/jpa/common/jta/NonTxStoredProcedureQueryWrapper.java ================================================ /* * Copyright (c) 2014-2017 Kumuluz and/or its affiliates * and other contributors as indicated by the @author tags and * the contributor list. * * Licensed under the MIT License (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://opensource.org/licenses/MIT * * The software is provided "AS IS", WITHOUT WARRANTY OF ANY KIND, express or * implied, including but not limited to the warranties of merchantability, * fitness for a particular purpose and noninfringement. in no event shall the * authors or copyright holders be liable for any claim, damages or other * liability, whether in an action of contract, tort or otherwise, arising from, * out of or in connection with the software or the use or other dealings in the * software. See the License for the specific language governing permissions and * limitations under the License. */ package com.kumuluz.ee.jpa.common.jta; import javax.persistence.*; import java.util.*; /** * @author Tilen Faganel * @since 2.4.0 */ public class NonTxStoredProcedureQueryWrapper implements StoredProcedureQuery { private StoredProcedureQuery storedProcedureQuery; private EntityManager em; public NonTxStoredProcedureQueryWrapper(StoredProcedureQuery storedProcedureQuery, EntityManager em) { this.storedProcedureQuery = storedProcedureQuery; this.em = em; } @Override public StoredProcedureQuery setHint(String hintName, Object value) { storedProcedureQuery.setHint(hintName, value); return this; } @Override public Map getHints() { return storedProcedureQuery.getHints(); } @Override public StoredProcedureQuery setParameter(Parameter param, T value) { storedProcedureQuery.setParameter(param, value); return this; } @Override public StoredProcedureQuery setParameter(Parameter param, Calendar value, TemporalType temporalType) { storedProcedureQuery.setParameter(param, value, temporalType); return this; } @Override public StoredProcedureQuery setParameter(Parameter param, Date value, TemporalType temporalType) { storedProcedureQuery.setParameter(param, value, temporalType); return this; } @Override public StoredProcedureQuery setParameter(String name, Object value) { storedProcedureQuery.setParameter(name, value); return this; } @Override public StoredProcedureQuery setParameter(String name, Calendar value, TemporalType temporalType) { storedProcedureQuery.setParameter(name, value, temporalType); return this; } @Override public StoredProcedureQuery setParameter(String name, Date value, TemporalType temporalType) { storedProcedureQuery.setParameter(name, value, temporalType); return this; } @Override public StoredProcedureQuery setParameter(int position, Object value) { storedProcedureQuery.setParameter(position, value); return this; } @Override public StoredProcedureQuery setParameter(int position, Calendar value, TemporalType temporalType) { storedProcedureQuery.setParameter(position, value, temporalType); return this; } @Override public StoredProcedureQuery setParameter(int position, Date value, TemporalType temporalType) { storedProcedureQuery.setParameter(position, value, temporalType); return this; } @Override public Set> getParameters() { return storedProcedureQuery.getParameters(); } @Override public Parameter getParameter(String name) { return storedProcedureQuery.getParameter(name); } @Override public Parameter getParameter(String name, Class type) { return storedProcedureQuery.getParameter(name, type); } @Override public Parameter getParameter(int position) { return storedProcedureQuery.getParameter(position); } @Override public Parameter getParameter(int position, Class type) { return storedProcedureQuery.getParameter(position, type); } @Override public boolean isBound(Parameter param) { return storedProcedureQuery.isBound(param); } @Override public T getParameterValue(Parameter param) { return storedProcedureQuery.getParameterValue(param); } @Override public Object getParameterValue(String name) { return storedProcedureQuery.getParameterValue(name); } @Override public Object getParameterValue(int position) { return storedProcedureQuery.getParameterValue(position); } @Override public StoredProcedureQuery setFlushMode(FlushModeType flushMode) { storedProcedureQuery.setFlushMode(flushMode); return this; } @Override public FlushModeType getFlushMode() { return storedProcedureQuery.getFlushMode(); } @Override public Query setLockMode(LockModeType lockMode) { storedProcedureQuery.setLockMode(lockMode); return this; } @Override public LockModeType getLockMode() { return storedProcedureQuery.getLockMode(); } @Override public T unwrap(Class cls) { return storedProcedureQuery.unwrap(cls); } @Override public StoredProcedureQuery registerStoredProcedureParameter(int position, Class type, ParameterMode mode) { storedProcedureQuery.registerStoredProcedureParameter(position, type, mode); return this; } @Override public StoredProcedureQuery registerStoredProcedureParameter(String parameterName, Class type, ParameterMode mode) { storedProcedureQuery.registerStoredProcedureParameter(parameterName, type, mode); return this; } @Override public Object getOutputParameterValue(int position) { return storedProcedureQuery.getOutputParameterValue(position); } @Override public Object getOutputParameterValue(String parameterName) { return storedProcedureQuery.getOutputParameterValue(parameterName); } @Override public boolean execute() { return storedProcedureQuery.execute(); } @Override public int executeUpdate() { return storedProcedureQuery.executeUpdate(); } @Override public Query setMaxResults(int maxResult) { storedProcedureQuery.setMaxResults(maxResult); return this; } @Override public int getMaxResults() { return storedProcedureQuery.getMaxResults(); } @Override public Query setFirstResult(int startPosition) { storedProcedureQuery.setFirstResult(startPosition); return this; } @Override public int getFirstResult() { return storedProcedureQuery.getFirstResult(); } @Override public List getResultList() { List resultList = storedProcedureQuery.getResultList(); em.clear(); return resultList; } @Override public Object getSingleResult() { Object singleResult = storedProcedureQuery.getSingleResult(); em.clear(); return singleResult; } @Override public boolean hasMoreResults() { return storedProcedureQuery.hasMoreResults(); } @Override public int getUpdateCount() { return storedProcedureQuery.getUpdateCount(); } } ================================================ FILE: components/jpa/common/src/main/java/com/kumuluz/ee/jpa/common/jta/NonTxTypedQueryWrapper.java ================================================ /* * Copyright (c) 2014-2017 Kumuluz and/or its affiliates * and other contributors as indicated by the @author tags and * the contributor list. * * Licensed under the MIT License (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://opensource.org/licenses/MIT * * The software is provided "AS IS", WITHOUT WARRANTY OF ANY KIND, express or * implied, including but not limited to the warranties of merchantability, * fitness for a particular purpose and noninfringement. in no event shall the * authors or copyright holders be liable for any claim, damages or other * liability, whether in an action of contract, tort or otherwise, arising from, * out of or in connection with the software or the use or other dealings in the * software. See the License for the specific language governing permissions and * limitations under the License. */ package com.kumuluz.ee.jpa.common.jta; import javax.persistence.*; import java.util.*; /** * @author Tilen Faganel * @since 2.4.0 */ public class NonTxTypedQueryWrapper implements TypedQuery { private TypedQuery typedQuery; private EntityManager em; public NonTxTypedQueryWrapper(TypedQuery typedQuery, EntityManager em) { this.typedQuery = typedQuery; this.em = em; } @Override public List getResultList() { List resultList = typedQuery.getResultList(); em.clear(); return resultList; } @Override public X getSingleResult() { X singleResult = typedQuery.getSingleResult(); em.clear(); return singleResult; } @Override public int executeUpdate() { return typedQuery.executeUpdate(); } @Override public TypedQuery setMaxResults(int maxResult) { typedQuery.setMaxResults(maxResult); return this; } @Override public int getMaxResults() { return typedQuery.getMaxResults(); } @Override public TypedQuery setFirstResult(int startPosition) { typedQuery.setFirstResult(startPosition); return this; } @Override public int getFirstResult() { return typedQuery.getFirstResult(); } @Override public TypedQuery setHint(String hintName, Object value) { typedQuery.setHint(hintName, value); return this; } @Override public Map getHints() { return typedQuery.getHints(); } @Override public TypedQuery setParameter(Parameter param, T value) { typedQuery.setParameter(param, value); return this; } @Override public TypedQuery setParameter(Parameter param, Calendar value, TemporalType temporalType) { typedQuery.setParameter(param, value, temporalType); return this; } @Override public TypedQuery setParameter(Parameter param, Date value, TemporalType temporalType) { typedQuery.setParameter(param, value, temporalType); return this; } @Override public TypedQuery setParameter(String name, Object value) { typedQuery.setParameter(name, value); return this; } @Override public TypedQuery setParameter(String name, Calendar value, TemporalType temporalType) { typedQuery.setParameter(name, value, temporalType); return this; } @Override public TypedQuery setParameter(String name, Date value, TemporalType temporalType) { typedQuery.setParameter(name, value, temporalType); return this; } @Override public TypedQuery setParameter(int position, Object value) { typedQuery.setParameter(position, value); return this; } @Override public TypedQuery setParameter(int position, Calendar value, TemporalType temporalType) { typedQuery.setParameter(position, value, temporalType); return this; } @Override public TypedQuery setParameter(int position, Date value, TemporalType temporalType) { typedQuery.setParameter(position, value, temporalType); return this; } @Override public Set> getParameters() { return typedQuery.getParameters(); } @Override public Parameter getParameter(String name) { return typedQuery.getParameter(name); } @Override public Parameter getParameter(String name, Class type) { return typedQuery.getParameter(name, type); } @Override public Parameter getParameter(int position) { return typedQuery.getParameter(position); } @Override public Parameter getParameter(int position, Class type) { return typedQuery.getParameter(position, type); } @Override public boolean isBound(Parameter param) { return typedQuery.isBound(param); } @Override public T getParameterValue(Parameter param) { return typedQuery.getParameterValue(param); } @Override public Object getParameterValue(String name) { return typedQuery.getParameterValue(name); } @Override public Object getParameterValue(int position) { return typedQuery.getParameterValue(position); } @Override public TypedQuery setFlushMode(FlushModeType flushMode) { typedQuery.setFlushMode(flushMode); return this; } @Override public FlushModeType getFlushMode() { return typedQuery.getFlushMode(); } @Override public TypedQuery setLockMode(LockModeType lockMode) { typedQuery.setLockMode(lockMode); return this; } @Override public LockModeType getLockMode() { return typedQuery.getLockMode(); } @Override public T unwrap(Class cls) { return typedQuery.unwrap(cls); } } ================================================ FILE: components/jpa/common/src/main/java/com/kumuluz/ee/jpa/common/jta/SyncEntityManagerWrapper.java ================================================ /* * Copyright (c) 2014-2017 Kumuluz and/or its affiliates * and other contributors as indicated by the @author tags and * the contributor list. * * Licensed under the MIT License (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://opensource.org/licenses/MIT * * The software is provided "AS IS", WITHOUT WARRANTY OF ANY KIND, express or * implied, including but not limited to the warranties of merchantability, * fitness for a particular purpose and noninfringement. in no event shall the * authors or copyright holders be liable for any claim, damages or other * liability, whether in an action of contract, tort or otherwise, arising from, * out of or in connection with the software or the use or other dealings in the * software. See the License for the specific language governing permissions and * limitations under the License. */ package com.kumuluz.ee.jpa.common.jta; import javax.persistence.*; import javax.persistence.criteria.CriteriaBuilder; import javax.persistence.criteria.CriteriaDelete; import javax.persistence.criteria.CriteriaQuery; import javax.persistence.criteria.CriteriaUpdate; import javax.persistence.metamodel.Metamodel; import java.util.List; import java.util.Map; /** * @author Tilen Faganel * @since 2.4.0 */ public class SyncEntityManagerWrapper implements EntityManager { private EntityManager em; private SynchronizationType sync; public SyncEntityManagerWrapper(EntityManager em, SynchronizationType sync) { this.em = em; this.sync = sync; } public SynchronizationType getSynchronizationType() { return sync; } @Override public void persist(Object entity) { em.persist(entity); } @Override public T merge(T entity) { return em.merge(entity); } @Override public void remove(Object entity) { em.remove(entity); } @Override public T find(Class entityClass, Object primaryKey) { return em.find(entityClass, primaryKey); } @Override public T find(Class entityClass, Object primaryKey, Map properties) { return em.find(entityClass, primaryKey, properties); } @Override public T find(Class entityClass, Object primaryKey, LockModeType lockMode) { return em.find(entityClass, primaryKey, lockMode); } @Override public T find(Class entityClass, Object primaryKey, LockModeType lockMode, Map properties) { return em.find(entityClass, primaryKey, lockMode, properties); } @Override public T getReference(Class entityClass, Object primaryKey) { return em.getReference(entityClass, primaryKey); } @Override public void flush() { em.flush(); } @Override public void setFlushMode(FlushModeType flushMode) { em.setFlushMode(flushMode); } @Override public FlushModeType getFlushMode() { return em.getFlushMode(); } @Override public void lock(Object entity, LockModeType lockMode) { em.lock(entity, lockMode); } @Override public void lock(Object entity, LockModeType lockMode, Map properties) { em.lock(entity, lockMode, properties); } @Override public void refresh(Object entity) { em.refresh(entity); } @Override public void refresh(Object entity, Map properties) { em.refresh(entity, properties); } @Override public void refresh(Object entity, LockModeType lockMode) { em.refresh(entity, lockMode); } @Override public void refresh(Object entity, LockModeType lockMode, Map properties) { em.refresh(entity, lockMode, properties); } @Override public void clear() { em.clear(); } @Override public void detach(Object entity) { em.detach(entity); } @Override public boolean contains(Object entity) { return em.contains(entity); } @Override public LockModeType getLockMode(Object entity) { return em.getLockMode(entity); } @Override public void setProperty(String propertyName, Object value) { em.setProperty(propertyName, value); } @Override public Map getProperties() { return em.getProperties(); } @Override public Query createQuery(String qlString) { return em.createQuery(qlString); } @Override public TypedQuery createQuery(CriteriaQuery criteriaQuery) { return em.createQuery(criteriaQuery); } @Override public Query createQuery(CriteriaUpdate updateQuery) { return em.createQuery(updateQuery); } @Override public Query createQuery(CriteriaDelete deleteQuery) { return em.createQuery(deleteQuery); } @Override public TypedQuery createQuery(String qlString, Class resultClass) { return em.createQuery(qlString, resultClass); } @Override public Query createNamedQuery(String name) { return em.createNamedQuery(name); } @Override public TypedQuery createNamedQuery(String name, Class resultClass) { return em.createNamedQuery(name, resultClass); } @Override public Query createNativeQuery(String sqlString) { return em.createNativeQuery(sqlString); } @Override public Query createNativeQuery(String sqlString, Class resultClass) { return em.createNativeQuery(sqlString, resultClass); } @Override public Query createNativeQuery(String sqlString, String resultSetMapping) { return em.createNativeQuery(sqlString, resultSetMapping); } @Override public StoredProcedureQuery createNamedStoredProcedureQuery(String name) { return em.createNamedStoredProcedureQuery(name); } @Override public StoredProcedureQuery createStoredProcedureQuery(String procedureName) { return em.createNamedStoredProcedureQuery(procedureName); } @Override public StoredProcedureQuery createStoredProcedureQuery(String procedureName, Class... resultClasses) { return em.createStoredProcedureQuery(procedureName, resultClasses); } @Override public StoredProcedureQuery createStoredProcedureQuery(String procedureName, String... resultSetMappings) { return em.createStoredProcedureQuery(procedureName, resultSetMappings); } @Override public void joinTransaction() { em.joinTransaction(); } @Override public boolean isJoinedToTransaction() { return em.isJoinedToTransaction(); } @Override public T unwrap(Class cls) { return em.unwrap(cls); } @Override public Object getDelegate() { return em.getDelegate(); } @Override public void close() { em.close(); } @Override public boolean isOpen() { return em.isOpen(); } @Override public EntityTransaction getTransaction() { return em.getTransaction(); } @Override public EntityManagerFactory getEntityManagerFactory() { return em.getEntityManagerFactory(); } @Override public CriteriaBuilder getCriteriaBuilder() { return em.getCriteriaBuilder(); } @Override public Metamodel getMetamodel() { return em.getMetamodel(); } @Override public EntityGraph createEntityGraph(Class rootType) { return em.createEntityGraph(rootType); } @Override public EntityGraph createEntityGraph(String graphName) { return em.createEntityGraph(graphName); } @Override public EntityGraph getEntityGraph(String graphName) { return em.getEntityGraph(graphName); } @Override public List> getEntityGraphs(Class entityClass) { return em.getEntityGraphs(entityClass); } } ================================================ FILE: components/jpa/common/src/main/java/com/kumuluz/ee/jpa/common/jta/TxScopedEntityManager.java ================================================ /* * Copyright (c) 2014-2017 Kumuluz and/or its affiliates * and other contributors as indicated by the @author tags and * the contributor list. * * Licensed under the MIT License (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://opensource.org/licenses/MIT * * The software is provided "AS IS", WITHOUT WARRANTY OF ANY KIND, express or * implied, including but not limited to the warranties of merchantability, * fitness for a particular purpose and noninfringement. in no event shall the * authors or copyright holders be liable for any claim, damages or other * liability, whether in an action of contract, tort or otherwise, arising from, * out of or in connection with the software or the use or other dealings in the * software. See the License for the specific language governing permissions and * limitations under the License. */ package com.kumuluz.ee.jpa.common.jta; import com.kumuluz.ee.jta.common.utils.TxUtils; import javax.persistence.*; import javax.persistence.criteria.CriteriaBuilder; import javax.persistence.criteria.CriteriaDelete; import javax.persistence.criteria.CriteriaQuery; import javax.persistence.criteria.CriteriaUpdate; import javax.persistence.metamodel.Metamodel; import javax.transaction.TransactionManager; import javax.transaction.TransactionSynchronizationRegistry; import java.util.List; import java.util.Map; /** * @author Tilen Faganel * @since 2.4.0 */ public class TxScopedEntityManager implements EntityManager { private String unitName; private EntityManagerFactory emf; private SynchronizationType sync; private TransactionManager transactionManager; private TransactionSynchronizationRegistry transactionSynchronizationRegistry; private NonTxEntityManagerHolder nonTxEmHolder; public TxScopedEntityManager(String unitName, EntityManagerFactory emf, SynchronizationType sync, TransactionManager transactionManager, TransactionSynchronizationRegistry transactionSynchronizationRegistry, NonTxEntityManagerHolder nonTxEmHolder) { this.unitName = unitName; this.emf = emf; this.sync = sync; this.transactionManager = transactionManager; this.transactionSynchronizationRegistry = transactionSynchronizationRegistry; this.nonTxEmHolder = nonTxEmHolder; } @Override public void persist(Object entity) { validateActiveTransaction(); getEntityManager().persist(entity); } @Override public T merge(T entity) { validateActiveTransaction(); return getEntityManager().merge(entity); } @Override public void remove(Object entity) { validateActiveTransaction(); getEntityManager().remove(entity); } @Override public T find(Class entityClass, Object primaryKey) { EntityManager em = getEntityManager(); T result = em.find(entityClass, primaryKey); detachLoadedNonTxEntities(em); return result; } @Override public T find(Class entityClass, Object primaryKey, Map properties) { EntityManager em = getEntityManager(); T result = em.find(entityClass, primaryKey, properties); detachLoadedNonTxEntities(em); return result; } @Override public T find(Class entityClass, Object primaryKey, LockModeType lockMode) { EntityManager em = getEntityManager(); T result = em.find(entityClass, primaryKey, lockMode); detachLoadedNonTxEntities(em); return result; } @Override public T find(Class entityClass, Object primaryKey, LockModeType lockMode, Map properties) { EntityManager em = getEntityManager(); T result = em.find(entityClass, primaryKey, lockMode, properties); detachLoadedNonTxEntities(em); return result; } @Override public T getReference(Class entityClass, Object primaryKey) { EntityManager em = getEntityManager(); T result = em.getReference(entityClass, primaryKey); detachLoadedNonTxEntities(em); return result; } @Override public void flush() { getEntityManager().flush(); } @Override public void setFlushMode(FlushModeType flushMode) { getEntityManager().setFlushMode(flushMode); } @Override public FlushModeType getFlushMode() { return getEntityManager().getFlushMode(); } @Override public void lock(Object entity, LockModeType lockMode) { getEntityManager().lock(entity, lockMode); } @Override public void lock(Object entity, LockModeType lockMode, Map properties) { getEntityManager().lock(entity, lockMode, properties); } @Override public void refresh(Object entity) { validateActiveTransaction(); getEntityManager().refresh(entity); } @Override public void refresh(Object entity, Map properties) { validateActiveTransaction(); getEntityManager().refresh(entity, properties); } @Override public void refresh(Object entity, LockModeType lockMode) { validateActiveTransaction(); getEntityManager().refresh(entity, lockMode); } @Override public void refresh(Object entity, LockModeType lockMode, Map properties) { validateActiveTransaction(); getEntityManager().refresh(entity, lockMode, properties); } @Override public void clear() { getEntityManager().clear(); } @Override public void detach(Object entity) { getEntityManager().detach(entity); } @Override public boolean contains(Object entity) { return getEntityManager().contains(entity); } @Override public LockModeType getLockMode(Object entity) { return getEntityManager().getLockMode(entity); } @Override public void setProperty(String propertyName, Object value) { getEntityManager().setProperty(propertyName, value); } @Override public Map getProperties() { return getEntityManager().getProperties(); } @Override public Query createQuery(String qlString) { EntityManager em = getEntityManager(); Query query = em.createQuery(qlString); return detachLoadedNonTxQueryEntities(query, em); } @Override public TypedQuery createQuery(CriteriaQuery criteriaQuery) { EntityManager em = getEntityManager(); TypedQuery typedQuery = em.createQuery(criteriaQuery); return detachLoadedNonTxTypedQueryEntities(typedQuery, em); } @Override public Query createQuery(CriteriaUpdate updateQuery) { return getEntityManager().createQuery(updateQuery); } @Override public Query createQuery(CriteriaDelete deleteQuery) { return getEntityManager().createQuery(deleteQuery); } @Override public TypedQuery createQuery(String qlString, Class resultClass) { EntityManager em = getEntityManager(); TypedQuery typedQuery = em.createQuery(qlString, resultClass); return detachLoadedNonTxTypedQueryEntities(typedQuery, em); } @Override public Query createNamedQuery(String name) { EntityManager em = getEntityManager(); Query query = em.createNamedQuery(name); return detachLoadedNonTxQueryEntities(query, em); } @Override public TypedQuery createNamedQuery(String name, Class resultClass) { EntityManager em = getEntityManager(); TypedQuery typedQuery = em.createNamedQuery(name, resultClass); return detachLoadedNonTxTypedQueryEntities(typedQuery, em); } @Override public Query createNativeQuery(String sqlString) { EntityManager em = getEntityManager(); Query query = em.createNativeQuery(sqlString); return detachLoadedNonTxQueryEntities(query, em); } @Override public Query createNativeQuery(String sqlString, Class resultClass) { EntityManager em = getEntityManager(); Query query = em.createNativeQuery(sqlString, resultClass); return detachLoadedNonTxQueryEntities(query, em); } @Override public Query createNativeQuery(String sqlString, String resultSetMapping) { EntityManager em = getEntityManager(); Query query = em.createNativeQuery(sqlString, resultSetMapping); return detachLoadedNonTxQueryEntities(query, em); } @Override public StoredProcedureQuery createNamedStoredProcedureQuery(String name) { EntityManager em = getEntityManager(); StoredProcedureQuery storedProcedureQuery = em.createNamedStoredProcedureQuery(name); return detachLoadedNonTxStoredProcedureQueryEntities(storedProcedureQuery, em); } @Override public StoredProcedureQuery createStoredProcedureQuery(String procedureName) { EntityManager em = getEntityManager(); StoredProcedureQuery storedProcedureQuery = em.createStoredProcedureQuery(procedureName); return detachLoadedNonTxStoredProcedureQueryEntities(storedProcedureQuery, em); } @Override public StoredProcedureQuery createStoredProcedureQuery(String procedureName, Class... resultClasses) { EntityManager em = getEntityManager(); StoredProcedureQuery storedProcedureQuery = em.createStoredProcedureQuery(procedureName, resultClasses); return detachLoadedNonTxStoredProcedureQueryEntities(storedProcedureQuery, em); } @Override public StoredProcedureQuery createStoredProcedureQuery(String procedureName, String... resultSetMappings) { EntityManager em = getEntityManager(); StoredProcedureQuery storedProcedureQuery = em.createStoredProcedureQuery(procedureName, resultSetMappings); return detachLoadedNonTxStoredProcedureQueryEntities(storedProcedureQuery, em); } @Override public void joinTransaction() { getEntityManager().joinTransaction(); } @Override public boolean isJoinedToTransaction() { return getEntityManager().isJoinedToTransaction(); } @Override public T unwrap(Class cls) { return getEntityManager().unwrap(cls); } @Override public Object getDelegate() { return getEntityManager().getDelegate(); } @Override public void close() { throw new IllegalStateException("Cannot closed a transaction managed entity manager."); } @Override public boolean isOpen() { return getEntityManager().isOpen(); } @Override public EntityTransaction getTransaction() { return getEntityManager().getTransaction(); } @Override public EntityManagerFactory getEntityManagerFactory() { return getEntityManager().getEntityManagerFactory(); } @Override public CriteriaBuilder getCriteriaBuilder() { return getEntityManager().getCriteriaBuilder(); } @Override public Metamodel getMetamodel() { return getEntityManager().getMetamodel(); } @Override public EntityGraph createEntityGraph(Class rootType) { return getEntityManager().createEntityGraph(rootType); } @Override public EntityGraph createEntityGraph(String graphName) { return getEntityManager().createEntityGraph(graphName); } @Override public EntityGraph getEntityGraph(String graphName) { return getEntityManager().getEntityGraph(graphName); } @Override public List> getEntityGraphs(Class entityClass) { return getEntityManager().getEntityGraphs(entityClass); } //// Private logic methods private EntityManager getEntityManager() { EntityManager em; if (TxUtils.isActive(transactionManager)) { em = (EntityManager) transactionSynchronizationRegistry.getResource(unitName); if (em == null) { em = createEntityManager(); transactionSynchronizationRegistry.registerInterposedSynchronization(new TxSynchronization(em)); transactionSynchronizationRegistry.putResource(unitName, em); } else { validateCompatibleSyncTypes(em); } } else { em = nonTxEmHolder.getEntityManager(); if (em == null) { em = createEntityManager(); nonTxEmHolder.setEntityManager(em); } } return em; } private EntityManager createEntityManager() { if (sync.equals(SynchronizationType.UNSYNCHRONIZED)) { return new SyncEntityManagerWrapper(emf.createEntityManager(sync), sync); } return emf.createEntityManager(); } private void detachLoadedNonTxEntities(EntityManager em) { if (!TxUtils.isActive(transactionManager)) { em.clear(); } } private Query detachLoadedNonTxQueryEntities(Query query, EntityManager em) { if (!TxUtils.isActive(transactionManager)) { return new NonTxQueryWrapper(query, em); } return query; } private TypedQuery detachLoadedNonTxTypedQueryEntities(TypedQuery query, EntityManager em) { if (!TxUtils.isActive(transactionManager)) { return new NonTxTypedQueryWrapper<>(query, em); } return query; } private StoredProcedureQuery detachLoadedNonTxStoredProcedureQueryEntities(StoredProcedureQuery procedureQuery, EntityManager em) { if (!TxUtils.isActive(transactionManager)) { return new NonTxStoredProcedureQueryWrapper(procedureQuery, em); } return procedureQuery; } private void validateActiveTransaction() { if (!TxUtils.isActive(transactionManager)) { throw new TransactionRequiredException("An active transaction is required in order to perform this function."); } } private void validateCompatibleSyncTypes(EntityManager existingEm) { if (existingEm instanceof SyncEntityManagerWrapper && ((SyncEntityManagerWrapper) existingEm).getSynchronizationType().equals(sync)) { throw new IllegalStateException("Incompatible SynchronizationType for the same PersistenceContext across " + "multiple injection points. The SynchronizationType can not be SYNCHRONIZED if a " + "previous one that is UNSYCHRONIZED already exists."); } } } ================================================ FILE: components/jpa/common/src/main/java/com/kumuluz/ee/jpa/common/jta/TxScopedEntityManagerFactory.java ================================================ /* * Copyright (c) 2014-2017 Kumuluz and/or its affiliates * and other contributors as indicated by the @author tags and * the contributor list. * * Licensed under the MIT License (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://opensource.org/licenses/MIT * * The software is provided "AS IS", WITHOUT WARRANTY OF ANY KIND, express or * implied, including but not limited to the warranties of merchantability, * fitness for a particular purpose and noninfringement. in no event shall the * authors or copyright holders be liable for any claim, damages or other * liability, whether in an action of contract, tort or otherwise, arising from, * out of or in connection with the software or the use or other dealings in the * software. See the License for the specific language governing permissions and * limitations under the License. */ package com.kumuluz.ee.jpa.common.jta; import com.kumuluz.ee.jpa.common.injection.EntityManagerWrapper; import com.kumuluz.ee.jta.common.JtaProvider; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.SynchronizationType; import javax.transaction.TransactionManager; import javax.transaction.TransactionSynchronizationRegistry; /** * @author Tilen Faganel * @since 2.4.0 */ public class TxScopedEntityManagerFactory { public static EntityManagerWrapper buildEntityManagerWrapper(String unitName, EntityManagerFactory emf, SynchronizationType sync) { JtaProvider jtaProvider = JtaProvider.getInstance(); TransactionManager transactionManager = jtaProvider.getTransactionManager(); TransactionSynchronizationRegistry transactionSynchronizationRegistry = jtaProvider.getTransactionSynchronizationRegistry(); NonTxEntityManagerHolder emHolder = new NonTxEntityManagerHolder(); EntityManager em = new TxScopedEntityManager(unitName, emf, sync, transactionManager, transactionSynchronizationRegistry, emHolder); return new TxScopedEntityManagerWrapper(em, emHolder); } } ================================================ FILE: components/jpa/common/src/main/java/com/kumuluz/ee/jpa/common/jta/TxScopedEntityManagerWrapper.java ================================================ /* * Copyright (c) 2014-2017 Kumuluz and/or its affiliates * and other contributors as indicated by the @author tags and * the contributor list. * * Licensed under the MIT License (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://opensource.org/licenses/MIT * * The software is provided "AS IS", WITHOUT WARRANTY OF ANY KIND, express or * implied, including but not limited to the warranties of merchantability, * fitness for a particular purpose and noninfringement. in no event shall the * authors or copyright holders be liable for any claim, damages or other * liability, whether in an action of contract, tort or otherwise, arising from, * out of or in connection with the software or the use or other dealings in the * software. See the License for the specific language governing permissions and * limitations under the License. */ package com.kumuluz.ee.jpa.common.jta; import com.kumuluz.ee.jpa.common.injection.EntityManagerWrapper; import com.kumuluz.ee.jpa.common.jta.NonTxEntityManagerHolder; import javax.persistence.EntityManager; /** * @author Tilen Faganel * @since 2.4.0 */ public class TxScopedEntityManagerWrapper implements EntityManagerWrapper { private EntityManager em; private NonTxEntityManagerHolder nonTxEmHolder; public TxScopedEntityManagerWrapper(EntityManager em, NonTxEntityManagerHolder nonTxEmHolder) { this.em = em; this.nonTxEmHolder = nonTxEmHolder; } @Override public EntityManager getEntityManager() { return em; } @Override public void close() { EntityManager nonTxEm = nonTxEmHolder.getEntityManager(); if (nonTxEm != null && nonTxEm.isOpen()) { nonTxEm.close(); nonTxEmHolder.setEntityManager(null); } } } ================================================ FILE: components/jpa/common/src/main/java/com/kumuluz/ee/jpa/common/jta/TxSynchronization.java ================================================ /* * Copyright (c) 2014-2017 Kumuluz and/or its affiliates * and other contributors as indicated by the @author tags and * the contributor list. * * Licensed under the MIT License (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://opensource.org/licenses/MIT * * The software is provided "AS IS", WITHOUT WARRANTY OF ANY KIND, express or * implied, including but not limited to the warranties of merchantability, * fitness for a particular purpose and noninfringement. in no event shall the * authors or copyright holders be liable for any claim, damages or other * liability, whether in an action of contract, tort or otherwise, arising from, * out of or in connection with the software or the use or other dealings in the * software. See the License for the specific language governing permissions and * limitations under the License. */ package com.kumuluz.ee.jpa.common.jta; import javax.persistence.EntityManager; import javax.transaction.Synchronization; /** * @author Tilen Faganel * @since 2.4.0 */ public class TxSynchronization implements Synchronization { private EntityManager em; public TxSynchronization(EntityManager em) { this.em = em; } @Override public void beforeCompletion() { } @Override public void afterCompletion(int status) { if (em != null && em.isOpen()) { em.close(); } } } ================================================ FILE: components/jpa/common/src/main/java/com/kumuluz/ee/jpa/common/utils/PersistenceUtils.java ================================================ /* * Copyright (c) 2014-2017 Kumuluz and/or its affiliates * and other contributors as indicated by the @author tags and * the contributor list. * * Licensed under the MIT License (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://opensource.org/licenses/MIT * * The software is provided "AS IS", WITHOUT WARRANTY OF ANY KIND, express or * implied, including but not limited to the warranties of merchantability, * fitness for a particular purpose and noninfringement. in no event shall the * authors or copyright holders be liable for any claim, damages or other * liability, whether in an action of contract, tort or otherwise, arising from, * out of or in connection with the software or the use or other dealings in the * software. See the License for the specific language governing permissions and * limitations under the License. */ package com.kumuluz.ee.jpa.common.utils; import com.kumuluz.ee.jpa.common.TransactionType; import org.w3c.dom.Document; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import java.io.IOException; import java.net.URL; import java.util.Enumeration; import java.util.Optional; /** * @author Tilen Faganel * @since 2.3.0 */ public class PersistenceUtils { private static final String PERSISTENCE_XML = "META-INF/persistence.xml"; public static TransactionType getEntityManagerFactoryTransactionType(EntityManagerFactory emf) { EntityManager manager = emf.createEntityManager(); // Hibernate does not throw exception when getTransaction() in JTA context is called, this is the workaround // for JTA detection if (emf.getProperties().containsKey("hibernate.transaction.coordinator_class") && emf.getProperties().get("hibernate.transaction.coordinator_class") instanceof Class && ((Class) emf.getProperties().get("hibernate.transaction.coordinator_class")).getSimpleName() .equals("JtaTransactionCoordinatorBuilderImpl")) { return TransactionType.JTA; } try { manager.getTransaction(); return TransactionType.RESOURCE_LOCAL; } catch (IllegalStateException e) { manager.close(); return TransactionType.JTA; } } public static Optional getDefaultUnitName() { Document document; try { Enumeration enumeration = PersistenceUtils.class.getClassLoader().getResources(PERSISTENCE_XML); if (!enumeration.hasMoreElements()) { return Optional.empty(); } enumeration.nextElement(); if (enumeration.hasMoreElements()) { return Optional.empty(); } DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); document = builder.parse(PersistenceUtils.class.getClassLoader() .getResourceAsStream(PERSISTENCE_XML)); } catch (IOException | ParserConfigurationException | SAXException ex) { return Optional.empty(); } String rootElementName = document.getDocumentElement().getTagName(); if (!rootElementName.equals("persistence")) { return Optional.empty(); } NodeList childNodes = document.getDocumentElement().getElementsByTagName("persistence-unit"); if (childNodes.getLength() != 1) { return Optional.empty(); } String pu = childNodes.item(0).getNodeName(); if (!pu.equals("persistence-unit")) { return Optional.empty(); } String puName = childNodes.item(0).getAttributes().getNamedItem("name").getNodeValue(); if (puName != null && !puName.isEmpty()) { return Optional.of(puName); } return Optional.empty(); } } ================================================ FILE: components/jpa/common/src/main/resources/META-INF/services/org.jboss.weld.bootstrap.api.Service ================================================ com.kumuluz.ee.jpa.common.injection.JpaService ================================================ FILE: components/jpa/eclipselink/pom.xml ================================================ kumuluzee-jpa com.kumuluz.ee 4.2.0-SNAPSHOT 4.0.0 KumuluzEE JPA EclipseLink KumuluzEE JPA component implemented by EclipseLink kumuluzee-jpa-eclipselink com.kumuluz.ee kumuluzee-jpa-common jakarta.persistence jakarta.persistence-api org.eclipse.persistence org.eclipse.persistence.jpa ${eclipselink.version} org.eclipse.persistence javax.persistence org.glassfish javax.json com.kumuluz.ee kumuluzee-jta-common provided ================================================ FILE: components/jpa/eclipselink/src/main/java/com/kumuluz/ee/jpa/eclipselink/EclipseLinkSettings.java ================================================ /* * Copyright (c) 2014-2017 Kumuluz and/or its affiliates * and other contributors as indicated by the @author tags and * the contributor list. * * Licensed under the MIT License (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://opensource.org/licenses/MIT * * The software is provided "AS IS", WITHOUT WARRANTY OF ANY KIND, express or * implied, including but not limited to the warranties of merchantability, * fitness for a particular purpose and noninfringement. in no event shall the * authors or copyright holders be liable for any claim, damages or other * liability, whether in an action of contract, tort or otherwise, arising from, * out of or in connection with the software or the use or other dealings in the * software. See the License for the specific language governing permissions and * limitations under the License. */ package com.kumuluz.ee.jpa.eclipselink; import com.kumuluz.ee.jpa.common.PersistenceSettings; import org.eclipse.persistence.config.PersistenceUnitProperties; import java.util.HashMap; import java.util.Map; /** * @author Tilen Faganel * @since 2.3.0 */ public class EclipseLinkSettings implements PersistenceSettings { private Map properties = new HashMap<>(); private Boolean jtaPresent; EclipseLinkSettings(Boolean jtaPresent) { this.jtaPresent = jtaPresent; } @Override public Map getPersistenceUnitProperties() { if (jtaPresent) { properties.put(PersistenceUnitProperties.TARGET_SERVER, KumuluzPlatform.class.getName()); } return properties; } } ================================================ FILE: components/jpa/eclipselink/src/main/java/com/kumuluz/ee/jpa/eclipselink/JpaComponent.java ================================================ /* * Copyright (c) 2014-2017 Kumuluz and/or its affiliates * and other contributors as indicated by the @author tags and * the contributor list. * * Licensed under the MIT License (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://opensource.org/licenses/MIT * * The software is provided "AS IS", WITHOUT WARRANTY OF ANY KIND, express or * implied, including but not limited to the warranties of merchantability, * fitness for a particular purpose and noninfringement. in no event shall the * authors or copyright holders be liable for any claim, damages or other * liability, whether in an action of contract, tort or otherwise, arising from, * out of or in connection with the software or the use or other dealings in the * software. See the License for the specific language governing permissions and * limitations under the License. */ package com.kumuluz.ee.jpa.eclipselink; import com.kumuluz.ee.common.Component; import com.kumuluz.ee.common.config.EeConfig; import com.kumuluz.ee.common.dependencies.EeComponentDef; import com.kumuluz.ee.common.dependencies.EeComponentType; import com.kumuluz.ee.common.runtime.EeRuntime; import com.kumuluz.ee.common.wrapper.KumuluzServerWrapper; import com.kumuluz.ee.jpa.common.PersistenceUnitHolder; import java.util.logging.Logger; /** * @author Tilen Faganel * @since 1.0.0 */ @EeComponentDef(name = "EclipseLink", type = EeComponentType.JPA) public class JpaComponent implements Component { private Logger log = Logger.getLogger(JpaComponent.class.getSimpleName()); @Override public void init(KumuluzServerWrapper server, EeConfig eeConfig) { PersistenceUnitHolder holder = PersistenceUnitHolder.getInstance(); // Check if JTA is present in the runtime Boolean jtaPresent = EeRuntime.getInstance().getEeComponents().stream().anyMatch(c -> c.getType().equals(EeComponentType.JTA)); holder.setProviderProperties(new EclipseLinkSettings(jtaPresent)); } @Override public void load() { log.info("Initiating EclipseLink"); } } ================================================ FILE: components/jpa/eclipselink/src/main/java/com/kumuluz/ee/jpa/eclipselink/KumuluzPlatform.java ================================================ /* * Copyright (c) 2014-2017 Kumuluz and/or its affiliates * and other contributors as indicated by the @author tags and * the contributor list. * * Licensed under the MIT License (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://opensource.org/licenses/MIT * * The software is provided "AS IS", WITHOUT WARRANTY OF ANY KIND, express or * implied, including but not limited to the warranties of merchantability, * fitness for a particular purpose and noninfringement. in no event shall the * authors or copyright holders be liable for any claim, damages or other * liability, whether in an action of contract, tort or otherwise, arising from, * out of or in connection with the software or the use or other dealings in the * software. See the License for the specific language governing permissions and * limitations under the License. */ package com.kumuluz.ee.jpa.eclipselink; import org.eclipse.persistence.platform.server.ServerPlatformBase; import org.eclipse.persistence.sessions.DatabaseSession; /** * @author Marcos Koch Salvador * @since 2.3.0 */ public class KumuluzPlatform extends ServerPlatformBase { public KumuluzPlatform(DatabaseSession newDatabaseSession) { super(newDatabaseSession); } @Override public Class getExternalTransactionControllerClass() { return KumuluzTransactionController.class; } } ================================================ FILE: components/jpa/eclipselink/src/main/java/com/kumuluz/ee/jpa/eclipselink/KumuluzTransactionController.java ================================================ /* * Copyright (c) 2014-2017 Kumuluz and/or its affiliates * and other contributors as indicated by the @author tags and * the contributor list. * * Licensed under the MIT License (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://opensource.org/licenses/MIT * * The software is provided "AS IS", WITHOUT WARRANTY OF ANY KIND, express or * implied, including but not limited to the warranties of merchantability, * fitness for a particular purpose and noninfringement. in no event shall the * authors or copyright holders be liable for any claim, damages or other * liability, whether in an action of contract, tort or otherwise, arising from, * out of or in connection with the software or the use or other dealings in the * software. See the License for the specific language governing permissions and * limitations under the License. */ package com.kumuluz.ee.jpa.eclipselink; import com.kumuluz.ee.jta.common.JtaProvider; import org.eclipse.persistence.transaction.JTATransactionController; import javax.transaction.TransactionManager; /** * @author Marcos Koch Salvador * @since 2.3.0 */ public class KumuluzTransactionController extends JTATransactionController { @Override protected TransactionManager acquireTransactionManager() throws Exception { return JtaProvider.getInstance().getTransactionManager(); } } ================================================ FILE: components/jpa/eclipselink/src/main/resources/META-INF/services/com.kumuluz.ee.common.Component ================================================ com.kumuluz.ee.jpa.eclipselink.JpaComponent ================================================ FILE: components/jpa/hibernate/pom.xml ================================================ kumuluzee-jpa com.kumuluz.ee 4.2.0-SNAPSHOT 4.0.0 KumuluzEE JPA Hibernate KumuluzEE JPA component implemented by Hibernate kumuluzee-jpa-hibernate com.kumuluz.ee kumuluzee-jpa-common jakarta.transaction jakarta.transaction-api org.hibernate hibernate-core ${hibernate.version} org.jboss.spec.javax.transaction jboss-transaction-api_1.2_spec org.jboss jandex org.jboss.logging jboss-logging com.fasterxml classmate org.javassist javassist org.jboss jandex org.jboss.logging jboss-logging com.fasterxml classmate org.javassist javassist javax.xml.bind jaxb-api ${jaxb-api.version} ================================================ FILE: components/jpa/hibernate/src/main/java/com/kumuluz/ee/jpa/hibernate/JpaComponent.java ================================================ /* * Copyright (c) 2014-2017 Kumuluz and/or its affiliates * and other contributors as indicated by the @author tags and * the contributor list. * * Licensed under the MIT License (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://opensource.org/licenses/MIT * * The software is provided "AS IS", WITHOUT WARRANTY OF ANY KIND, express or * implied, including but not limited to the warranties of merchantability, * fitness for a particular purpose and noninfringement. in no event shall the * authors or copyright holders be liable for any claim, damages or other * liability, whether in an action of contract, tort or otherwise, arising from, * out of or in connection with the software or the use or other dealings in the * software. See the License for the specific language governing permissions and * limitations under the License. */ package com.kumuluz.ee.jpa.hibernate; import com.kumuluz.ee.common.Component; import com.kumuluz.ee.common.config.EeConfig; import com.kumuluz.ee.common.dependencies.EeComponentDef; import com.kumuluz.ee.common.dependencies.EeComponentType; import com.kumuluz.ee.common.wrapper.KumuluzServerWrapper; import java.util.logging.Logger; /** * @author Tilen Faganel * @since 2.1.0 */ @EeComponentDef(name = "Hibernate", type = EeComponentType.JPA) public class JpaComponent implements Component { private final Logger log = Logger.getLogger(JpaComponent.class.getSimpleName()); @Override public void init(KumuluzServerWrapper server, EeConfig eeConfig) { } @Override public void load() { log.info("Initiating Hibernate"); } } ================================================ FILE: components/jpa/hibernate/src/main/resources/META-INF/services/com.kumuluz.ee.common.Component ================================================ com.kumuluz.ee.jpa.hibernate.JpaComponent ================================================ FILE: components/jpa/pom.xml ================================================ kumuluzee-components com.kumuluz.ee 4.2.0-SNAPSHOT 4.0.0 pom eclipselink hibernate common KumuluzEE JPA KumuluzEE JPA component kumuluzee-jpa ================================================ FILE: components/jsf/mojarra/pom.xml ================================================ kumuluzee-jsf com.kumuluz.ee 4.2.0-SNAPSHOT 4.0.0 KumuluzEE JSF Mojarra KumuluzEE JSF component implemented by Mojarra kumuluzee-jsf-mojarra com.kumuluz.ee kumuluzee-common jakarta.websocket jakarta.websocket-api jakarta.websocket jakarta.websocket-client-api org.glassfish jakarta.faces ${mojarra.version} ================================================ FILE: components/jsf/mojarra/src/main/java/com/kumuluz/ee/jsf/mojarra/JsfComponent.java ================================================ /* * Copyright (c) 2014-2017 Kumuluz and/or its affiliates * and other contributors as indicated by the @author tags and * the contributor list. * * Licensed under the MIT License (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://opensource.org/licenses/MIT * * The software is provided "AS IS", WITHOUT WARRANTY OF ANY KIND, express or * implied, including but not limited to the warranties of merchantability, * fitness for a particular purpose and noninfringement. in no event shall the * authors or copyright holders be liable for any claim, damages or other * liability, whether in an action of contract, tort or otherwise, arising from, * out of or in connection with the software or the use or other dealings in the * software. See the License for the specific language governing permissions and * limitations under the License. */ package com.kumuluz.ee.jsf.mojarra; import com.kumuluz.ee.common.Component; import com.kumuluz.ee.common.config.EeConfig; import com.kumuluz.ee.common.dependencies.EeComponentDef; import com.kumuluz.ee.common.dependencies.EeComponentDependency; import com.kumuluz.ee.common.dependencies.EeComponentType; import com.kumuluz.ee.common.wrapper.KumuluzServerWrapper; import java.util.logging.Logger; /** * @author Tilen Faganel * @since 2.0.0 */ @EeComponentDef(name = "Mojarra", type = EeComponentType.JSF) @EeComponentDependency(value = EeComponentType.SERVLET) @EeComponentDependency(value = EeComponentType.JSP) @EeComponentDependency(value = EeComponentType.EL) public class JsfComponent implements Component { private Logger log = Logger.getLogger(JsfComponent.class.getSimpleName()); @Override public void init(KumuluzServerWrapper server, EeConfig eeConfig) { } @Override public void load() { log.info("Initiating Mojarra"); } } ================================================ FILE: components/jsf/mojarra/src/main/resources/META-INF/services/com.kumuluz.ee.common.Component ================================================ com.kumuluz.ee.jsf.mojarra.JsfComponent ================================================ FILE: components/jsf/pom.xml ================================================ kumuluzee-components com.kumuluz.ee 4.2.0-SNAPSHOT 4.0.0 pom mojarra KumuluzEE JSF KumuluzEE JSF component kumuluzee-jsf ================================================ FILE: components/json-b/pom.xml ================================================ kumuluzee-components com.kumuluz.ee 4.2.0-SNAPSHOT 4.0.0 pom KumuluzEE JSON-B KumuluzEE JSOP-B component yasson kumuluzee-json-b ================================================ FILE: components/json-b/yasson/pom.xml ================================================ kumuluzee-json-b com.kumuluz.ee 4.2.0-SNAPSHOT 4.0.0 kumuluzee-json-b-yasson KumuluzEE JSON-B Yasson KumuluzEE JSOP-B component implemented by Yasson com.kumuluz.ee kumuluzee-common org.eclipse yasson ${yasson.version} javax.json javax.json-api javax.enterprise cdi-api org.glassfish.jersey.media jersey-media-json-binding ${jersey.version} org.glassfish.jersey.core jersey-common org.glassfish javax.json org.eclipse yasson javax.json.bind javax.json.bind-api ================================================ FILE: components/json-b/yasson/src/main/java/com/kumuluz/ee/jsonb/yasson/JsonBComponent.java ================================================ package com.kumuluz.ee.jsonb.yasson; import com.kumuluz.ee.common.Component; import com.kumuluz.ee.common.config.EeConfig; import com.kumuluz.ee.common.dependencies.EeComponentDef; import com.kumuluz.ee.common.dependencies.EeComponentDependency; import com.kumuluz.ee.common.dependencies.EeComponentType; import com.kumuluz.ee.common.wrapper.KumuluzServerWrapper; import java.util.logging.Logger; /** * @author Tilen Faganel * @since 2.6.0 */ @EeComponentDef(name = "Yasson", type = EeComponentType.JSON_B) @EeComponentDependency(value = EeComponentType.JSON_P) public class JsonBComponent implements Component { private Logger log = Logger.getLogger(JsonBComponent.class.getSimpleName()); @Override public void init(KumuluzServerWrapper server, EeConfig eeConfig) { } @Override public void load() { log.info("Initiating Yasson"); } } ================================================ FILE: components/json-b/yasson/src/main/resources/META-INF/services/com.kumuluz.ee.common.Component ================================================ com.kumuluz.ee.jsonb.yasson.JsonBComponent ================================================ FILE: components/json-p/jsonp/pom.xml ================================================ kumuluzee-json-p com.kumuluz.ee 4.2.0-SNAPSHOT 4.0.0 kumuluzee-json-p-jsonp KumuluzEE JSON-P JSONP KumuluzEE JSOP-P component implemented by JSONP com.kumuluz.ee kumuluzee-common org.glassfish javax.json ${jsonp-impl.version} org.glassfish.jersey.media jersey-media-json-processing ${jersey.version} org.glassfish.jersey.core jersey-common org.glassfish javax.json javax.ws.rs javax.ws.rs-api ================================================ FILE: components/json-p/jsonp/src/main/java/com/kumuluz/ee/jsonp/JsonPComponent.java ================================================ /* * Copyright (c) 2014-2017 Kumuluz and/or its affiliates * and other contributors as indicated by the @author tags and * the contributor list. * * Licensed under the MIT License (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://opensource.org/licenses/MIT * * The software is provided "AS IS", WITHOUT WARRANTY OF ANY KIND, express or * implied, including but not limited to the warranties of merchantability, * fitness for a particular purpose and noninfringement. in no event shall the * authors or copyright holders be liable for any claim, damages or other * liability, whether in an action of contract, tort or otherwise, arising from, * out of or in connection with the software or the use or other dealings in the * software. See the License for the specific language governing permissions and * limitations under the License. */ package com.kumuluz.ee.jsonp; import com.kumuluz.ee.common.Component; import com.kumuluz.ee.common.config.EeConfig; import com.kumuluz.ee.common.dependencies.EeComponentDef; import com.kumuluz.ee.common.dependencies.EeComponentType; import com.kumuluz.ee.common.wrapper.KumuluzServerWrapper; import java.util.logging.Logger; /** * @author Tilen Faganel * @since 1.0.0 */ @EeComponentDef(name = "JSONP", type = EeComponentType.JSON_P) public class JsonPComponent implements Component { private Logger log = Logger.getLogger(JsonPComponent.class.getSimpleName()); @Override public void init(KumuluzServerWrapper server, EeConfig eeConfig) { } @Override public void load() { log.info("Initiating JSONP"); } } ================================================ FILE: components/json-p/jsonp/src/main/java/com/kumuluz/ee/jsonp/configuration/utils/JsonConfigurationUtil.java ================================================ /* * Copyright (c) 2014-2017 Kumuluz and/or its affiliates * and other contributors as indicated by the @author tags and * the contributor list. * * Licensed under the MIT License (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://opensource.org/licenses/MIT * * The software is provided "AS IS", WITHOUT WARRANTY OF ANY KIND, express or * implied, including but not limited to the warranties of merchantability, * fitness for a particular purpose and noninfringement. in no event shall the * authors or copyright holders be liable for any claim, damages or other * liability, whether in an action of contract, tort or otherwise, arising from, * out of or in connection with the software or the use or other dealings in the * software. See the License for the specific language governing permissions and * limitations under the License. */ package com.kumuluz.ee.jsonp.configuration.utils; import com.kumuluz.ee.configuration.utils.ConfigurationUtil; import javax.json.*; import java.util.Optional; /** * Enables retrieval of a part of a configuration hierarchy as a JSON-P object/array. * * @author Urban Malc * @since 3.4.0 */ public class JsonConfigurationUtil { private static JsonConfigurationUtil instance = null; private static synchronized void initialize() { if (instance == null) { instance = getBuilder().build(); } } public static JsonConfigurationUtil getInstance() { if (instance == null) { initialize(); } return instance; } public static Builder getBuilder() { return new JsonConfigurationUtil.Builder(); } private JsonConfigurationUtil() { } private ConfigurationUtil config = ConfigurationUtil.getInstance(); private String mapToNull; private String mapToEmptyObject; private String mapToEmptyArray; private JsonValue getMappingIfAvailable(String s) { if (mapToNull != null && mapToNull.equals(s)) { return JsonValue.NULL; } if (mapToEmptyObject != null && mapToEmptyObject.equals(s)) { return JsonValue.EMPTY_JSON_OBJECT; } if (mapToEmptyArray != null && mapToEmptyArray.equals(s)) { return JsonValue.EMPTY_JSON_ARRAY; } return null; } public Optional getJsonObject(String key) { JsonObjectBuilder objectBuilder = Json.createObjectBuilder(); config.getMapKeys(key).ifPresent(mapList -> mapList.forEach(prop -> { String nextKey = (key.equals("")) ? prop : key + "." + prop; config.getType(nextKey).ifPresent(type -> { switch (type) { case MAP: getJsonObject(nextKey).ifPresent(o -> objectBuilder.add(prop, o)); break; case LIST: getJsonArray(nextKey).ifPresent(a -> objectBuilder.add(prop, a)); break; case INTEGER: config.getInteger(nextKey).ifPresent(value -> objectBuilder.add(prop, value)); break; case LONG: config.getLong(nextKey).ifPresent(value -> objectBuilder.add(prop, value)); break; case DOUBLE: config.getDouble(nextKey).ifPresent(value -> objectBuilder.add(prop, value)); break; case FLOAT: config.getFloat(nextKey).ifPresent(value -> objectBuilder.add(prop, value)); break; case BOOLEAN: config.getBoolean(nextKey).ifPresent(value -> objectBuilder.add(prop, value)); break; case STRING: config.get(nextKey).ifPresent(s -> { JsonValue mapped = getMappingIfAvailable(s); if (mapped != null) { objectBuilder.add(prop, mapped); } else { objectBuilder.add(prop, s); } }); break; } }); })); JsonObject jsonObject = objectBuilder.build(); if (jsonObject.isEmpty()) { return Optional.empty(); } return Optional.of(jsonObject); } public Optional getJsonArray(String key) { JsonArrayBuilder arrayBuilder = Json.createArrayBuilder(); config.getListSize(key).ifPresent(listSize -> { for (int i = 0; i < listSize; i++) { String nextKey = key + "[" + i + "]"; config.getType(nextKey).ifPresent(type -> { switch (type) { case MAP: getJsonObject(nextKey).ifPresent(arrayBuilder::add); break; case LIST: getJsonArray(nextKey).ifPresent(arrayBuilder::add); break; case INTEGER: config.getInteger(nextKey).ifPresent(arrayBuilder::add); break; case LONG: config.getLong(nextKey).ifPresent(arrayBuilder::add); break; case DOUBLE: config.getDouble(nextKey).ifPresent(arrayBuilder::add); break; case FLOAT: config.getFloat(nextKey).ifPresent(arrayBuilder::add); break; case BOOLEAN: config.getBoolean(nextKey).ifPresent(arrayBuilder::add); break; case STRING: config.get(nextKey).ifPresent(s -> { JsonValue mapped = getMappingIfAvailable(s); if (mapped != null) { arrayBuilder.add(mapped); } else { arrayBuilder.add(s); } }); break; } }); } }); JsonArray jsonArray = arrayBuilder.build(); if (jsonArray.isEmpty()) { return Optional.empty(); } return Optional.of(jsonArray); } public static final class Builder { private String mapToNull; private String mapToEmptyObject; private String mapToEmptyArray; private Builder() { } public Builder mapToNull(String mapToNull) { this.mapToNull = mapToNull; return this; } public Builder mapToEmptyObject(String mapToEmptyObject) { this.mapToEmptyObject = mapToEmptyObject; return this; } public Builder mapToEmptyArray(String mapToEmptyArray) { this.mapToEmptyArray = mapToEmptyArray; return this; } public JsonConfigurationUtil build() { JsonConfigurationUtil jsonConfigurationUtil = new JsonConfigurationUtil(); jsonConfigurationUtil.mapToEmptyObject = this.mapToEmptyObject; jsonConfigurationUtil.mapToEmptyArray = this.mapToEmptyArray; jsonConfigurationUtil.mapToNull = this.mapToNull; return jsonConfigurationUtil; } } } ================================================ FILE: components/json-p/jsonp/src/main/resources/META-INF/services/com.kumuluz.ee.common.Component ================================================ com.kumuluz.ee.jsonp.JsonPComponent ================================================ FILE: components/json-p/pom.xml ================================================ kumuluzee-components com.kumuluz.ee 4.2.0-SNAPSHOT 4.0.0 pom KumuluzEE JSON-P KumuluzEE JSOP-P component jsonp kumuluzee-json-p ================================================ FILE: components/jsp/jetty/pom.xml ================================================ kumuluzee-jsp com.kumuluz.ee 4.2.0-SNAPSHOT 4.0.0 kumuluzee-jsp-jetty KumuluzEE JSP Jetty KumuluzEE JSP component implemented by Jetty (Apache Jasper) com.kumuluz.ee kumuluzee-common org.eclipse.jetty apache-jsp ${jetty.version} org.mortbay.jasper apache-el javax.servlet javax.servlet-api junit junit test ================================================ FILE: components/jsp/jetty/src/main/java/com/kumuluz/ee/jsp/JspComponent.java ================================================ /* * Copyright (c) 2014-2017 Kumuluz and/or its affiliates * and other contributors as indicated by the @author tags and * the contributor list. * * Licensed under the MIT License (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://opensource.org/licenses/MIT * * The software is provided "AS IS", WITHOUT WARRANTY OF ANY KIND, express or * implied, including but not limited to the warranties of merchantability, * fitness for a particular purpose and noninfringement. in no event shall the * authors or copyright holders be liable for any claim, damages or other * liability, whether in an action of contract, tort or otherwise, arising from, * out of or in connection with the software or the use or other dealings in the * software. See the License for the specific language governing permissions and * limitations under the License. */ package com.kumuluz.ee.jsp; import com.kumuluz.ee.common.Component; import com.kumuluz.ee.common.config.EeConfig; import com.kumuluz.ee.common.dependencies.EeComponentDef; import com.kumuluz.ee.common.dependencies.EeComponentDependency; import com.kumuluz.ee.common.dependencies.EeComponentType; import com.kumuluz.ee.common.wrapper.KumuluzServerWrapper; import java.util.logging.Logger; /** * @author Tilen Faganel * @since 1.0.0 */ @EeComponentDef(name = "Jetty", type = EeComponentType.JSP) @EeComponentDependency(value = EeComponentType.SERVLET, implementations = {"Jetty"}) @EeComponentDependency(value = EeComponentType.EL) public class JspComponent implements Component { private Logger log = Logger.getLogger(JspComponent.class.getSimpleName()); @Override public void init(KumuluzServerWrapper server, EeConfig eeConfig) { } @Override public void load() { log.info("Initiating Jetty Apache Jasper"); } } ================================================ FILE: components/jsp/jetty/src/main/resources/META-INF/services/com.kumuluz.ee.common.Component ================================================ com.kumuluz.ee.jsp.JspComponent ================================================ FILE: components/jsp/jetty/src/test/java/com/kumuluz/ee/jetty/jsp/test/JspTest.java ================================================ /* * Copyright (c) 2014-2017 Kumuluz and/or its affiliates * and other contributors as indicated by the @author tags and * the contributor list. * * Licensed under the MIT License (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://opensource.org/licenses/MIT * * The software is provided "AS IS", WITHOUT WARRANTY OF ANY KIND, express or * implied, including but not limited to the warranties of merchantability, * fitness for a particular purpose and noninfringement. in no event shall the * authors or copyright holders be liable for any claim, damages or other * liability, whether in an action of contract, tort or otherwise, arising from, * out of or in connection with the software or the use or other dealings in the * software. See the License for the specific language governing permissions and * limitations under the License. */ package com.kumuluz.ee.jetty.jsp.test; import org.junit.Test; /** * @author Tilen */ public class JspTest { @Test public void testJspServlet() { } } ================================================ FILE: components/jsp/jetty/src/test/java/com/kumuluz/ee/jetty/jsp/test/beans/TimeBean.java ================================================ /* * Copyright (c) 2014-2017 Kumuluz and/or its affiliates * and other contributors as indicated by the @author tags and * the contributor list. * * Licensed under the MIT License (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://opensource.org/licenses/MIT * * The software is provided "AS IS", WITHOUT WARRANTY OF ANY KIND, express or * implied, including but not limited to the warranties of merchantability, * fitness for a particular purpose and noninfringement. in no event shall the * authors or copyright holders be liable for any claim, damages or other * liability, whether in an action of contract, tort or otherwise, arising from, * out of or in connection with the software or the use or other dealings in the * software. See the License for the specific language governing permissions and * limitations under the License. */ package com.kumuluz.ee.jetty.jsp.test.beans; import java.util.Date; /** * @author Tilen */ public class TimeBean { private Date currentTime; public TimeBean() { currentTime = new Date(); } public Date getCurrentTime() { return currentTime; } public void setCurrentTime(Date currentTime) { this.currentTime = currentTime; } } ================================================ FILE: components/jsp/jetty/src/test/java/com/kumuluz/ee/jetty/jsp/test/beans/UserBean.java ================================================ /* * Copyright (c) 2014-2017 Kumuluz and/or its affiliates * and other contributors as indicated by the @author tags and * the contributor list. * * Licensed under the MIT License (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://opensource.org/licenses/MIT * * The software is provided "AS IS", WITHOUT WARRANTY OF ANY KIND, express or * implied, including but not limited to the warranties of merchantability, * fitness for a particular purpose and noninfringement. in no event shall the * authors or copyright holders be liable for any claim, damages or other * liability, whether in an action of contract, tort or otherwise, arising from, * out of or in connection with the software or the use or other dealings in the * software. See the License for the specific language governing permissions and * limitations under the License. */ package com.kumuluz.ee.jetty.jsp.test.beans; import java.time.LocalDate; import java.time.ZoneId; import java.util.Date; /** * @author Tilen */ public class UserBean { private String username; private String email; private String firstname; private String lastname; private Integer age; private String country; private Date created; public UserBean() { username = "ahughes"; email = "amy.hughes@mac.com"; firstname = "Amy"; lastname = "Hughes"; age = 1; country = "US"; created = Date.from( LocalDate.of(2014, 3, 3) .atStartOfDay() .atZone(ZoneId.systemDefault()) .toInstant()); } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getFirstname() { return firstname; } public void setFirstname(String firstname) { this.firstname = firstname; } public String getLastname() { return lastname; } public void setLastname(String lastname) { this.lastname = lastname; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } public String getCountry() { return country; } public void setCountry(String country) { country = country; } public Date getCreated() { return created; } public void setCreated(Date created) { this.created = created; } } ================================================ FILE: components/jsp/jetty/src/test/resources/webapp/index.jsp ================================================ KumuluzEE Jsp test

The time is: <%= time.getCurrentTime() %>

The current user is:
Username: <%= user.getUsername() %>
Email: <%= user.getEmail() %>
First name: <%= user.getFirstname() %>
Last name: <%= user.getLastname() %>
Age: <%= user.getAge() %>
Country: <%= user.getCountry() %>
Created: <%= user.getCreated() %>

================================================ FILE: components/jsp/pom.xml ================================================ kumuluzee-components com.kumuluz.ee 4.2.0-SNAPSHOT 4.0.0 pom KumuluzEE JSP KumuluzEE JSP component jetty kumuluzee-jsp ================================================ FILE: components/jta/common/pom.xml ================================================ kumuluzee-jta com.kumuluz.ee 4.2.0-SNAPSHOT 4.0.0 KumuluzEE JTA Common KumuluzEE JTA component common utilities, configs and exceptions kumuluzee-jta-common com.kumuluz.ee kumuluzee-common jakarta.transaction jakarta.transaction-api jakarta.resource jakarta.resource-api org.jboss.weld.module weld-jta ${weld.version} org.jboss.spec.javax.transaction jboss-transaction-api_1.3_spec org.jboss.spec.javax.annotation jboss-annotations-api_1.3_spec org.jboss.spec.javax.el jboss-el-api_3.0_spec org.jboss.spec.javax.interceptor jboss-interceptors-api_1.2_spec org.jboss.logging jboss-logging org.jboss.logging jboss-logging com.kumuluz.ee kumuluzee-cdi-weld provided ================================================ FILE: components/jta/common/src/main/java/com/kumuluz/ee/jta/common/JtaProvider.java ================================================ /* * Copyright (c) 2014-2017 Kumuluz and/or its affiliates * and other contributors as indicated by the @author tags and * the contributor list. * * Licensed under the MIT License (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://opensource.org/licenses/MIT * * The software is provided "AS IS", WITHOUT WARRANTY OF ANY KIND, express or * implied, including but not limited to the warranties of merchantability, * fitness for a particular purpose and noninfringement. in no event shall the * authors or copyright holders be liable for any claim, damages or other * liability, whether in an action of contract, tort or otherwise, arising from, * out of or in connection with the software or the use or other dealings in the * software. See the License for the specific language governing permissions and * limitations under the License. */ package com.kumuluz.ee.jta.common; import com.kumuluz.ee.common.exceptions.KumuluzServerException; import io.agroal.api.transaction.TransactionIntegration; import javax.transaction.Status; import javax.transaction.TransactionManager; import javax.transaction.TransactionSynchronizationRegistry; import javax.transaction.UserTransaction; import java.util.Arrays; import java.util.Iterator; import java.util.List; import java.util.ServiceLoader; /** * @author Marcos Koch Salvador * @since 2.3.0 */ public abstract class JtaProvider { public static final List TRANSACTION_ACTIVE_STATUS = Arrays.asList( Status.STATUS_ACTIVE, Status.STATUS_COMMITTING, Status.STATUS_MARKED_ROLLBACK, Status.STATUS_PREPARED, Status.STATUS_PREPARING, Status.STATUS_ROLLING_BACK ); private static JtaProvider instance; public static JtaProvider getInstance() { if (instance == null) { Iterator it = ServiceLoader.load(JtaProvider.class).iterator(); if (!it.hasNext()) { throw new KumuluzServerException("No JTA components were found"); } instance = it.next(); } return instance; } public abstract UserTransaction getUserTransaction(); public abstract TransactionManager getTransactionManager(); public abstract TransactionSynchronizationRegistry getTransactionSynchronizationRegistry(); public abstract TransactionIntegration getTransactionIntegration(String jndiName); } ================================================ FILE: components/jta/common/src/main/java/com/kumuluz/ee/jta/common/JtaTransactionServices.java ================================================ /* * Copyright (c) 2014-2017 Kumuluz and/or its affiliates * and other contributors as indicated by the @author tags and * the contributor list. * * Licensed under the MIT License (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://opensource.org/licenses/MIT * * The software is provided "AS IS", WITHOUT WARRANTY OF ANY KIND, express or * implied, including but not limited to the warranties of merchantability, * fitness for a particular purpose and noninfringement. in no event shall the * authors or copyright holders be liable for any claim, damages or other * liability, whether in an action of contract, tort or otherwise, arising from, * out of or in connection with the software or the use or other dealings in the * software. See the License for the specific language governing permissions and * limitations under the License. */ package com.kumuluz.ee.jta.common; import org.jboss.weld.transaction.spi.TransactionServices; import javax.transaction.Synchronization; import javax.transaction.SystemException; import javax.transaction.UserTransaction; /** * @author Marcos Koch Salvador * @since 2.3.0 */ public class JtaTransactionServices implements TransactionServices { @Override public void registerSynchronization(Synchronization synchronizedObserver) { try { JtaProvider.getInstance().getTransactionManager().getTransaction().registerSynchronization(synchronizedObserver); } catch (IllegalStateException | javax.transaction.RollbackException | SystemException e) { throw new RuntimeException(e); } } @Override public boolean isTransactionActive() { try { int status = JtaProvider.getInstance().getTransactionManager().getStatus(); return JtaProvider.TRANSACTION_ACTIVE_STATUS.contains(status); } catch (SystemException e) { throw new RuntimeException(e); } } @Override public UserTransaction getUserTransaction() { return JtaProvider.getInstance().getUserTransaction(); } @Override public void cleanup() { } } ================================================ FILE: components/jta/common/src/main/java/com/kumuluz/ee/jta/common/datasources/JtaXAConnectionWrapper.java ================================================ /* * Copyright (c) 2014-2017 Kumuluz and/or its affiliates * and other contributors as indicated by the @author tags and * the contributor list. * * Licensed under the MIT License (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://opensource.org/licenses/MIT * * The software is provided "AS IS", WITHOUT WARRANTY OF ANY KIND, express or * implied, including but not limited to the warranties of merchantability, * fitness for a particular purpose and noninfringement. in no event shall the * authors or copyright holders be liable for any claim, damages or other * liability, whether in an action of contract, tort or otherwise, arising from, * out of or in connection with the software or the use or other dealings in the * software. See the License for the specific language governing permissions and * limitations under the License. */ package com.kumuluz.ee.jta.common.datasources; import com.kumuluz.ee.jta.common.JtaProvider; import com.kumuluz.ee.jta.common.utils.TxUtils; import javax.sql.XAConnection; import javax.transaction.RollbackException; import javax.transaction.Synchronization; import javax.transaction.SystemException; import javax.transaction.TransactionManager; import javax.transaction.xa.XAResource; import java.sql.*; import java.util.Collections; import java.util.Map; import java.util.Properties; import java.util.concurrent.Executor; import java.util.logging.Logger; /** * @author Tilen Faganel * @since 2.3.0 */ @Deprecated public class JtaXAConnectionWrapper implements Connection { private Logger log = Logger.getLogger(JtaXAConnectionWrapper.class.getSimpleName()); private Boolean isClosed = false; private Boolean isEnlistedInJTA = false; private Boolean closeAfterTransactionEnd = false; private XAConnection parentConnection; private Connection xaConnection; private XAResource xaResource; private TransactionManager transactionManager; public JtaXAConnectionWrapper(XAConnection xaConnection) throws SQLException { this.xaResource = xaConnection.getXAResource(); this.parentConnection = xaConnection; this.xaConnection = xaConnection.getConnection(); } @Override public Statement createStatement() throws SQLException { checkIfValid(); jtaPreInvoke(); Statement statement = xaConnection.createStatement(); return (Statement) XAStatementProxy.newInstance(statement, this); } @Override public PreparedStatement prepareStatement(String sql) throws SQLException { checkIfValid(); jtaPreInvoke(); PreparedStatement preparedStatement = xaConnection.prepareStatement(sql); return (PreparedStatement) XAStatementProxy.newInstance(preparedStatement, this); } @Override public CallableStatement prepareCall(String sql) throws SQLException { checkIfValid(); jtaPreInvoke(); CallableStatement callableStatement = xaConnection.prepareCall(sql); return (CallableStatement) XAStatementProxy.newInstance(callableStatement, this); } @Override public String nativeSQL(String sql) throws SQLException { checkIfValid(); return xaConnection.nativeSQL(sql); } @Override public boolean getAutoCommit() throws SQLException { checkIfValid(); jtaPreInvoke(); return xaConnection.getAutoCommit(); } @Override public void setAutoCommit(boolean autoCommit) throws SQLException { checkIfValid(); jtaPreInvoke(); xaConnection.setAutoCommit(autoCommit); } @Override public void commit() throws SQLException { checkIfValid(); xaConnection.commit(); } @Override public void rollback() throws SQLException { checkIfValid(); jtaPreInvoke(); xaConnection.rollback(); } @Override public void close() throws SQLException { if (isClosed) return; isClosed = true; if (isEnlistedInJTA) { closeAfterTransactionEnd = true; return; } closeConnections(this); } @Override public boolean isClosed() throws SQLException { if (!isClosed) { jtaPreInvoke(); } return isClosed; } @Override public DatabaseMetaData getMetaData() throws SQLException { checkIfValid(); jtaPreInvoke(); return xaConnection.getMetaData(); } @Override public boolean isReadOnly() throws SQLException { checkIfValid(); jtaPreInvoke(); return xaConnection.isReadOnly(); } @Override public void setReadOnly(boolean readOnly) throws SQLException { checkIfValid(); jtaPreInvoke(); xaConnection.setReadOnly(readOnly); } @Override public String getCatalog() throws SQLException { checkIfValid(); jtaPreInvoke(); return xaConnection.getCatalog(); } @Override public void setCatalog(String catalog) throws SQLException { checkIfValid(); jtaPreInvoke(); xaConnection.setCatalog(catalog); } @Override public int getTransactionIsolation() throws SQLException { checkIfValid(); jtaPreInvoke(); return xaConnection.getTransactionIsolation(); } @Override public void setTransactionIsolation(int level) throws SQLException { checkIfValid(); jtaPreInvoke(); xaConnection.setTransactionIsolation(level); } @Override public SQLWarning getWarnings() throws SQLException { checkIfValid(); jtaPreInvoke(); return xaConnection.getWarnings(); } @Override public void clearWarnings() throws SQLException { checkIfValid(); jtaPreInvoke(); xaConnection.clearWarnings(); } @Override public Statement createStatement(int resultSetType, int resultSetConcurrency) throws SQLException { checkIfValid(); jtaPreInvoke(); Statement statement = xaConnection.createStatement(resultSetType, resultSetConcurrency); return (Statement) XAStatementProxy.newInstance(statement, this); } @Override public PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency) throws SQLException { checkIfValid(); jtaPreInvoke(); PreparedStatement preparedStatement = xaConnection.prepareStatement(sql, resultSetType, resultSetConcurrency); return (PreparedStatement) XAStatementProxy.newInstance(preparedStatement, this); } @Override public CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency) throws SQLException { checkIfValid(); jtaPreInvoke(); CallableStatement callableStatement = xaConnection.prepareCall(sql, resultSetType, resultSetConcurrency); return (CallableStatement) XAStatementProxy.newInstance(callableStatement, this); } @Override public Map> getTypeMap() throws SQLException { checkIfValid(); jtaPreInvoke(); return xaConnection.getTypeMap(); } @Override public void setTypeMap(Map> map) throws SQLException { checkIfValid(); jtaPreInvoke(); xaConnection.setTypeMap(map); } @Override public int getHoldability() throws SQLException { checkIfValid(); jtaPreInvoke(); return xaConnection.getHoldability(); } @Override public void setHoldability(int holdability) throws SQLException { checkIfValid(); jtaPreInvoke(); xaConnection.setHoldability(holdability); } @Override public Savepoint setSavepoint() throws SQLException { checkIfValid(); jtaPreInvoke(); return xaConnection.setSavepoint(); } @Override public Savepoint setSavepoint(String name) throws SQLException { checkIfValid(); jtaPreInvoke(); return xaConnection.setSavepoint(name); } @Override public void rollback(Savepoint savepoint) throws SQLException { checkIfValid(); jtaPreInvoke(); xaConnection.rollback(); } @Override public void releaseSavepoint(Savepoint savepoint) throws SQLException { checkIfValid(); jtaPreInvoke(); xaConnection.releaseSavepoint(savepoint); } @Override public Statement createStatement(int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException { checkIfValid(); jtaPreInvoke(); Statement statement = xaConnection.createStatement(resultSetType, resultSetConcurrency, resultSetHoldability); return (Statement) XAStatementProxy.newInstance(statement, this); } @Override public PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException { checkIfValid(); jtaPreInvoke(); PreparedStatement preparedStatement = xaConnection.prepareStatement(sql, resultSetType, resultSetConcurrency, resultSetHoldability); return (PreparedStatement) XAStatementProxy.newInstance(preparedStatement, this); } @Override public CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException { checkIfValid(); jtaPreInvoke(); CallableStatement callableStatement = xaConnection.prepareCall(sql, resultSetType, resultSetConcurrency, resultSetHoldability); return (CallableStatement) XAStatementProxy.newInstance(callableStatement, this); } @Override public PreparedStatement prepareStatement(String sql, int autoGeneratedKeys) throws SQLException { checkIfValid(); jtaPreInvoke(); PreparedStatement preparedStatement = xaConnection.prepareStatement(sql, autoGeneratedKeys); return (PreparedStatement) XAStatementProxy.newInstance(preparedStatement, this); } @Override public PreparedStatement prepareStatement(String sql, int[] columnIndexes) throws SQLException { checkIfValid(); jtaPreInvoke(); PreparedStatement preparedStatement = xaConnection.prepareStatement(sql, columnIndexes); return (PreparedStatement) XAStatementProxy.newInstance(preparedStatement, this); } @Override public PreparedStatement prepareStatement(String sql, String[] columnNames) throws SQLException { checkIfValid(); jtaPreInvoke(); PreparedStatement preparedStatement = xaConnection.prepareStatement(sql, columnNames); return (PreparedStatement) XAStatementProxy.newInstance(preparedStatement, this); } @Override public Clob createClob() throws SQLException { checkIfValid(); jtaPreInvoke(); return xaConnection.createClob(); } @Override public Blob createBlob() throws SQLException { checkIfValid(); jtaPreInvoke(); return xaConnection.createBlob(); } @Override public NClob createNClob() throws SQLException { checkIfValid(); jtaPreInvoke(); return xaConnection.createNClob(); } @Override public SQLXML createSQLXML() throws SQLException { checkIfValid(); jtaPreInvoke(); return xaConnection.createSQLXML(); } @Override public boolean isValid(int timeout) throws SQLException { checkIfValid(); jtaPreInvoke(); return xaConnection.isValid(timeout); } @Override public void setClientInfo(String name, String value) throws SQLClientInfoException { try { checkIfValid(); jtaPreInvoke(); xaConnection.setClientInfo(name, value); } catch (SQLException e) { throw new SQLClientInfoException(Collections.emptyMap(), e); } } @Override public String getClientInfo(String name) throws SQLException { checkIfValid(); jtaPreInvoke(); return xaConnection.getClientInfo(name); } @Override public Properties getClientInfo() throws SQLException { checkIfValid(); jtaPreInvoke(); return xaConnection.getClientInfo(); } @Override public void setClientInfo(Properties properties) throws SQLClientInfoException { try { checkIfValid(); jtaPreInvoke(); xaConnection.setClientInfo(properties); } catch (SQLException e) { throw new SQLClientInfoException(Collections.emptyMap(), e); } } @Override public Array createArrayOf(String typeName, Object[] elements) throws SQLException { checkIfValid(); jtaPreInvoke(); return xaConnection.createArrayOf(typeName, elements); } @Override public Struct createStruct(String typeName, Object[] attributes) throws SQLException { checkIfValid(); jtaPreInvoke(); return xaConnection.createStruct(typeName, attributes); } @Override public String getSchema() throws SQLException { checkIfValid(); jtaPreInvoke(); return xaConnection.getSchema(); } @Override public void setSchema(String schema) throws SQLException { checkIfValid(); jtaPreInvoke(); xaConnection.setSchema(schema); } @Override public void abort(Executor executor) throws SQLException { checkIfValid(); jtaPreInvoke(); xaConnection.abort(executor); } @Override public void setNetworkTimeout(Executor executor, int milliseconds) throws SQLException { checkIfValid(); jtaPreInvoke(); xaConnection.setNetworkTimeout(executor, milliseconds); } @Override public int getNetworkTimeout() throws SQLException { checkIfValid(); jtaPreInvoke(); return xaConnection.getNetworkTimeout(); } @Override public T unwrap(Class iface) throws SQLException { checkIfValid(); jtaPreInvoke(); return xaConnection.unwrap(iface); } @Override public boolean isWrapperFor(Class iface) throws SQLException { checkIfValid(); jtaPreInvoke(); return xaConnection.isWrapperFor(iface); } private void checkIfValid() throws SQLException { if (isClosed) throw new SQLException("The connection is closed"); if (xaConnection == null) throw new SQLException("The connection is invalid"); } private void jtaPreInvoke() throws SQLException { if (isEnlistedInJTA) return; try { if (transactionManager == null) { transactionManager = JtaProvider.getInstance().getTransactionManager(); } if (TxUtils.isActive(transactionManager)) { transactionManager.getTransaction().enlistResource(xaResource); transactionManager.getTransaction().registerSynchronization(new Synchronization() { @Override public void beforeCompletion() { } @Override public void afterCompletion(int status) { JtaXAConnectionWrapper jtaXaConnectionWrapper = JtaXAConnectionWrapper.this; jtaXaConnectionWrapper.isEnlistedInJTA = false; if (jtaXaConnectionWrapper.closeAfterTransactionEnd && jtaXaConnectionWrapper.xaConnection != null) { try { closeConnections(jtaXaConnectionWrapper); } catch (SQLException e) { log.severe("There was an error closing the connection after transaction complete"); } } } }); this.isEnlistedInJTA = true; } } catch (SystemException | RollbackException e) { throw new SQLException(e); } } private static void closeConnections(JtaXAConnectionWrapper jtaXaConnectionWrapper) throws SQLException { if (jtaXaConnectionWrapper.xaConnection != null) { jtaXaConnectionWrapper.xaConnection.close(); jtaXaConnectionWrapper.xaConnection = null; } if (jtaXaConnectionWrapper.parentConnection != null) { jtaXaConnectionWrapper.parentConnection.close(); jtaXaConnectionWrapper.parentConnection = null; } } } ================================================ FILE: components/jta/common/src/main/java/com/kumuluz/ee/jta/common/datasources/JtaXADataSourceWrapper.java ================================================ /* * Copyright (c) 2014-2017 Kumuluz and/or its affiliates * and other contributors as indicated by the @author tags and * the contributor list. * * Licensed under the MIT License (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://opensource.org/licenses/MIT * * The software is provided "AS IS", WITHOUT WARRANTY OF ANY KIND, express or * implied, including but not limited to the warranties of merchantability, * fitness for a particular purpose and noninfringement. in no event shall the * authors or copyright holders be liable for any claim, damages or other * liability, whether in an action of contract, tort or otherwise, arising from, * out of or in connection with the software or the use or other dealings in the * software. See the License for the specific language governing permissions and * limitations under the License. */ package com.kumuluz.ee.jta.common.datasources; import com.kumuluz.ee.common.datasources.NonJtaXADataSourceWrapper; import javax.sql.XAConnection; import javax.sql.XADataSource; import java.sql.Connection; import java.sql.SQLException; /** * @author Tilen Faganel * @since 2.3.0 */ @Deprecated public class JtaXADataSourceWrapper extends NonJtaXADataSourceWrapper { public JtaXADataSourceWrapper(XADataSource xaDataSource) { super(xaDataSource); } @Override public Connection getConnection() throws SQLException { checkIfValid(); XAConnection xaConnection = xaDataSource.getXAConnection(); return new JtaXAConnectionWrapper(xaConnection); } @Override public Connection getConnection(String username, String password) throws SQLException { checkIfValid(); XAConnection xaConnection = xaDataSource.getXAConnection(username, password); return new JtaXAConnectionWrapper(xaConnection); } } ================================================ FILE: components/jta/common/src/main/java/com/kumuluz/ee/jta/common/datasources/XAStatementProxy.java ================================================ /* * Copyright (c) 2014-2017 Kumuluz and/or its affiliates * and other contributors as indicated by the @author tags and * the contributor list. * * Licensed under the MIT License (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://opensource.org/licenses/MIT * * The software is provided "AS IS", WITHOUT WARRANTY OF ANY KIND, express or * implied, including but not limited to the warranties of merchantability, * fitness for a particular purpose and noninfringement. in no event shall the * authors or copyright holders be liable for any claim, damages or other * liability, whether in an action of contract, tort or otherwise, arising from, * out of or in connection with the software or the use or other dealings in the * software. See the License for the specific language governing permissions and * limitations under the License. */ package com.kumuluz.ee.jta.common.datasources; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import java.sql.CallableStatement; import java.sql.PreparedStatement; import java.sql.SQLException; import java.sql.Statement; /** * @author Tilen Faganel * @since 2.3.0 */ @Deprecated public class XAStatementProxy implements InvocationHandler { private Statement statement; private JtaXAConnectionWrapper jtaXaConnectionWrapper; private XAStatementProxy(Statement statement, JtaXAConnectionWrapper jtaXaConnectionWrapper) { this.statement = statement; this.jtaXaConnectionWrapper = jtaXaConnectionWrapper; } public static Object newInstance(Statement statement, JtaXAConnectionWrapper jtaXaConnectionWrapper) { return Proxy.newProxyInstance(statement.getClass().getClassLoader(), new Class[]{Statement.class}, new XAStatementProxy(statement, jtaXaConnectionWrapper)); } public static Object newInstance(PreparedStatement statement, JtaXAConnectionWrapper jtaXaConnectionWrapper) { return Proxy.newProxyInstance(statement.getClass().getClassLoader(), new Class[]{PreparedStatement.class}, new XAStatementProxy(statement, jtaXaConnectionWrapper)); } public static Object newInstance(CallableStatement statement, JtaXAConnectionWrapper jtaXaConnectionWrapper) { return Proxy.newProxyInstance(statement.getClass().getClassLoader(), new Class[]{CallableStatement.class}, new XAStatementProxy(statement, jtaXaConnectionWrapper)); } @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { if (jtaXaConnectionWrapper.isClosed()) { throw new SQLException("The connection associated with this statement is closed"); } return method.invoke(statement, args); } } ================================================ FILE: components/jta/common/src/main/java/com/kumuluz/ee/jta/common/exceptions/CannotRetrieveTxException.java ================================================ /* * Copyright (c) 2014-2017 Kumuluz and/or its affiliates * and other contributors as indicated by the @author tags and * the contributor list. * * Licensed under the MIT License (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://opensource.org/licenses/MIT * * The software is provided "AS IS", WITHOUT WARRANTY OF ANY KIND, express or * implied, including but not limited to the warranties of merchantability, * fitness for a particular purpose and noninfringement. in no event shall the * authors or copyright holders be liable for any claim, damages or other * liability, whether in an action of contract, tort or otherwise, arising from, * out of or in connection with the software or the use or other dealings in the * software. See the License for the specific language governing permissions and * limitations under the License. */ package com.kumuluz.ee.jta.common.exceptions; /** * @author Tilen Faganel * @since 2.4.0 */ public class CannotRetrieveTxException extends IllegalStateException { public CannotRetrieveTxException(Throwable cause) { super("There was an error retrieving the current threads transaction.", cause); } } ================================================ FILE: components/jta/common/src/main/java/com/kumuluz/ee/jta/common/utils/TxUtils.java ================================================ /* * Copyright (c) 2014-2017 Kumuluz and/or its affiliates * and other contributors as indicated by the @author tags and * the contributor list. * * Licensed under the MIT License (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://opensource.org/licenses/MIT * * The software is provided "AS IS", WITHOUT WARRANTY OF ANY KIND, express or * implied, including but not limited to the warranties of merchantability, * fitness for a particular purpose and noninfringement. in no event shall the * authors or copyright holders be liable for any claim, damages or other * liability, whether in an action of contract, tort or otherwise, arising from, * out of or in connection with the software or the use or other dealings in the * software. See the License for the specific language governing permissions and * limitations under the License. */ package com.kumuluz.ee.jta.common.utils; import com.kumuluz.ee.jta.common.JtaProvider; import com.kumuluz.ee.jta.common.exceptions.CannotRetrieveTxException; import javax.transaction.SystemException; import javax.transaction.Transaction; import javax.transaction.TransactionManager; /** * @author Tilen Faganel * @since 2.4.0 */ public class TxUtils { public static Boolean isActive(TransactionManager transactionManager) { try { Transaction tx = transactionManager.getTransaction(); return tx != null && JtaProvider.TRANSACTION_ACTIVE_STATUS.contains(tx.getStatus()); } catch (SystemException e) { throw new CannotRetrieveTxException(e); } } } ================================================ FILE: components/jta/common/src/main/resources/META-INF/services/org.jboss.weld.bootstrap.api.Service ================================================ com.kumuluz.ee.jta.common.JtaTransactionServices ================================================ FILE: components/jta/narayana/pom.xml ================================================ kumuluzee-jta com.kumuluz.ee 4.2.0-SNAPSHOT 4.0.0 KumuluzEE JTA Narayana KumuluzEE JTA component implemented by Narayana kumuluzee-jta-narayana com.kumuluz.ee kumuluzee-jta-common org.jboss jboss-transaction-spi ${jboss-transaction-spi.version} org.jboss.spec.javax.transaction jboss-transaction-api_1.2_spec org.jboss.spec.javax.resource jboss-connector-api_1.7_spec org.jboss.narayana.jta narayana-jta ${narayana.version} org.jboss jboss-transaction-spi org.jboss.spec.javax.resource jboss-connector-api_1.7_spec io.agroal agroal-narayana ${agroal.version} ================================================ FILE: components/jta/narayana/src/main/java/com/kumuluz/ee/jta/narayana/JtaComponent.java ================================================ /* * Copyright (c) 2014-2017 Kumuluz and/or its affiliates * and other contributors as indicated by the @author tags and * the contributor list. * * Licensed under the MIT License (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://opensource.org/licenses/MIT * * The software is provided "AS IS", WITHOUT WARRANTY OF ANY KIND, express or * implied, including but not limited to the warranties of merchantability, * fitness for a particular purpose and noninfringement. in no event shall the * authors or copyright holders be liable for any claim, damages or other * liability, whether in an action of contract, tort or otherwise, arising from, * out of or in connection with the software or the use or other dealings in the * software. See the License for the specific language governing permissions and * limitations under the License. */ package com.kumuluz.ee.jta.narayana; import com.arjuna.ats.arjuna.common.arjPropertyManager; import com.arjuna.ats.jta.utils.JNDIManager; import com.kumuluz.ee.common.Component; import com.kumuluz.ee.common.ServletServer; import com.kumuluz.ee.common.config.EeConfig; import com.kumuluz.ee.common.dependencies.EeComponentDef; import com.kumuluz.ee.common.dependencies.EeComponentDependency; import com.kumuluz.ee.common.dependencies.EeComponentType; import com.kumuluz.ee.common.wrapper.KumuluzServerWrapper; import com.kumuluz.ee.jta.common.JtaProvider; import javax.naming.NamingException; import java.util.logging.Level; import java.util.logging.Logger; /** * @author Marcos Koch Salvador * @since 2.3.0 */ @EeComponentDef(name = "Narayana JTA", type = EeComponentType.JTA) @EeComponentDependency(value = EeComponentType.CDI) public class JtaComponent implements Component { private Logger log = Logger.getLogger(JtaComponent.class.getSimpleName()); @Override public void init(KumuluzServerWrapper server, EeConfig eeConfig) { if (server.getServer() instanceof ServletServer) { ((ServletServer) server.getServer()).registerTransactionManager(JtaProvider.getInstance().getUserTransaction()); } } @Override public void load() { log.info("Initiating Narayana JTA"); arjPropertyManager.getObjectStoreEnvironmentBean().setObjectStoreDir("ObjectStore"); try { JNDIManager.bindJTAImplementation(); } catch (NamingException e) { log.log(Level.WARNING, e.getMessage(), e); } } } ================================================ FILE: components/jta/narayana/src/main/java/com/kumuluz/ee/jta/narayana/NarayanaJtaProvider.java ================================================ /* * Copyright (c) 2014-2017 Kumuluz and/or its affiliates * and other contributors as indicated by the @author tags and * the contributor list. * * Licensed under the MIT License (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://opensource.org/licenses/MIT * * The software is provided "AS IS", WITHOUT WARRANTY OF ANY KIND, express or * implied, including but not limited to the warranties of merchantability, * fitness for a particular purpose and noninfringement. in no event shall the * authors or copyright holders be liable for any claim, damages or other * liability, whether in an action of contract, tort or otherwise, arising from, * out of or in connection with the software or the use or other dealings in the * software. See the License for the specific language governing permissions and * limitations under the License. */ package com.kumuluz.ee.jta.narayana; import com.arjuna.ats.jta.common.JTAEnvironmentBean; import com.arjuna.ats.jta.common.jtaPropertyManager; import com.kumuluz.ee.jta.common.JtaProvider; import io.agroal.api.transaction.TransactionIntegration; import io.agroal.narayana.NarayanaTransactionIntegration; import javax.transaction.*; import java.util.HashMap; import java.util.Map; /** * @author Marcos Koch Salvador * @since 2.3.0 */ public class NarayanaJtaProvider extends JtaProvider { private final JTAEnvironmentBean jtaEnvironment; private final Map transactionIntegrations; public NarayanaJtaProvider() { jtaEnvironment = jtaPropertyManager.getJTAEnvironmentBean(); transactionIntegrations = new HashMap<>(); } @Override public UserTransaction getUserTransaction() { return jtaEnvironment.getUserTransaction(); } @Override public TransactionManager getTransactionManager() { return jtaEnvironment.getTransactionManager(); } @Override public TransactionSynchronizationRegistry getTransactionSynchronizationRegistry() { return jtaEnvironment.getTransactionSynchronizationRegistry(); } @Override public TransactionIntegration getTransactionIntegration(String jndiName) { if (!transactionIntegrations.containsKey(jndiName)) { transactionIntegrations.put(jndiName, new NarayanaTransactionIntegration(getTransactionManager(), getTransactionSynchronizationRegistry(), jndiName)); } return transactionIntegrations.get(jndiName); } } ================================================ FILE: components/jta/narayana/src/main/resources/META-INF/services/com.kumuluz.ee.common.Component ================================================ com.kumuluz.ee.jta.narayana.JtaComponent ================================================ FILE: components/jta/narayana/src/main/resources/META-INF/services/com.kumuluz.ee.jta.common.JtaProvider ================================================ com.kumuluz.ee.jta.narayana.NarayanaJtaProvider ================================================ FILE: components/jta/pom.xml ================================================ kumuluzee-components com.kumuluz.ee 4.2.0-SNAPSHOT 4.0.0 pom common narayana KumuluzEE JTA KumuluzEE JTA component kumuluzee-jta ================================================ FILE: components/pom.xml ================================================ kumuluzee com.kumuluz.ee 4.2.0-SNAPSHOT 4.0.0 pom KumuluzEE Components KumuluzEE Java EE components that are independent of the underlying server. websocket jsp el cdi jax-rs jsf jpa json-p bean-validation jax-ws jta json-b javamail kumuluzee-components ================================================ FILE: components/websocket/jetty/pom.xml ================================================ kumuluzee-websocket com.kumuluz.ee 4.2.0-SNAPSHOT 4.0.0 KumuluzEE WebSocket Jetty KumuluzEE WebSocket server component for Jetty kumuluzee-websocket-jetty com.kumuluz.ee kumuluzee-common com.kumuluz.ee kumuluzee-servlet-jetty provided jakarta.websocket jakarta.websocket-api ${websocket.version} org.eclipse.jetty.websocket websocket-javax-server ${jetty.version} org.eclipse.jetty.websocket websocket-javax-client ${jetty.version} ================================================ FILE: components/websocket/jetty/src/main/java/com/kumuluz/ee/websocket/jetty/WebSocketComponent.java ================================================ /* * Copyright (c) 2014-2017 Kumuluz and/or its affiliates * and other contributors as indicated by the @author tags and * the contributor list. * * Licensed under the MIT License (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://opensource.org/licenses/MIT * * The software is provided "AS IS", WITHOUT WARRANTY OF ANY KIND, express or * implied, including but not limited to the warranties of merchantability, * fitness for a particular purpose and noninfringement. in no event shall the * authors or copyright holders be liable for any claim, damages or other * liability, whether in an action of contract, tort or otherwise, arising from, * out of or in connection with the software or the use or other dealings in the * software. See the License for the specific language governing permissions and * limitations under the License. */ package com.kumuluz.ee.websocket.jetty; import com.kumuluz.ee.common.Component; import com.kumuluz.ee.common.config.EeConfig; import com.kumuluz.ee.common.dependencies.*; import com.kumuluz.ee.common.wrapper.KumuluzServerWrapper; import java.util.logging.Logger; /** * @author Tilen Faganel * @since 2.0.0 */ @EeComponentDef(name = "Jetty", type = EeComponentType.WEBSOCKET) @EeComponentDependency(value = EeComponentType.SERVLET, implementations = {"Jetty"}) public class WebSocketComponent implements Component { private Logger log = Logger.getLogger(WebSocketComponent.class.getSimpleName()); @Override public void init(KumuluzServerWrapper server, EeConfig eeConfig) { } @Override public void load() { log.info("Initiating WebSocket for Jetty"); } } ================================================ FILE: components/websocket/jetty/src/main/resources/META-INF/services/com.kumuluz.ee.common.Component ================================================ com.kumuluz.ee.websocket.jetty.WebSocketComponent ================================================ FILE: components/websocket/pom.xml ================================================ kumuluzee-components com.kumuluz.ee 4.2.0-SNAPSHOT 4.0.0 pom KumuluzEE WebSocket KumuluzEE WebSocket server component jetty kumuluzee-websocket ================================================ FILE: core/pom.xml ================================================ kumuluzee com.kumuluz.ee 4.2.0-SNAPSHOT 4.0.0 KumuluzEE Core KumuluzEE core bootstrap implementation kumuluzee-core com.kumuluz.ee kumuluzee-common com.kumuluz.ee kumuluzee-jta-common provided junit junit test ================================================ FILE: core/src/main/java/com/kumuluz/ee/EeApplication.java ================================================ /* * Copyright (c) 2014-2017 Kumuluz and/or its affiliates * and other contributors as indicated by the @author tags and * the contributor list. * * Licensed under the MIT License (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://opensource.org/licenses/MIT * * The software is provided "AS IS", WITHOUT WARRANTY OF ANY KIND, express or * implied, including but not limited to the warranties of merchantability, * fitness for a particular purpose and noninfringement. in no event shall the * authors or copyright holders be liable for any claim, damages or other * liability, whether in an action of contract, tort or otherwise, arising from, * out of or in connection with the software or the use or other dealings in the * software. See the License for the specific language governing permissions and * limitations under the License. */ package com.kumuluz.ee; import com.kumuluz.ee.common.*; import com.kumuluz.ee.common.config.EeConfig; import com.kumuluz.ee.common.dependencies.*; import com.kumuluz.ee.common.exceptions.KumuluzServerException; import com.kumuluz.ee.common.filters.PoweredByFilter; import com.kumuluz.ee.common.runtime.EeRuntime; import com.kumuluz.ee.common.runtime.EeRuntimeComponent; import com.kumuluz.ee.common.runtime.EeRuntimeExtension; import com.kumuluz.ee.common.runtime.EeRuntimeInternal; import com.kumuluz.ee.common.utils.ResourceUtils; import com.kumuluz.ee.common.wrapper.ComponentWrapper; import com.kumuluz.ee.common.wrapper.EeComponentWrapper; import com.kumuluz.ee.common.wrapper.ExtensionWrapper; import com.kumuluz.ee.common.wrapper.KumuluzServerWrapper; import com.kumuluz.ee.configuration.ConfigurationSource; import com.kumuluz.ee.configuration.utils.ConfigurationImpl; import com.kumuluz.ee.configuration.utils.ConfigurationUtil; import com.kumuluz.ee.factories.AgroalDataSourceFactory; import com.kumuluz.ee.factories.EeConfigFactory; import com.kumuluz.ee.loaders.*; import com.kumuluz.ee.logs.impl.JavaUtilDefaultLogConfigurator; import io.agroal.api.AgroalDataSource; import java.util.*; import java.util.logging.Handler; import java.util.logging.LogManager; import java.util.logging.Logger; import java.util.stream.Collectors; /** * @author Tilen Faganel * @since 1.0.0 */ public class EeApplication { private Logger log; private EeConfig eeConfig; private KumuluzServerWrapper server; public EeApplication() { initialize(); } public EeApplication(EeConfig eeConfig) { this.eeConfig = eeConfig; initialize(); } public static void main(String args[]) { EeApplication app = new EeApplication(); } public KumuluzServer getServer() { return this.server.getServer(); } private void initialize() { // Loading the logs extension and set up logging bridges before any actual logging is done Optional logsExtensionOptional = LogsExtensionLoader.loadExtension(); LogsExtension logsExtension = null; if (logsExtensionOptional.isPresent()) { logsExtension = logsExtensionOptional.get(); Optional> logManager = logsExtension.getJavaUtilLogManagerClass(); Optional logHandler = logsExtension.getJavaUtilLogHandler(); if (logManager.isPresent()) { System.setProperty("java.util.logging.manager", logManager.get().getName()); } else { logHandler.ifPresent(JavaUtilDefaultLogConfigurator::initSoleHandler); } } else { JavaUtilDefaultLogConfigurator.init(); } // Initialize the configuration ConfigurationImpl configImpl = new ConfigurationImpl(); ConfigurationUtil.initialize(configImpl); // we need to order config sources here in order to ensure correct initialisation of EeConfig configImpl.getConfigurationSources().sort(Comparator.comparingInt(ConfigurationSource::getOrdinal).reversed()); // initialize config profiles String[] configurationProfiles = ConfigurationUtil.getInstance().get("kumuluzee.config.profile") .or(() -> ConfigurationUtil.getInstance().get("mp.config.profile")) .map(s -> s.split(",")) .orElse(new String[0]); Arrays.stream(configurationProfiles) .forEach(profile -> configImpl.getConfigurationSources().forEach(cs -> cs.initProfile(profile))); if (this.eeConfig == null) { this.eeConfig = EeConfigFactory.buildEeConfig(); } else if (!EeConfigFactory.isEeConfigValid(this.eeConfig)) { throw new KumuluzServerException("The programmatically supplied EeConfig is malformed." + "Please check the supplied values and the config reference to fix the missing or invalid values."); } EeConfig.initialize(this.eeConfig); // We first set java.util.logging.manager by extension detection and only load the extension // after configuration sources have been initialized. This is because the property must be set // before any calls are made to LogManager or Logger. Some of the external configuration libraries // can and do in fact call the methods so this reorder is necessary. if (logsExtension!=null) { logsExtension.load(); } // Create the main class logger log = Logger.getLogger(EeApplication.class.getSimpleName()); // Signal the configuration impl that logging is up and running configImpl.postInit(); for (ConfigurationSource configurationSource : configImpl.getConfigurationSources()) { log.info("Initialized configuration source: " + configurationSource.getClass().getSimpleName()); } log.info("Initializing KumuluzEE"); log.info("Checking for requirements"); checkRequirements(); log.info("Checks passed"); log.info("Initialized main configuration"); log.info("Loading available EE components and extensions"); // Loading the kumuluz server and extracting its metadata KumuluzServer kumuluzServer = ServerLoader.loadServletServer(); processKumuluzServer(kumuluzServer); // Loading all the present components, extracting their metadata and process dependencies List components = ComponentLoader.loadComponents(); List eeComponents = processEeComponents(components); // Loading the config extensions and extracting its metadata List configExtensions = ConfigExtensionLoader.loadExtensions(); List> eeConfigExtensions = processSingleEeExtensions(configExtensions, eeComponents); List logsExtensions = logsExtensionOptional.map(Collections::singletonList).orElseGet(Collections::emptyList); List> eeLogsExtensions = processGroupEeExtensions(logsExtensions, eeComponents); // Loading the extensions and extracting its metadata List extensions = ExtensionLoader.loadExtensions(); List> eeExtensions = processGroupEeExtensions(extensions, eeComponents); log.info("EE Components and extensions loaded"); log.info("Initializing the KumuluzEE runtime"); EeRuntimeInternal eeRuntimeInternal = new EeRuntimeInternal(); List eeRuntimeComponents = eeComponents.stream() .map(e -> new EeRuntimeComponent(e.getType(), e.getName())) .collect(Collectors.toList()); List serverEeRuntimeComponents = Arrays.stream(server.getProvidedEeComponents()) .map(c -> new EeRuntimeComponent(c, server.getName())) .collect(Collectors.toList()); serverEeRuntimeComponents.addAll(eeRuntimeComponents); eeRuntimeInternal.setEeComponents(serverEeRuntimeComponents); List eeRuntimeExtensions = eeExtensions.stream() .map(e -> new EeRuntimeExtension(e.getGroup(), e.getName())).collect(Collectors.toList()); eeRuntimeExtensions.addAll(eeConfigExtensions.stream() .map(e -> new EeRuntimeExtension(e.getGroup(), e.getName())).collect(Collectors.toList())); eeRuntimeExtensions.addAll(eeLogsExtensions.stream() .map(e -> new EeRuntimeExtension(e.getGroup(), e.getName())).collect(Collectors.toList())); eeRuntimeInternal.setEeExtensions(eeRuntimeExtensions); EeRuntime.initialize(eeRuntimeInternal); log.info("Initialized the KumuluzEE runtime"); // Initiate the config extensions log.info("Initializing config extensions"); for (ExtensionWrapper extension : eeConfigExtensions) { log.info("Found config extension implemented by " + extension.getName()); if (extension.getExtension().isEnabled()) { extension.getExtension().load(); extension.getExtension().init(server, eeConfig); List sources = extension.getExtension().getConfigurationSources(); if (sources == null || sources.size() == 0) { //noinspection deprecation sources = Collections.singletonList(extension.getExtension().getConfigurationSource()); } for (ConfigurationSource source : sources) { if (source != null) { source.init(configImpl.getDispatcher()); configImpl.getConfigurationSources().add(source); } } } else { log.info("Config extension " + extension.getName() + " won't be initialized because it's disabled."); } } // sort the configuration sources again since new sources could be added by extensions configImpl.getConfigurationSources().sort(Comparator.comparingInt(ConfigurationSource::getOrdinal).reversed()); log.info("Config extensions initialized"); for (ExtensionWrapper extension : eeLogsExtensions) { log.info("Found logs extension implemented by " + extension.getName()); extension.getExtension().init(server, eeConfig); } // Initiate the server server.getServer().setServerConfig(eeConfig.getServer()); server.getServer().initServer(); // Depending on the server type, initiate server specific functionality if (server.getServer() instanceof ServletServer) { ServletServer servletServer = (ServletServer) server.getServer(); List allExtensions = new ArrayList<>(); allExtensions.addAll(eeExtensions.stream().map(ExtensionWrapper::getExtension) .collect(Collectors.toList())); allExtensions.addAll(eeConfigExtensions.stream().map(ExtensionWrapper::getExtension) .collect(Collectors.toList())); allExtensions.addAll(eeLogsExtensions.stream().map(ExtensionWrapper::getExtension) .collect(Collectors.toList())); servletServer.initWebContext(collectScanLibraries(allExtensions)); // Create and register datasources to the underlying server boolean jtaPresent = eeRuntimeInternal.getEeComponents().stream().anyMatch(c -> c.getType().equals(EeComponentType.JTA)); eeConfig.getDatasources().forEach(dsc -> { AgroalDataSource ds = AgroalDataSourceFactory.createDataSource(dsc, jtaPresent); servletServer.registerDataSource(ds, dsc.getJndiName()); }); eeConfig.getXaDatasources().forEach(xdsc -> { AgroalDataSource xds = AgroalDataSourceFactory.createXaDataSource(xdsc, jtaPresent); servletServer.registerDataSource(xds, xdsc.getJndiName()); }); // Add the server info headers if (eeConfig.getServer().getShowServerInfo()) { Map filterParams = new HashMap<>(); filterParams.put("name", "KumuluzEE/" + eeRuntimeInternal.getVersion()); servletServer.registerFilter(PoweredByFilter.class, "/*", filterParams); } } log.info("Initializing components"); // Initiate every found component in the order specified by the components dependencies for (EeComponentWrapper cw : eeComponents) { log.info("Found EE component " + cw.getType().getName() + " implemented by " + cw.getName()); cw.getComponent().init(server, eeConfig); cw.getComponent().load(); } log.info("Components initialized"); // Initiate the other extensions log.info("Initializing extensions"); for (ExtensionWrapper extension : eeExtensions) { log.info("Found extension implemented by " + extension.getName()); if (extension.getExtension().isEnabled()) { extension.getExtension().load(); extension.getExtension().init(server, eeConfig); } else { log.info("Extension " + extension.getName() + " won't be initialized because it's disabled."); } } log.info("Extensions Initialized"); server.getServer().startServer(); log.info("KumuluzEE started successfully"); } private List collectScanLibraries(List extensions) { Set scanLibraries = new HashSet<>(); extensions.stream().filter(Extension::isEnabled).forEach(e -> scanLibraries.addAll(e.scanLibraries())); return new ArrayList<>(scanLibraries); } private void processKumuluzServer(KumuluzServer kumuluzServer) { ServerDef serverDef = kumuluzServer.getClass().getDeclaredAnnotation(ServerDef.class); server = new KumuluzServerWrapper(kumuluzServer, serverDef.value(), serverDef.provides()); } private List processEeComponents(List components) { Map eeComp = new HashMap<>(); // Wrap components with their metadata and check for duplicates for (Component c : components) { EeComponentDef def = c.getClass().getDeclaredAnnotation(EeComponentDef.class); if (def != null) { if (eeComp.containsKey(def.type()) || Arrays.asList(server.getProvidedEeComponents()).contains(def.type())) { String msg = "Found multiple implementations (" + (eeComp.get(def.type()) != null ? eeComp.get(def.type()).getName() : server.getName()) + ", " + def.name() + ") of the same EE component (" + def.type().getName() + "). " + "Please check to make sure you only include a single implementation of a specific " + "EE component."; log.severe(msg); throw new KumuluzServerException(msg); } EeComponentDependency[] dependencies = c.getClass().getDeclaredAnnotationsByType (EeComponentDependency.class); EeComponentOptional[] optionals = c.getClass().getDeclaredAnnotationsByType(EeComponentOptional.class); eeComp.put(def.type(), new EeComponentWrapper(c, def.name(), def.type(), dependencies, optionals)); } } log.info("Processing EE component dependencies"); // Check if all dependencies are fulfilled for (EeComponentWrapper cmp : eeComp.values()) { for (EeComponentDependency dep : cmp.getDependencies()) { String depCompName = null; ComponentWrapper depComp = eeComp.get(dep.value()); // Check all posible locations for the dependency (Components and Server) if (depComp != null) { depCompName = depComp.getName(); } else if (Arrays.asList(server.getProvidedEeComponents()).contains(dep.value())) { depCompName = server.getName(); } if (depCompName == null) { String msg = "EE component dependency unfulfilled. The EE component " + cmp.getType().getName() + " implemented by " + cmp.getName() + " requires " + dep.value().getName() + ", which was " + "not " + "found. Please make sure to include the required component."; log.severe(msg); throw new KumuluzServerException(msg); } if (dep.implementations().length > 0 && !Arrays.asList(dep.implementations()).contains(depCompName)) { String msg = "EE component implementation dependency unfulfilled. The EE component " + cmp.getType().getName() + " implemented by " + cmp.getName() + " requires " + dep.value() .getName() + " implemented by one of the following implementations: " + Arrays.toString(dep.implementations()) + ". Please make sure you use one of the " + "implementations required by this component."; log.severe(msg); throw new KumuluzServerException(msg); } } // Check if all optional dependencies and their implementations are fulfilled for (EeComponentOptional dep : cmp.getOptionalDependencies()) { String depCompName = null; ComponentWrapper depComp = eeComp.get(dep.value()); // Check all posible locations for the dependency (Components and Server) if (depComp != null) { depCompName = depComp.getName(); } else if (!Arrays.asList(server.getProvidedEeComponents()).contains(dep.value())) { depCompName = server.getName(); } if (depCompName != null && dep.implementations().length > 0 && !Arrays.asList(dep.implementations()).contains(depCompName)) { String msg = "EE component optional implementation dependency unfulfilled. The EE component " + cmp.getType().getName() + " implemented by " + cmp.getName() + " requires " + dep.value() .getName() + " implemented by one of the following implementations: " + Arrays.toString(dep.implementations()) + ". Please make sure you use one of the " + "implementations required by this component."; log.severe(msg); throw new KumuluzServerException(msg); } } } return new ArrayList<>(eeComp.values()); } private List> processGroupEeExtensions(List extensions, List wrappedComponents) { Map> eeExt = new HashMap<>(); // Wrap extensions with their metadata and check for duplicates for (E e : extensions) { EeExtensionDef def = e.getClass().getDeclaredAnnotation(EeExtensionDef.class); if (def != null) { if (eeExt.containsKey(def.group())) { String msg = "Found multiple implementations (" + eeExt.get(def.group()).getName() + ", " + def.name() + ") of the same EE extension group (" + def.group() + "). " + "Please check to make sure you only include a single implementation of a specific " + "EE extension group."; log.severe(msg); throw new KumuluzServerException(msg); } EeComponentDependency[] dependencies = e.getClass().getDeclaredAnnotationsByType (EeComponentDependency.class); EeComponentOptional[] optionals = e.getClass().getDeclaredAnnotationsByType(EeComponentOptional.class); eeExt.put(def.group(), new ExtensionWrapper<>(e, def.name(), def.group(), dependencies, optionals)); } } List> extensionWrappers = new ArrayList<>(eeExt.values()); log.info("Processing EE extension dependencies"); processEeExtensionDependencies(extensionWrappers, wrappedComponents); return extensionWrappers; } private List> processSingleEeExtensions(List extensions, List wrappedComponents) { List> extensionWrappers = new ArrayList<>(); for (E e : extensions) { EeExtensionDef def = e.getClass().getDeclaredAnnotation(EeExtensionDef.class); if (def != null) { EeComponentDependency[] dependencies = e.getClass().getDeclaredAnnotationsByType(EeComponentDependency.class); EeComponentOptional[] optionals = e.getClass().getDeclaredAnnotationsByType(EeComponentOptional.class); extensionWrappers.add(new ExtensionWrapper<>(e, def.name(), def.group(), dependencies, optionals)); } } log.info("Processing EE single extensions dependencies"); processEeExtensionDependencies(extensionWrappers, wrappedComponents); return extensionWrappers; } private void processEeExtensionDependencies(List> extensions, List components) { // Check if all dependencies are fulfilled for (ExtensionWrapper ext : extensions) { for (EeComponentDependency dep : ext.getDependencies()) { Optional depComp = components.stream() .filter(c -> c.getType().equals(dep.value())).findFirst(); String depCompName = null; if (depComp.isPresent()) { depCompName = depComp.get().getName(); } else if (Arrays.asList(server.getProvidedEeComponents()).contains(dep.value())) { depCompName = server.getName(); } if (depCompName == null) { String msg = "EE extension implementation dependency unfulfilled. The EE extension group " + ext.getGroup() + " implemented by " + ext.getName() + " requires " + dep.value().getName() + " implemented by one of the following implementations: " + Arrays.toString(dep.implementations()) + ". Please make sure you use one of the " + "implementations required by this component."; log.severe(msg); throw new KumuluzServerException(msg); } if (dep.implementations().length > 0 && !Arrays.asList(dep.implementations()).contains(depCompName)) { String msg = "EE extension implementation dependency unfulfilled. The EE extension group " + ext.getGroup() + " implemented by " + ext.getName() + " requires component " + dep.value().getName() + " implemented by one of the following implementations: " + Arrays.toString(dep.implementations()) + ". Please make sure you use one of the " + "component implementations required by this component."; log.severe(msg); throw new KumuluzServerException(msg); } } // Check if all optional dependencies and their implementations are fulfilled for (EeComponentOptional dep : ext.getOptionalDependencies()) { Optional depComp = components.stream() .filter(c -> c.getType().equals(dep.value())).findFirst(); String depCompName = null; // Check all posible locations for the dependency (Components and Server) if (depComp.isPresent()) { depCompName = depComp.get().getName(); } else if (!Arrays.asList(server.getProvidedEeComponents()).contains(dep.value())) { depCompName = server.getName(); } if (depCompName != null && dep.implementations().length > 0 && !Arrays.asList(dep.implementations()).contains(depCompName)) { String msg = "EE extension optional implementation dependency unfulfilled. The EE extension group " + ext.getGroup() + " implemented by " + ext.getName() + " requires component " + dep.value().getName() + " implemented by one of the following implementations: " + Arrays.toString(dep.implementations()) + ". Please make sure you use one of the " + "component implementations required by this component."; log.severe(msg); throw new KumuluzServerException(msg); } } } } private void checkRequirements() { if (ResourceUtils.isRunningInJar()) { log.info("KumuluzEE running inside a JAR runtime."); } else { log.info("KumuluzEE running in an exploded class and dependency runtime."); } } } ================================================ FILE: core/src/main/java/com/kumuluz/ee/factories/AgroalDataSourceFactory.java ================================================ package com.kumuluz.ee.factories; import com.kumuluz.ee.common.config.DataSourceConfig; import com.kumuluz.ee.common.config.DataSourcePoolConfig; import com.kumuluz.ee.common.config.XaDataSourceConfig; import com.kumuluz.ee.common.exceptions.KumuluzServerException; import com.kumuluz.ee.common.utils.StringUtils; import com.kumuluz.ee.jta.common.JtaProvider; import io.agroal.api.AgroalDataSource; import io.agroal.api.configuration.AgroalConnectionFactoryConfiguration.TransactionIsolation; import io.agroal.api.configuration.AgroalConnectionPoolConfiguration; import io.agroal.api.configuration.AgroalDataSourceConfiguration.DataSourceImplementation; import io.agroal.api.configuration.supplier.AgroalConnectionFactoryConfigurationSupplier; import io.agroal.api.configuration.supplier.AgroalConnectionPoolConfigurationSupplier; import io.agroal.api.configuration.supplier.AgroalDataSourceConfigurationSupplier; import io.agroal.api.security.NamePrincipal; import io.agroal.api.security.SimplePassword; import java.sql.Connection; import java.sql.SQLException; import java.sql.Statement; import java.time.Duration; import java.util.Arrays; import java.util.Optional; import java.util.logging.Level; import java.util.logging.Logger; import java.util.stream.Collectors; /** * @author Marcos Koch Salvador * @since 3.7.0 */ public class AgroalDataSourceFactory { private static final Logger log = Logger.getLogger(AgroalDataSourceFactory.class.getSimpleName()); public static AgroalDataSource createDataSource(DataSourceConfig dsc, boolean jtaPresent) { AgroalDataSourceConfigurationSupplier dataSourceConfig = new AgroalDataSourceConfigurationSupplier(); AgroalConnectionPoolConfigurationSupplier poolConfig = dataSourceConfig.connectionPoolConfiguration(); AgroalConnectionFactoryConfigurationSupplier connectionFactoryConfig = poolConfig.connectionFactoryConfiguration(); if (!jtaPresent) { dataSourceConfig.dataSourceImplementation(DataSourceImplementation.HIKARI); } else { poolConfig.transactionIntegration( JtaProvider.getInstance().getTransactionIntegration(dsc.getJndiName()) ); } if (!StringUtils.isNullOrEmpty( dsc.getDriverClass() )) { connectionFactoryConfig.connectionProviderClassName(dsc.getDriverClass()); } else if (!StringUtils.isNullOrEmpty( dsc.getDataSourceClass( ))) { connectionFactoryConfig.connectionProviderClassName(dsc.getDataSourceClass()); } if (!StringUtils.isNullOrEmpty( dsc.getConnectionUrl() )) { connectionFactoryConfig.jdbcUrl(dsc.getConnectionUrl()); } setDatabaseCredentials(connectionFactoryConfig, dsc.getUsername(), dsc.getPassword()); setConnectionPoolConfiguration(poolConfig, connectionFactoryConfig, dsc.getPool(), !jtaPresent); dsc.getProps().forEach(connectionFactoryConfig::jdbcProperty); try { return AgroalDataSource.from( dataSourceConfig ); } catch (SQLException e) { throw new KumuluzServerException("Failed to create DataSource", e); } } public static AgroalDataSource createXaDataSource(XaDataSourceConfig xdsc, boolean jtaPresent) { AgroalDataSourceConfigurationSupplier xaDataSourceConfig = new AgroalDataSourceConfigurationSupplier(); AgroalConnectionPoolConfigurationSupplier poolConfig = xaDataSourceConfig.connectionPoolConfiguration(); AgroalConnectionFactoryConfigurationSupplier connectionFactoryConfig = poolConfig.connectionFactoryConfiguration(); if (jtaPresent) { poolConfig.transactionIntegration( JtaProvider.getInstance().getTransactionIntegration(xdsc.getJndiName()) ); } if (!StringUtils.isNullOrEmpty( xdsc.getXaDatasourceClass() )) { connectionFactoryConfig.connectionProviderClassName( xdsc.getXaDatasourceClass() ); } setDatabaseCredentials(connectionFactoryConfig, xdsc.getUsername(), xdsc.getPassword()); setConnectionPoolConfiguration(poolConfig, connectionFactoryConfig, xdsc.getPool(), false); xdsc.getProps().forEach(connectionFactoryConfig::jdbcProperty); try { return AgroalDataSource.from( xaDataSourceConfig ); } catch (SQLException e) { throw new KumuluzServerException("Failed to create XaDataSource", e); } } private static void setDatabaseCredentials(AgroalConnectionFactoryConfigurationSupplier connectionFactory, String username, String password) { if (!StringUtils.isNullOrEmpty( username )) { connectionFactory.principal(new NamePrincipal( username )); } if (!StringUtils.isNullOrEmpty( password )) { connectionFactory.credential(new SimplePassword( password )); } } private static void setConnectionPoolConfiguration(AgroalConnectionPoolConfigurationSupplier pool, AgroalConnectionFactoryConfigurationSupplier connectionFactoryConfig, DataSourcePoolConfig dscp, boolean isHikariSelected) { Optional.ofNullable( dscp.getAutoCommit() ).ifPresent(connectionFactoryConfig::autoCommit); Optional.ofNullable( dscp.getFlushOnClose() ).ifPresent(v -> { warnMessageAgroalFeature("flushOnClose", isHikariSelected); pool.flushOnClose(v); }); Optional.ofNullable( dscp.getConnectionTimeout() ).map(Duration::ofMillis).ifPresent(pool::acquisitionTimeout); Optional.ofNullable( dscp.getIdleTimeout() ).map(Duration::ofMillis).ifPresent(pool::reapTimeout); Optional.ofNullable( dscp.getMaxLifetime() ).map(Duration::ofMillis).ifPresent(pool::maxLifetime); Optional.ofNullable( dscp.getInitialSize() ).ifPresent(v -> { warnMessageAgroalFeature("initialSize", isHikariSelected); pool.initialSize(v); }); Optional.ofNullable( dscp.getMinSize() ).ifPresent(v -> { warnMessageAgroalFeature("minSize", isHikariSelected); pool.minSize(v); }); Optional.ofNullable( dscp.getMaxSize() ).ifPresent(pool::maxSize); if (!StringUtils.isNullOrEmpty( dscp.getName() )) { // Unknown or non-existent configuration in Agroal warnMessageDepreciatedProperty("name"); } // Unknown or non-existent configuration in Agroal Optional.ofNullable( dscp.getInitializationFailTimeout() ).ifPresent(v -> warnMessageDepreciatedProperty("initializationFailTimeout") ); // Unknown or non-existent configuration in Agroal Optional.ofNullable( dscp.getIsolateInternalQueries() ).ifPresent(v -> warnMessageDepreciatedProperty("isolateInternalQueries") ); // Unknown or non-existent configuration in Agroal Optional.ofNullable( dscp.getAllowPoolSuspension() ).ifPresent(v -> warnMessageDepreciatedProperty("allowPoolSuspension") ); // Unknown or non-existent configuration in Agroal Optional.ofNullable( dscp.getReadOnly() ).ifPresent(v -> warnMessageDepreciatedProperty("readOnly") ); // Unknown or non-existent configuration in Agroal Optional.ofNullable( dscp.getRegisterMbeans() ).ifPresent(v -> warnMessageDepreciatedProperty("registerMbeans") ); Optional.ofNullable( dscp.getValidationTimeout() ).map(Duration::ofMillis).ifPresent(pool::validationTimeout); Optional.ofNullable( dscp.getLeakDetectionThreshold() ).map(Duration::ofMillis).ifPresent(pool::leakTimeout); Optional.ofNullable( dscp.getIdleValidationTimeout() ).map(Duration::ofMillis).ifPresent(v -> { warnMessageAgroalFeature("idleValidationTimeout", isHikariSelected); pool.idleValidationTimeout(v); }); // Unknown or non-existent configuration in Agroal Optional.ofNullable( dscp.getMinIdle() ).ifPresent(v -> warnMessageDepreciatedProperty("minIdle") ); if (dscp.getConnectionValidSql() != null) { String validationQuery = dscp.getConnectionValidSql(); pool.connectionValidator(new AgroalConnectionPoolConfiguration.ConnectionValidator() { @Override public boolean isValid(Connection connection) { try (Statement stmt = connection.createStatement()) { stmt.execute(validationQuery); return true; } catch (Exception e) { log.log(Level.WARNING, "Connection validation failed", e); } return false; } }); } else { pool.connectionValidator(AgroalConnectionPoolConfiguration.ConnectionValidator.defaultValidator()); } if (!StringUtils.isNullOrEmpty( dscp.getConnectionInitSql() )) { connectionFactoryConfig.initialSql(dscp.getConnectionInitSql()); } setJdbcTransactionIsolation(connectionFactoryConfig, dscp.getTransactionIsolation()); } private static void setJdbcTransactionIsolation(AgroalConnectionFactoryConfigurationSupplier connectionFactory, String transactionIsolation) { if (!StringUtils.isNullOrEmpty( transactionIsolation )) { boolean found = false; for (TransactionIsolation isolation : TransactionIsolation.values()) { final String isolationName = "TRANSACTION_" + isolation.name(); if (isolationName.equalsIgnoreCase(transactionIsolation)) { connectionFactory.jdbcTransactionIsolation(isolation); found = true; break; } } if (!found) { log.warning("Could not find transaction isolation level with name: " + transactionIsolation + ", possible values: " + Arrays.stream(TransactionIsolation.values()) .map(Enum::name) .map(n -> "TRANSACTION_" + n) .collect(Collectors.joining(", "))); } } } private static void warnMessageAgroalFeature(String propertyName, boolean isHikariSelected) { if (isHikariSelected) { log.log(Level.WARNING, "The property \"" + propertyName + "\" is exclusive to the Agroal Connection Pool, therefore it will not be recognized by HikariCP!"); } } private static void warnMessageDepreciatedProperty(String propertyName) { log.log(Level.WARNING, "Property \"" + propertyName + "\" is not supported by Agroal Connection Pool and will be removed soon!"); } } ================================================ FILE: core/src/main/java/com/kumuluz/ee/factories/EeConfigFactory.java ================================================ /* * Copyright (c) 2014-2017 Kumuluz and/or its affiliates * and other contributors as indicated by the @author tags and * the contributor list. * * Licensed under the MIT License (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://opensource.org/licenses/MIT * * The software is provided "AS IS", WITHOUT WARRANTY OF ANY KIND, express or * implied, including but not limited to the warranties of merchantability, * fitness for a particular purpose and noninfringement. in no event shall the * authors or copyright holders be liable for any claim, damages or other * liability, whether in an action of contract, tort or otherwise, arising from, * out of or in connection with the software or the use or other dealings in the * software. See the License for the specific language governing permissions and * limitations under the License. */ package com.kumuluz.ee.factories; import com.kumuluz.ee.common.config.*; import com.kumuluz.ee.common.utils.StringUtils; import com.kumuluz.ee.configuration.utils.ConfigurationUtil; import java.util.*; import java.util.stream.Collectors; import java.util.stream.Stream; /** * @author Tilen Faganel * @since 2.4.0 */ public class EeConfigFactory { // ordered by priority, first entry has the highest priority private static final List PORT_ENVIRONMENT_VARIABLE_NAMES = List.of( "PORT", "FUNCTIONS_CUSTOMHANDLER_PORT" ); public static EeConfig buildEeConfig() { ConfigurationUtil cfg = ConfigurationUtil.getInstance(); EeConfig.Builder eeConfigBuilder = new EeConfig.Builder(); Optional appName = cfg.get("kumuluzee.name"); Optional appVersion = cfg.get("kumuluzee.version"); Optional appDebug = cfg.getBoolean("kumuluzee.debug"); appName.ifPresent(eeConfigBuilder::name); appVersion.ifPresent(eeConfigBuilder::version); appDebug.ifPresent(eeConfigBuilder::debug); ServerConfig.Builder serverBuilder = new ServerConfig.Builder(); Optional> serverCfgOpt = cfg.getMapKeys("kumuluzee.server"); if (serverCfgOpt.isPresent()) { Optional baseUrl = cfg.get("kumuluzee.server.base-url"); Optional contextPath = cfg.get("kumuluzee.server.context-path"); Optional dirBrowsing = cfg.getBoolean("kumuluzee.server.dir-browsing"); Optional etags = cfg.getBoolean("kumuluzee.server.etags"); Optional minThreads = cfg.getInteger("kumuluzee.server.min-threads"); Optional maxThreads = cfg.getInteger("kumuluzee.server.max-threads"); Optional forceHttps = cfg.getBoolean("kumuluzee.server.force-https"); Optional showServerInfo = cfg.getBoolean("kumuluzee.server.show-server-info"); Optional forwardStartupException = cfg.getBoolean("kumuluzee.server.jetty.forward-startup-exception"); baseUrl.ifPresent(serverBuilder::baseUrl); contextPath.ifPresent(serverBuilder::contextPath); dirBrowsing.ifPresent(serverBuilder::dirBrowsing); etags.ifPresent(serverBuilder::etags); minThreads.ifPresent(serverBuilder::minThreads); maxThreads.ifPresent(serverBuilder::maxThreads); forceHttps.ifPresent(serverBuilder::forceHttps); showServerInfo.ifPresent(serverBuilder::showServerInfo); forwardStartupException.ifPresent(serverBuilder::forwardStartupException); } ServerConnectorConfig.Builder httpBuilder = createServerConnectorConfigBuilder("kumuluzee.server.http", ServerConnectorConfig.DEFAULT_HTTP_PORT); PORT_ENVIRONMENT_VARIABLE_NAMES.stream() .map(System::getenv) .filter(Objects::nonNull) .filter(s -> !s.isEmpty()) .map(Integer::parseInt) .findFirst() .ifPresent(httpBuilder::port); ServerConnectorConfig.Builder httpsBuilder = createServerConnectorConfigBuilder("kumuluzee.server.https", ServerConnectorConfig.DEFAULT_HTTPS_PORT); serverBuilder.http(httpBuilder); serverBuilder.https(httpsBuilder); GzipConfig.Builder gzipBuilder = createGzipConfigBuilder("kumuluzee.server.gzip"); serverBuilder.gzip(gzipBuilder); eeConfigBuilder.server(serverBuilder); Optional> envCfgOpt = cfg.getMapKeys("kumuluzee.env"); if (envCfgOpt.isPresent()) { EnvConfig.Builder envBuilder = new EnvConfig.Builder(); Optional envName = cfg.get("kumuluzee.env.name"); envName.ifPresent(envBuilder::name); eeConfigBuilder.env(envBuilder); } Optional> loaderCfgOpt = cfg.getMapKeys("kumuluzee.dev"); if (loaderCfgOpt.isPresent()) { DevConfig.Builder devBuilder = new DevConfig.Builder(); Optional webappDir = cfg.get("kumuluzee.dev.webapp-dir"); Optional runningTests = cfg.getBoolean("kumuluzee.dev.running-tests"); webappDir.ifPresent(devBuilder::webappDir); runningTests.ifPresent(devBuilder::runningTests); getConfigList("kumuluzee.dev.scan-libraries").ifPresent(devBuilder::scanLibraries); eeConfigBuilder.dev(devBuilder); } Optional dsSizeOpt = cfg.getListSize("kumuluzee.datasources"); if (dsSizeOpt.isPresent()) { for (int i = 0; i < dsSizeOpt.get(); i++) { DataSourceConfig.Builder dsc = new DataSourceConfig.Builder(); Optional jndiName = cfg.get("kumuluzee.datasources[" + i + "].jndi-name"); Optional driverClass = cfg.get("kumuluzee.datasources[" + i + "].driver-class"); Optional dataSourceClass = cfg.get("kumuluzee.datasources[" + i + "].datasource-class"); Optional conUrl = cfg.get("kumuluzee.datasources[" + i + "].connection-url"); Optional user = cfg.get("kumuluzee.datasources[" + i + "].username"); Optional pass = cfg.get("kumuluzee.datasources[" + i + "].password"); jndiName.ifPresent(dsc::jndiName); driverClass.ifPresent(dsc::driverClass); dataSourceClass.ifPresent(dsc::dataSourceClass); conUrl.ifPresent(dsc::connectionUrl); user.ifPresent(dsc::username); pass.ifPresent(dsc::password); Optional> pool = cfg.getMapKeys("kumuluzee.datasources[" + i + "].pool"); if (pool.isPresent()) { DataSourcePoolConfig.Builder dspc = new DataSourcePoolConfig.Builder(); Optional autoCommit = cfg.getBoolean("kumuluzee.datasources[" + i + "].pool.auto-commit"); Optional flushOnClose = cfg.getBoolean("kumuluzee.datasources[" + i + "].pool.flush-on-close"); Optional connectionTimeout = cfg.getLong("kumuluzee.datasources[" + i + "].pool.connection-timeout"); Optional idleTimeout = cfg.getLong("kumuluzee.datasources[" + i + "].pool.idle-timeout"); Optional maxLifetime = cfg.getLong("kumuluzee.datasources[" + i + "].pool.max-lifetime"); Optional minIdle = cfg.getInteger("kumuluzee.datasources[" + i + "].pool.min-idle"); Optional initialSize = cfg.getInteger("kumuluzee.datasources[" + i + "].pool.initial-size"); Optional minSize = cfg.getInteger("kumuluzee.datasources[" + i + "].pool.min-size"); Optional maxSize = cfg.getInteger("kumuluzee.datasources[" + i + "].pool.max-size"); Optional poolName = cfg.get("kumuluzee.datasources[" + i + "].pool.name"); Optional initializationFailTimeout = cfg.getLong("kumuluzee.datasources[" + i + "].pool" + ".initialization-fail-timeout"); Optional isolateInternalQueries = cfg.getBoolean("kumuluzee.datasources[" + i + "].pool" + ".isolate-internal-queries"); Optional allowPoolSuspension = cfg.getBoolean("kumuluzee.datasources[" + i + "].pool.allow-pool-suspension"); Optional readOnly = cfg.getBoolean("kumuluzee.datasources[" + i + "].pool.read-only"); Optional registerMbeans = cfg.getBoolean("kumuluzee.datasources[" + i + "].pool.register-mbeans"); Optional connectionInitSql = cfg.get("kumuluzee.datasources[" + i + "].pool.connection-init-sql"); Optional connectionValidSql = cfg.get("kumuluzee.datasources[" + i + "].pool.connection-valid-sql"); Optional transactionIsolation = cfg.get("kumuluzee.datasources[" + i + "].pool.transaction-isolation"); Optional validationTimeout = cfg.getLong("kumuluzee.datasources[" + i + "].pool.validation-timeout"); Optional leakDetectionThreshold = cfg.getLong("kumuluzee.datasources[" + i + "].pool.leak-detection-threshold"); Optional idleValidationTimeout = cfg.getLong("kumuluzee.datasources[" + i + "].pool.idle-validation-timeout"); autoCommit.ifPresent(dspc::autoCommit); flushOnClose.ifPresent(dspc::flushOnClose); connectionTimeout.ifPresent(dspc::connectionTimeout); idleTimeout.ifPresent(dspc::idleTimeout); maxLifetime.ifPresent(dspc::maxLifetime); minIdle.ifPresent(dspc::minIdle); initialSize.ifPresent(dspc::initialSize); minSize.ifPresent(dspc::minSize); maxSize.ifPresent(dspc::maxSize); poolName.ifPresent(dspc::name); initializationFailTimeout.ifPresent(dspc::initializationFailTimeout); isolateInternalQueries.ifPresent(dspc::isolateInternalQueries); allowPoolSuspension.ifPresent(dspc::allowPoolSuspension); readOnly.ifPresent(dspc::readOnly); registerMbeans.ifPresent(dspc::registerMbeans); connectionInitSql.ifPresent(dspc::connectionInitSql); connectionValidSql.ifPresent(dspc::connectionValidSql); transactionIsolation.ifPresent(dspc::transactionIsolation); validationTimeout.ifPresent(dspc::validationTimeout); leakDetectionThreshold.ifPresent(dspc::leakDetectionThreshold); idleValidationTimeout.ifPresent(dspc::idleValidationTimeout); dsc.pool(dspc); } Optional> props = cfg.getMapKeys("kumuluzee.datasources[" + i + "].props"); if (props.isPresent()) { for (String propName : props.get()) { Optional propValue = cfg.get("kumuluzee.datasources[" + i + "].props." + propName); propValue.ifPresent(v -> dsc.prop(StringUtils.hyphenCaseToCamelCase(propName), v)); } } eeConfigBuilder.datasource(dsc); } } Optional xDsSizeOpt = cfg.getListSize("kumuluzee.xa-datasources"); if (xDsSizeOpt.isPresent()) { for (int i = 0; i < xDsSizeOpt.get(); i++) { XaDataSourceConfig.Builder xdsc = new XaDataSourceConfig.Builder(); Optional jndiName = cfg.get("kumuluzee.xa-datasources[" + i + "].jndi-name"); Optional xaDatasourceClass = cfg.get("kumuluzee.xa-datasources[" + i + "].xa-datasource-class"); Optional user = cfg.get("kumuluzee.xa-datasources[" + i + "].username"); Optional pass = cfg.get("kumuluzee.xa-datasources[" + i + "].password"); jndiName.ifPresent(xdsc::jndiName); xaDatasourceClass.ifPresent(xdsc::xaDatasourceClass); user.ifPresent(xdsc::username); pass.ifPresent(xdsc::password); Optional> pool = cfg.getMapKeys("kumuluzee.xa-datasources[" + i + "].pool"); if (pool.isPresent()) { DataSourcePoolConfig.Builder dspc = new DataSourcePoolConfig.Builder(); Optional autoCommit = cfg.getBoolean("kumuluzee.xa-datasources[" + i + "].pool.auto-commit"); Optional flushOnClose = cfg.getBoolean("kumuluzee.xa-datasources[" + i + "].pool.flush-on-close"); Optional connectionTimeout = cfg.getLong("kumuluzee.xa-datasources[" + i + "].pool.connection-timeout"); Optional idleTimeout = cfg.getLong("kumuluzee.xa-datasources[" + i + "].pool.idle-timeout"); Optional maxLifetime = cfg.getLong("kumuluzee.xa-datasources[" + i + "].pool.max-lifetime"); Optional minIdle = cfg.getInteger("kumuluzee.xa-datasources[" + i + "].pool.min-idle"); Optional initialSize = cfg.getInteger("kumuluzee.xa-datasources[" + i + "].pool.initial-size"); Optional minSize = cfg.getInteger("kumuluzee.xa-datasources[" + i + "].pool.min-size"); Optional maxSize = cfg.getInteger("kumuluzee.xa-datasources[" + i + "].pool.max-size"); Optional poolName = cfg.get("kumuluzee.xa-datasources[" + i + "].pool.name"); Optional initializationFailTimeout = cfg.getLong("kumuluzee.xa-datasources[" + i + "].pool" + ".initialization-fail-timeout"); Optional isolateInternalQueries = cfg.getBoolean("kumuluzee.xa-datasources[" + i + "].pool" + ".isolate-internal-queries"); Optional allowPoolSuspension = cfg.getBoolean("kumuluzee.xa-datasources[" + i + "].pool.allow-pool-suspension"); Optional readOnly = cfg.getBoolean("kumuluzee.xa-datasources[" + i + "].pool.read-only"); Optional registerMbeans = cfg.getBoolean("kumuluzee.xa-datasources[" + i + "].pool.register-mbeans"); Optional connectionInitSql = cfg.get("kumuluzee.xa-datasources[" + i + "].pool.connection-init-sql"); Optional transactionIsolation = cfg.get("kumuluzee.xa-datasources[" + i + "].pool.transaction-isolation"); Optional validationTimeout = cfg.getLong("kumuluzee.xa-datasources[" + i + "].pool.validation-timeout"); Optional leakDetectionThreshold = cfg.getLong("kumuluzee.xa-datasources[" + i + "].pool.leak-detection-threshold"); Optional idleValidationTimeout = cfg.getLong("kumuluzee.xa-datasources[" + i + "].pool.idle-validation-timeout"); autoCommit.ifPresent(dspc::autoCommit); flushOnClose.ifPresent(dspc::flushOnClose); connectionTimeout.ifPresent(dspc::connectionTimeout); idleTimeout.ifPresent(dspc::idleTimeout); maxLifetime.ifPresent(dspc::maxLifetime); minIdle.ifPresent(dspc::minIdle); initialSize.ifPresent(dspc::initialSize); minSize.ifPresent(dspc::minSize); maxSize.ifPresent(dspc::maxSize); poolName.ifPresent(dspc::name); initializationFailTimeout.ifPresent(dspc::initializationFailTimeout); isolateInternalQueries.ifPresent(dspc::isolateInternalQueries); allowPoolSuspension.ifPresent(dspc::allowPoolSuspension); readOnly.ifPresent(dspc::readOnly); registerMbeans.ifPresent(dspc::registerMbeans); connectionInitSql.ifPresent(dspc::connectionInitSql); transactionIsolation.ifPresent(dspc::transactionIsolation); validationTimeout.ifPresent(dspc::validationTimeout); leakDetectionThreshold.ifPresent(dspc::leakDetectionThreshold); idleValidationTimeout.ifPresent(dspc::idleValidationTimeout); xdsc.pool(dspc); } Optional> props = cfg.getMapKeys("kumuluzee.xa-datasources[" + i + "].props"); if (props.isPresent()) { for (String propName : props.get()) { Optional propValue = cfg.get("kumuluzee.xa-datasources[" + i + "].props." + propName); propValue.ifPresent(v -> xdsc.prop(StringUtils.hyphenCaseToCamelCase(propName), v)); } } eeConfigBuilder.xaDatasource(xdsc); } } Optional mailSessionsSizeOpt = cfg.getListSize("kumuluzee.mail-sessions"); if (mailSessionsSizeOpt.isPresent()) { for (int i = 0; i < mailSessionsSizeOpt.get(); i++) { String prefix = "kumuluzee.mail-sessions[" + i + "]"; MailSessionConfig.Builder mscc = new MailSessionConfig.Builder(); Optional jndiName = cfg.get(prefix + ".jndi-name"); Optional debug = cfg.getBoolean(prefix + ".debug"); jndiName.ifPresent(mscc::jndiName); debug.ifPresent(mscc::debug); Optional> transport = cfg.getMapKeys(prefix + ".transport"); Optional> store = cfg.getMapKeys(prefix + ".store"); if (transport.isPresent()) { mscc.transport(createMailServiceConfigBuilder(prefix + ".transport")); } if (store.isPresent()) { mscc.store(createMailServiceConfigBuilder(prefix + ".store")); } Optional> props = cfg.getMapKeys(prefix + ".props"); if (props.isPresent()) { for (String propName : props.get()) { Optional propValue = cfg.get(prefix + ".props." + propName); propValue.ifPresent(v -> mscc.prop(propName, v)); } } eeConfigBuilder.mailSession(mscc); } } return eeConfigBuilder.build(); } public static Boolean isEeConfigValid(EeConfig eeConfig) { return !(eeConfig == null || eeConfig.getVersion() == null || eeConfig.getDebug() == null || eeConfig.getEnv() == null || eeConfig.getDev() == null || eeConfig.getServer() == null || eeConfig.getServer().getContextPath() == null || eeConfig.getServer().getForceHttps() == null || eeConfig.getServer().getMinThreads() == null || eeConfig.getServer().getMaxThreads() == null || eeConfig.getServer().getShowServerInfo() == null || eeConfig.getServer().getForwardStartupException() == null || eeConfig.getServer().getHttp() == null || eeConfig.getServer().getHttp().getHttp2() == null || eeConfig.getServer().getHttp().getProxyForwarding() == null || eeConfig.getServer().getHttp().getRequestHeaderSize() == null || eeConfig.getServer().getHttp().getResponseHeaderSize() == null || eeConfig.getServer().getHttp().getIdleTimeout() == null || (eeConfig.getServer().getHttps() != null && (eeConfig.getServer().getHttps().getHttp2() == null || eeConfig.getServer().getHttps().getProxyForwarding() == null || eeConfig.getServer().getHttps().getRequestHeaderSize() == null || eeConfig.getServer().getHttps().getResponseHeaderSize() == null || eeConfig.getServer().getHttps().getIdleTimeout() == null)) || eeConfig.getDatasources().stream().anyMatch(ds -> (ds == null || ds.getPool() == null || ds.getPool().getAutoCommit() == null || ds.getPool().getConnectionTimeout() == null || ds.getPool().getIdleTimeout() == null || ds.getPool().getMaxLifetime() == null || ds.getPool().getMaxSize() == null || ds.getPool().getValidationTimeout() == null || ds.getPool().getLeakDetectionThreshold() == null))); } private static ServerConnectorConfig.Builder createServerConnectorConfigBuilder(String prefix, Integer defaultPort) { ConfigurationUtil cfg = ConfigurationUtil.getInstance(); ServerConnectorConfig.Builder serverConnectorBuilder = new ServerConnectorConfig.Builder(); serverConnectorBuilder.port(defaultPort); Optional> serverConnectorCfgOpt = cfg.getMapKeys(prefix); if (serverConnectorCfgOpt.isPresent()) { Optional port = cfg.getInteger(prefix + ".port"); Optional address = cfg.get(prefix + ".address"); Optional enabled = cfg.getBoolean(prefix + ".enabled"); Optional http2 = cfg.getBoolean(prefix + ".http2"); Optional proxyForwarding = cfg.getBoolean(prefix + ".proxy-forwarding"); Optional requestHeaderSize = cfg.getInteger(prefix + ".request-header-size"); Optional responseHeaderSize = cfg.getInteger(prefix + ".response-header-size"); Optional idleTimeout = cfg.getInteger(prefix + ".idle-timeout"); Optional keystorePath = cfg.get(prefix + ".keystore-path"); Optional keystorePassword = cfg.get(prefix + ".keystore-password"); Optional keyAlias = cfg.get(prefix + ".key-alias"); Optional keyPassword = cfg.get(prefix + ".key-password"); Optional sslProtocols = cfg.get(prefix + ".ssl-protocols"); Optional sslCiphers = cfg.get(prefix + ".ssl-ciphers"); port.ifPresent(serverConnectorBuilder::port); address.ifPresent(serverConnectorBuilder::address); enabled.ifPresent(serverConnectorBuilder::enabled); http2.ifPresent(serverConnectorBuilder::http2); proxyForwarding.ifPresent(serverConnectorBuilder::proxyForwarding); requestHeaderSize.ifPresent(serverConnectorBuilder::requestHeaderSize); responseHeaderSize.ifPresent(serverConnectorBuilder::responseHeaderSize); idleTimeout.ifPresent(serverConnectorBuilder::idleTimeout); keystorePath.ifPresent(serverConnectorBuilder::keystorePath); keystorePassword.ifPresent(serverConnectorBuilder::keystorePassword); keyAlias.ifPresent(serverConnectorBuilder::keyAlias); keyPassword.ifPresent(serverConnectorBuilder::keyPassword); sslProtocols.ifPresent(p -> serverConnectorBuilder.sslProtocols(Stream.of(p.split(",")).map(String::trim).collect(Collectors .toList()))); sslCiphers.ifPresent(c -> serverConnectorBuilder.sslCiphers(Stream.of(c.split(",")).map(String::trim).collect(Collectors .toList()))); } return serverConnectorBuilder; } private static MailServiceConfig.Builder createMailServiceConfigBuilder(String prefix) { ConfigurationUtil cfg = ConfigurationUtil.getInstance(); MailServiceConfig.Builder mailServiceBuilder = new MailServiceConfig.Builder(); Optional protocol = cfg.get(prefix + ".protocol"); Optional host = cfg.get(prefix + ".host"); Optional port = cfg.getInteger(prefix + ".port"); Optional starttls = cfg.getBoolean(prefix + ".starttls"); Optional username = cfg.get(prefix + ".username"); Optional password = cfg.get(prefix + ".password"); Optional connectionTimeout = cfg.getLong(prefix + ".connection-timeout"); Optional timeout = cfg.getLong(prefix + ".timeout"); protocol.ifPresent(mailServiceBuilder::protocol); host.ifPresent(mailServiceBuilder::host); port.ifPresent(mailServiceBuilder::port); starttls.ifPresent(mailServiceBuilder::starttls); username.ifPresent(mailServiceBuilder::username); password.ifPresent(mailServiceBuilder::password); connectionTimeout.ifPresent(mailServiceBuilder::connectionTimeout); timeout.ifPresent(mailServiceBuilder::timeout); return mailServiceBuilder; } private static GzipConfig.Builder createGzipConfigBuilder(String prefix) { ConfigurationUtil cfg = ConfigurationUtil.getInstance(); GzipConfig.Builder gzipBuilder = new GzipConfig.Builder(); Optional enabled = cfg.getBoolean(prefix + ".enabled"); Optional minGzipSize = cfg.getInteger(prefix + ".min-gzip-size"); Optional> includedMethods = getConfigList(prefix + ".included-methods"); Optional> includedMimeTypes = getConfigList(prefix + ".included-mime-types"); Optional> excludedMimeTypes = getConfigList(prefix + ".excluded-mime-types"); Optional> excludedAgentPatterns = getConfigList(prefix + ".excluded-agent-patterns"); Optional> excludedPaths = getConfigList(prefix + ".excluded-paths"); Optional> includedPaths = getConfigList(prefix + ".included-paths"); enabled.ifPresent(gzipBuilder::enabled); minGzipSize.ifPresent(gzipBuilder::minGzipSize); includedMethods.ifPresent(gzipBuilder::includedMethods); includedMimeTypes.ifPresent(gzipBuilder::includedMimeTypes); excludedMimeTypes.ifPresent(gzipBuilder::excludedMimeTypes); excludedAgentPatterns.ifPresent(gzipBuilder::excludedAgentPatterns); excludedPaths.ifPresent(gzipBuilder::excludedPaths); includedPaths.ifPresent(gzipBuilder::includedPaths); return gzipBuilder; } private static Optional> getConfigList(String key) { ConfigurationUtil cfg = ConfigurationUtil.getInstance(); Optional listSize = cfg.getListSize(key); if (listSize.isPresent()) { List list = new ArrayList<>(); for (int i = 0; i < listSize.get(); i++) { Optional item = cfg.get(key + "[" + i + "]"); item.ifPresent(list::add); } if (list.size() > 0) { return Optional.of(Collections.unmodifiableList(list)); } } return Optional.empty(); } } ================================================ FILE: core/src/main/java/com/kumuluz/ee/factories/JtaXADataSourceFactory.java ================================================ /* * Copyright (c) 2014-2017 Kumuluz and/or its affiliates * and other contributors as indicated by the @author tags and * the contributor list. * * Licensed under the MIT License (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://opensource.org/licenses/MIT * * The software is provided "AS IS", WITHOUT WARRANTY OF ANY KIND, express or * implied, including but not limited to the warranties of merchantability, * fitness for a particular purpose and noninfringement. in no event shall the * authors or copyright holders be liable for any claim, damages or other * liability, whether in an action of contract, tort or otherwise, arising from, * out of or in connection with the software or the use or other dealings in the * software. See the License for the specific language governing permissions and * limitations under the License. */ package com.kumuluz.ee.factories; import com.kumuluz.ee.common.datasources.NonJtaXADataSourceWrapper; import com.kumuluz.ee.jta.common.datasources.JtaXADataSourceWrapper; import javax.sql.XADataSource; /** * @author Tilen Faganel * @since 2.3.0 */ @Deprecated public class JtaXADataSourceFactory { public static NonJtaXADataSourceWrapper buildJtaXADataSourceWrapper(XADataSource xaDataSource) { return new JtaXADataSourceWrapper(xaDataSource); } } ================================================ FILE: core/src/main/java/com/kumuluz/ee/loaders/ComponentLoader.java ================================================ /* * Copyright (c) 2014-2017 Kumuluz and/or its affiliates * and other contributors as indicated by the @author tags and * the contributor list. * * Licensed under the MIT License (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://opensource.org/licenses/MIT * * The software is provided "AS IS", WITHOUT WARRANTY OF ANY KIND, express or * implied, including but not limited to the warranties of merchantability, * fitness for a particular purpose and noninfringement. in no event shall the * authors or copyright holders be liable for any claim, damages or other * liability, whether in an action of contract, tort or otherwise, arising from, * out of or in connection with the software or the use or other dealings in the * software. See the License for the specific language governing permissions and * limitations under the License. */ package com.kumuluz.ee.loaders; import com.kumuluz.ee.common.Component; import com.kumuluz.ee.common.ServletServer; import com.kumuluz.ee.common.config.EeConfig; import com.kumuluz.ee.common.dependencies.EeComponentDef; import com.kumuluz.ee.common.exceptions.KumuluzServerException; import com.kumuluz.ee.common.wrapper.ComponentWrapper; import com.kumuluz.ee.common.wrapper.KumuluzServerWrapper; import java.lang.annotation.Annotation; import java.util.ArrayList; import java.util.List; import java.util.Objects; import java.util.ServiceLoader; import java.util.logging.Logger; import java.util.stream.Stream; /** * @author Tilen Faganel * @since 1.0.0 */ public class ComponentLoader { private static final Logger log = Logger.getLogger(ComponentLoader.class.getSimpleName()); private static final Class COMPONENT_ANNOTATIONS[] = { EeComponentDef.class }; public static List loadComponents() { log.info("Loading available components"); List components = scanForAvailableComponents(); for (Component c : components) { boolean anyMatch = Stream.of(COMPONENT_ANNOTATIONS) .map(a -> c.getClass().getDeclaredAnnotation(a)) .anyMatch(Objects::nonNull); if (!anyMatch) { String msg = "The found class \"" + c.getClass().getSimpleName() + "\" is missing a component" + "definition annotation. The annotation is required in order to correctly process the component" + "type and its dependencies."; log.severe(msg); throw new KumuluzServerException(msg); } } log.info("Loading for components complete"); return components; } private static List scanForAvailableComponents() { log.finest("Scanning for available components in the runtime"); List components = new ArrayList<>(); ServiceLoader.load(Component.class).forEach(components::add); return components; } } ================================================ FILE: core/src/main/java/com/kumuluz/ee/loaders/ConfigExtensionLoader.java ================================================ /* * Copyright (c) 2014-2017 Kumuluz and/or its affiliates * and other contributors as indicated by the @author tags and * the contributor list. * * Licensed under the MIT License (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://opensource.org/licenses/MIT * * The software is provided "AS IS", WITHOUT WARRANTY OF ANY KIND, express or * implied, including but not limited to the warranties of merchantability, * fitness for a particular purpose and noninfringement. in no event shall the * authors or copyright holders be liable for any claim, damages or other * liability, whether in an action of contract, tort or otherwise, arising from, * out of or in connection with the software or the use or other dealings in the * software. See the License for the specific language governing permissions and * limitations under the License. */ package com.kumuluz.ee.loaders; import com.kumuluz.ee.common.ConfigExtension; import com.kumuluz.ee.common.dependencies.EeExtensionDef; import com.kumuluz.ee.common.dependencies.EeExtensionGroup; import com.kumuluz.ee.common.exceptions.KumuluzServerException; import java.util.ArrayList; import java.util.List; import java.util.ServiceLoader; import java.util.logging.Logger; /** * @author Tilen Faganel * @since 2.3.0 */ public class ConfigExtensionLoader { private static final Logger log = Logger.getLogger(ConfigExtensionLoader.class.getSimpleName()); public static List loadExtensions() { log.info("Loading available config extensions"); List extensions = scanForAvailableExtensions(); for (ConfigExtension e : extensions) { EeExtensionDef eeExtensionDef = e.getClass().getDeclaredAnnotation(EeExtensionDef.class); if (eeExtensionDef == null) { String msg = "The found class \"" + e.getClass().getSimpleName() + "\" is missing an extension" + "definition annotation. The annotation is required in order to correctly process the " + "extension type and its dependencies."; log.severe(msg); throw new KumuluzServerException(msg); } if (!eeExtensionDef.group().equalsIgnoreCase(EeExtensionGroup.CONFIG)) { String msg = "The found class \"" + e.getClass().getSimpleName() + "\" does not have the correct " + "extension group defined. The interface \"ConfigExtension\" requires that the supporting " + " definition annotations specifies the extension group of \"config\". "; log.severe(msg); throw new KumuluzServerException(msg); } } log.info("Config extension loading complete"); return extensions; } private static List scanForAvailableExtensions() { List extensions = new ArrayList<>(); ServiceLoader.load(ConfigExtension.class).forEach(extensions::add); return extensions; } } ================================================ FILE: core/src/main/java/com/kumuluz/ee/loaders/ExtensionLoader.java ================================================ /* * Copyright (c) 2014-2017 Kumuluz and/or its affiliates * and other contributors as indicated by the @author tags and * the contributor list. * * Licensed under the MIT License (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://opensource.org/licenses/MIT * * The software is provided "AS IS", WITHOUT WARRANTY OF ANY KIND, express or * implied, including but not limited to the warranties of merchantability, * fitness for a particular purpose and noninfringement. in no event shall the * authors or copyright holders be liable for any claim, damages or other * liability, whether in an action of contract, tort or otherwise, arising from, * out of or in connection with the software or the use or other dealings in the * software. See the License for the specific language governing permissions and * limitations under the License. */ package com.kumuluz.ee.loaders; import com.kumuluz.ee.common.Extension; import com.kumuluz.ee.common.dependencies.EeExtensionDef; import com.kumuluz.ee.common.dependencies.EeExtensionGroup; import com.kumuluz.ee.common.exceptions.KumuluzServerException; import java.util.ArrayList; import java.util.List; import java.util.ServiceLoader; import java.util.logging.Logger; /** * @author Jan Meznarič * @since 2.3.0 */ public class ExtensionLoader { private static final Logger log = Logger.getLogger(ExtensionLoader.class.getSimpleName()); public static List loadExtensions() { log.info("Loading available extensions"); List extensions = scanForAvailableExtensions(); for (Extension e : extensions) { EeExtensionDef eeExtensionDef = e.getClass().getDeclaredAnnotation(EeExtensionDef.class); if (eeExtensionDef == null) { String msg = "The found class \"" + e.getClass().getSimpleName() + "\" is missing an extension" + "definition annotation. The annotation is required in order to correctly process the " + "extension type and its dependencies."; log.severe(msg); throw new KumuluzServerException(msg); } if (eeExtensionDef.group().equalsIgnoreCase(EeExtensionGroup.CONFIG)) { String msg = "The found class \"" + e.getClass().getSimpleName() + "\" does not have the correct " + "extension group defined. The extension group \"config\" requires that the class implements " + "the \"ConfigExtension\" interface."; log.severe(msg); throw new KumuluzServerException(msg); } else if (eeExtensionDef.group().equalsIgnoreCase(EeExtensionGroup.LOGS)) { String msg = "The found class \"" + e.getClass().getSimpleName() + "\" does not have the correct " + "extension group defined. The extension group \"logs\" requires that the class implements " + "the \"LogsExtension\" interface."; log.severe(msg); throw new KumuluzServerException(msg); } } log.info("Extension loading complete"); return extensions; } private static List scanForAvailableExtensions() { List extensions = new ArrayList<>(); ServiceLoader.load(Extension.class).forEach(extensions::add); return extensions; } } ================================================ FILE: core/src/main/java/com/kumuluz/ee/loaders/LogsExtensionLoader.java ================================================ /* * Copyright (c) 2014-2017 Kumuluz and/or its affiliates * and other contributors as indicated by the @author tags and * the contributor list. * * Licensed under the MIT License (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://opensource.org/licenses/MIT * * The software is provided "AS IS", WITHOUT WARRANTY OF ANY KIND, express or * implied, including but not limited to the warranties of merchantability, * fitness for a particular purpose and noninfringement. in no event shall the * authors or copyright holders be liable for any claim, damages or other * liability, whether in an action of contract, tort or otherwise, arising from, * out of or in connection with the software or the use or other dealings in the * software. See the License for the specific language governing permissions and * limitations under the License. */ package com.kumuluz.ee.loaders; import com.kumuluz.ee.common.LogsExtension; import com.kumuluz.ee.common.dependencies.EeExtensionDef; import com.kumuluz.ee.common.dependencies.EeExtensionGroup; import com.kumuluz.ee.common.exceptions.KumuluzServerException; import java.util.ArrayList; import java.util.List; import java.util.Optional; import java.util.ServiceLoader; import java.util.logging.Logger; /** * @author Tilen Faganel * @since 2.4.0 */ public class LogsExtensionLoader { public static Optional loadExtension() { List extensions = scanForAvailableExtensions(); if (extensions.size() > 1) { String implementations = extensions.stream().skip(1) .map(e -> e.getClass().getSimpleName()) .reduce(extensions.get(0).getClass().getSimpleName(), (s, e) -> ", " + e.getClass().getSimpleName()); Logger log = Logger.getLogger(LogsExtensionLoader.class.getSimpleName()); String msg = "Found multiple implementations (" + implementations + ") of the same EE extension group (logs). " + "Please check to make sure you only include a single implementation of a specific " + "EE extension group."; log.severe(msg); throw new KumuluzServerException(msg); } if (extensions.size() == 1) { LogsExtension logsExtension = extensions.get(0); EeExtensionDef eeExtensionDef = logsExtension.getClass().getDeclaredAnnotation(EeExtensionDef.class); if (eeExtensionDef == null) { String msg = "The found class \"" + logsExtension.getClass().getSimpleName() + "\" is missing an extension" + "definition annotation. The annotation is required in order to correctly process the " + "extension type and its dependencies."; Logger log = Logger.getLogger(LogsExtensionLoader.class.getSimpleName()); log.severe(msg); throw new KumuluzServerException(msg); } if (!eeExtensionDef.group().equalsIgnoreCase(EeExtensionGroup.LOGS)) { String msg = "The found class \"" + logsExtension.getClass().getSimpleName() + "\" does not have the correct " + "extension group defined. The interface \"LogsExtension\" requires that the supporting " + " definition annotations specifies the extension group of \"logs\". "; Logger log = Logger.getLogger(LogsExtensionLoader.class.getSimpleName()); log.severe(msg); throw new KumuluzServerException(msg); } return Optional.of(logsExtension); } return Optional.empty(); } private static List scanForAvailableExtensions() { List extensions = new ArrayList<>(); ServiceLoader.load(LogsExtension.class).forEach(extensions::add); return extensions; } } ================================================ FILE: core/src/main/java/com/kumuluz/ee/loaders/ServerLoader.java ================================================ /* * Copyright (c) 2014-2017 Kumuluz and/or its affiliates * and other contributors as indicated by the @author tags and * the contributor list. * * Licensed under the MIT License (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://opensource.org/licenses/MIT * * The software is provided "AS IS", WITHOUT WARRANTY OF ANY KIND, express or * implied, including but not limited to the warranties of merchantability, * fitness for a particular purpose and noninfringement. in no event shall the * authors or copyright holders be liable for any claim, damages or other * liability, whether in an action of contract, tort or otherwise, arising from, * out of or in connection with the software or the use or other dealings in the * software. See the License for the specific language governing permissions and * limitations under the License. */ package com.kumuluz.ee.loaders; import com.kumuluz.ee.common.KumuluzServer; import com.kumuluz.ee.common.dependencies.ServerDef; import com.kumuluz.ee.common.exceptions.KumuluzServerException; import com.kumuluz.ee.common.wrapper.KumuluzServerWrapper; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.ServiceLoader; import java.util.logging.Logger; /** * @author Tilen Faganel * @since 1.0.0 */ public class ServerLoader { private static Logger log = Logger.getLogger(ServerLoader.class.getSimpleName()); public static KumuluzServer loadServletServer() { log.info("Loading the KumuluzEE server..."); List serversClasses = scanForAvailableServers(); if (serversClasses.isEmpty()) { String msg = "No supported servers were found. Please add one of them to the class " + "path. For example to add Jetty add the 'kumuluzee-servlet-jetty' module as a" + " dependency. For additional servers refer to the documentation."; log.severe(msg); throw new KumuluzServerException(msg); } if (serversClasses.size() > 1) { String msg = "Multiple servers were found. Only one can be used at a time, please " + "remove all but one servers. For additional information refer to the " + "documentation."; log.severe(msg); throw new KumuluzServerException(msg); } KumuluzServer server = serversClasses.get(0); ServerDef serverDef = server.getClass().getDeclaredAnnotation(ServerDef.class); if (serverDef == null) { String msg = "The found class \"" + server.getClass().getSimpleName() + "\" is missing the @ServerDef" + "annotation. The annotation is required in order to correctly process the specific " + "implementation and its components."; log.severe(msg); throw new KumuluzServerException(msg); } log.info("Found " + serverDef.value()); return server; } private static List scanForAvailableServers() { log.finest("Scanning for available supported KumuluzEE servers"); List servers = new ArrayList<>(); ServiceLoader.load(KumuluzServer.class).forEach(servers::add); return servers; } } ================================================ FILE: core/src/test/java/com/kumuluz/ee/test/ExampleTest.java ================================================ /* * Copyright (c) 2014-2017 Kumuluz and/or its affiliates * and other contributors as indicated by the @author tags and * the contributor list. * * Licensed under the MIT License (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://opensource.org/licenses/MIT * * The software is provided "AS IS", WITHOUT WARRANTY OF ANY KIND, express or * implied, including but not limited to the warranties of merchantability, * fitness for a particular purpose and noninfringement. in no event shall the * authors or copyright holders be liable for any claim, damages or other * liability, whether in an action of contract, tort or otherwise, arising from, * out of or in connection with the software or the use or other dealings in the * software. See the License for the specific language governing permissions and * limitations under the License. */ package com.kumuluz.ee.test; import org.junit.Assert; import org.junit.Test; /** * @author Tilen Faganel */ public class ExampleTest { @Test public void testAddition() { Assert.assertEquals(1 + 2, 3); } } ================================================ FILE: pom.xml ================================================ 4.0.0 com.kumuluz.ee kumuluzee pom 4.2.0-SNAPSHOT common core servlet components bom profiles tools KumuluzEE 2015 Lightweight framework for creating small standalone Java EE applications in a micro service way. https://ee.kumuluz.com 11 11 UTF-8 2.3.1 1.1.1 2.3.5 1.3.5 1.0.3 1.2.5 4.0.4 2.3.6 3.0.3 2.0.2 2.2.3 2.1.6 2.3.3 2.3.2 1.1.2 2.0.2 1.1.6 1.0.2 1.3.3 1.7.4 1.6.7 2.4.2.Final 3.3.2.Final 1.5.1 3.27.0-GA 1.9 1.27 4.13.1 3.8.2 3.6.1 2.3.2 3.2.0 3.2.0 3.6.0 3.8.1 3.1.2 10.0.9 2.0.0-alpha6 3.0.3 3.1.8.Final 6.2.0.Final 2.34 2.12.0 2.4.6 3.4.4 5.5.7.Final 2.7.10 2.3.16 1.1.4 1.0.8 5.10.6.Final 7.6.0.Final 1.6.2 scm:git:git@github.com:kumuluz/kumuluze.git scm:git:git@github.com:kumuluz/kumuluzee.git git@github.com:kumuluz/kumuluzee.git GitHub Issues https://github.com/kumuluz/kumuluzee/issues KumuluzEE Development Team kumuluz info@kumuluz.com https://github.com/kumuluz MIT License http://www.opensource.org/licenses/mit-license.php ossrh https://oss.sonatype.org/content/repositories/snapshots sonatype-snapshots OSS Sonatype repo (snapshots) https://oss.sonatype.org/content/repositories/snapshots/ false true com.kumuluz.ee kumuluzee-common ${project.version} com.kumuluz.ee kumuluzee-core ${project.version} com.kumuluz.ee kumuluzee-components ${project.version} com.kumuluz.ee kumuluzee-servlet ${project.version} pom com.kumuluz.ee kumuluzee-servlet-jetty ${project.version} com.kumuluz.ee kumuluzee-jsp ${project.version} pom com.kumuluz.ee kumuluzee-jsp-jetty ${project.version} com.kumuluz.ee kumuluzee-el ${project.version} pom com.kumuluz.ee kumuluzee-el-uel ${project.version} com.kumuluz.ee kumuluzee-cdi ${project.version} pom com.kumuluz.ee kumuluzee-cdi-weld ${project.version} com.kumuluz.ee kumuluzee-jpa ${project.version} pom com.kumuluz.ee kumuluzee-jpa-common ${project.version} com.kumuluz.ee kumuluzee-jpa-eclipselink ${project.version} com.kumuluz.ee kumuluzee-jpa-hibernate ${project.version} com.kumuluz.ee kumuluzee-jax-rs ${project.version} pom com.kumuluz.ee kumuluzee-jax-rs-jersey ${project.version} com.kumuluz.ee kumuluzee-jax-ws ${project.version} pom com.kumuluz.ee kumuluzee-jax-ws-metro ${project.version} com.kumuluz.ee kumuluzee-jax-ws-cxf ${project.version} com.kumuluz.ee kumuluzee-jsf ${project.version} pom com.kumuluz.ee kumuluzee-jsf-mojarra ${project.version} com.kumuluz.ee kumuluzee-websocket ${project.version} pom com.kumuluz.ee kumuluzee-websocket-jetty ${project.version} com.kumuluz.ee kumuluzee-bean-validation ${project.version} pom com.kumuluz.ee kumuluzee-bean-validation-hibernate-validator ${project.version} com.kumuluz.ee kumuluzee-json-p ${project.version} pom com.kumuluz.ee kumuluzee-json-p-jsonp ${project.version} com.kumuluz.ee kumuluzee-json-b ${project.version} pom com.kumuluz.ee kumuluzee-json-b-yasson ${project.version} com.kumuluz.ee kumuluzee-jta ${project.version} com.kumuluz.ee kumuluzee-jta-common ${project.version} com.kumuluz.ee kumuluzee-jta-narayana ${project.version} com.kumuluz.ee kumuluzee-bom ${project.version} pom com.kumuluz.ee kumuluzee-profiles ${project.version} pom com.kumuluz.ee kumuluzee-micro-profile ${project.version} com.kumuluz.ee kumuluzee-microProfile-3.3 ${project.version} com.kumuluz.ee kumuluzee-tools ${project.version} pom com.kumuluz.ee kumuluzee-loader ${project.version} com.kumuluz.ee kumuluzee-maven-plugin ${project.version} maven-plugin jakarta.annotation jakarta.annotation-api ${annotations.version} jakarta.inject jakarta.inject-api ${inject.version} jakarta.interceptor jakarta.interceptor-api ${interceptor.version} jakarta.servlet jakarta.servlet-api ${servlet.version} jakarta.servlet.jsp jakarta.servlet.jsp-api ${jsp.version} jakarta.el jakarta.el-api ${el.version} jakarta.enterprise jakarta.enterprise.cdi-api ${cdi.version} jakarta.persistence jakarta.persistence-api ${jpa.version} jakarta.ws.rs jakarta.ws.rs-api ${jaxrs.version} jakarta.xml.ws jakarta.xml.ws-api ${jaxws.version} jakarta.faces jakarta.faces-api ${jsf.version} jakarta.websocket jakarta.websocket-api ${websocket.version} jakarta.websocket jakarta.websocket-client-api ${websocket.version} jakarta.validation jakarta.validation-api ${beanvalidation.version} jakarta.json jakarta.json-api ${jsonp.version} jakarta.json.bind jakarta.json.bind-api ${jsonb.version} jakarta.transaction jakarta.transaction-api ${jta.version} jakarta.resource jakarta.resource-api ${resource.version} jakarta.mail jakarta.mail-api ${javamail.version} com.fasterxml.jackson jackson-bom ${jackson.version} import pom org.jboss jandex ${jandex.version} org.jboss.logging jboss-logging ${jboss-logging.version} com.fasterxml classmate ${classmate.version} org.javassist javassist ${javassist.version} io.agroal agroal-api ${agroal.version} org.yaml snakeyaml ${yaml.version} junit junit ${junit.version} org.apache.maven maven-plugin-api ${maven.plugin.api.version} org.apache.maven.plugin-tools maven-plugin-annotations ${maven-plugin-annotations.version} org.twdata.maven mojo-executor ${mojo-executor.version} org.sonatype.plugins nexus-staging-maven-plugin 1.6.5 true ossrh https://oss.sonatype.org/ true deploy org.apache.maven.plugins maven-gpg-plugin 1.6 sign-artifacts verify sign --pinentry-mode loopback org.apache.maven.plugins maven-javadoc-plugin none ================================================ FILE: profiles/micro-profile/pom.xml ================================================ kumuluzee-profiles com.kumuluz.ee 4.2.0-SNAPSHOT 4.0.0 KumuluzEE MicroProfile KumuluzEE MicroProfile which includes and tracks the latest community based specification found at https://microprofile.io, which focuses on technologies best-suited to build modern Java based cloud applications that follow the microservice architecture. The main KumuluzEE profile includes the reference implementations of the profile/specification. kumuluzee-micro-profile com.kumuluz.ee kumuluzee-microProfile-3.3 ================================================ FILE: profiles/micro-profile-1.0/pom.xml ================================================ kumuluzee-profiles com.kumuluz.ee 4.2.0-SNAPSHOT 4.0.0 KumuluzEE MicroProfile 1.0 KumuluzEE MicroProfile 1.0 which includes and tracks the version 1.0 community based specification found at https://microprofile.io, which focuses on technologies best-suited to build modern Java based cloud applications that follow the microservice architecture. The main KumuluzEE profile includes the reference implementations of the profile/specification. kumuluzee-microProfile-1.0 com.kumuluz.ee kumuluzee-core com.kumuluz.ee kumuluzee-servlet-jetty com.kumuluz.ee kumuluzee-cdi-weld com.kumuluz.ee kumuluzee-jax-rs-jersey com.kumuluz.ee kumuluzee-json-p-jsonp ================================================ FILE: profiles/micro-profile-1.1/pom.xml ================================================ kumuluzee-profiles com.kumuluz.ee 4.2.0-SNAPSHOT 4.0.0 KumuluzEE MicroProfile 1.1 KumuluzEE MicroProfile 1.1 which includes and tracks the version 1.1 community based specification found at https://microprofile.io, which focuses on technologies best-suited to build modern Java based cloud applications that follow the microservice architecture. The main KumuluzEE profile includes the reference implementations of the profile/specification. kumuluzee-microProfile-1.1 1.1.1 com.kumuluz.ee kumuluzee-core com.kumuluz.ee kumuluzee-servlet-jetty com.kumuluz.ee kumuluzee-cdi-weld com.kumuluz.ee kumuluzee-jax-rs-jersey com.kumuluz.ee kumuluzee-json-p-jsonp com.kumuluz.ee.config kumuluzee-config-mp ${version.kumuluzee-config-mp} ================================================ FILE: profiles/micro-profile-1.2/pom.xml ================================================ kumuluzee-profiles com.kumuluz.ee 4.2.0-SNAPSHOT 4.0.0 KumuluzEE MicroProfile 1.2 KumuluzEE MicroProfile 1.2 which includes and tracks the version 1.2 community based specification found at https://microprofile.io, which focuses on technologies best-suited to build modern Java based cloud applications that follow the microservice architecture. The main KumuluzEE profile includes the reference implementations of the profile/specification. kumuluzee-microProfile-1.2 1.1.1 1.0.0 1.0.0 1.0.0 1.0.0 com.kumuluz.ee kumuluzee-core com.kumuluz.ee kumuluzee-servlet-jetty com.kumuluz.ee kumuluzee-cdi-weld com.kumuluz.ee kumuluzee-jax-rs-jersey com.kumuluz.ee kumuluzee-json-p-jsonp com.kumuluz.ee.config kumuluzee-config-mp ${version.kumuluzee-config-mp} com.kumuluz.ee.fault.tolerance kumuluzee-fault-tolerance-hystrix ${version.kumuluzee-fault-tolerance} com.kumuluz.ee.health kumuluzee-health ${version.kumuluzee-health} com.kumuluz.ee.metrics kumuluzee-metrics-core ${version.kumuluzee-metrics} com.kumuluz.ee.jwt kumuluzee-jwt-auth ${version.kumuluzee-jwt-auth} ================================================ FILE: profiles/micro-profile-1.3/pom.xml ================================================ kumuluzee-profiles com.kumuluz.ee 4.2.0-SNAPSHOT 4.0.0 KumuluzEE MicroProfile 1.3 KumuluzEE MicroProfile 1.3 which includes and tracks the version 1.3 community based specification found at https://microprofile.io, which focuses on technologies best-suited to build modern Java based cloud applications that follow the microservice architecture. The main KumuluzEE profile includes the reference implementations of the profile/specification. kumuluzee-microProfile-1.3 1.2.1 1.0.1 1.0.1 1.1.2 1.0.1 1.2.1 1.0.1 1.0.1 com.kumuluz.ee kumuluzee-core com.kumuluz.ee kumuluzee-servlet-jetty com.kumuluz.ee kumuluzee-cdi-weld com.kumuluz.ee kumuluzee-jax-rs-jersey com.kumuluz.ee kumuluzee-json-p-jsonp com.kumuluz.ee.config kumuluzee-config-mp ${version.kumuluzee-config-mp} com.kumuluz.ee.fault.tolerance kumuluzee-fault-tolerance-hystrix ${version.kumuluzee-fault-tolerance} com.kumuluz.ee.health kumuluzee-health ${version.kumuluzee-health} com.kumuluz.ee.metrics kumuluzee-metrics-core ${version.kumuluzee-metrics} com.kumuluz.ee.jwt kumuluzee-jwt-auth ${version.kumuluzee-jwt-auth} com.kumuluz.ee.opentracing kumuluzee-opentracing-jaeger ${version.kumuluzee-opentracing} com.kumuluz.ee.openapi kumuluzee-openapi-mp ${version.kumuluzee-openapi-mp} com.kumuluz.ee.rest-client kumuluzee-rest-client ${version.kumuluzee-rest-client} ================================================ FILE: profiles/micro-profile-1.4/pom.xml ================================================ kumuluzee-profiles com.kumuluz.ee 4.2.0-SNAPSHOT 4.0.0 KumuluzEE MicroProfile 1.4 KumuluzEE MicroProfile 1.4 which includes and tracks the version 1.4 community based specification found at https://microprofile.io, which focuses on technologies best-suited to build modern Java based cloud applications that follow the microservice architecture. The main KumuluzEE profile includes the reference implementations of the profile/specification. kumuluzee-microProfile-1.4 1.3.0 1.1.3 1.0.1 1.1.2 1.1.1 1.2.1 1.0.1 1.1.0 com.kumuluz.ee kumuluzee-core com.kumuluz.ee kumuluzee-servlet-jetty com.kumuluz.ee kumuluzee-cdi-weld com.kumuluz.ee kumuluzee-jax-rs-jersey com.kumuluz.ee kumuluzee-json-p-jsonp com.kumuluz.ee.config kumuluzee-config-mp ${version.kumuluzee-config-mp} com.kumuluz.ee.fault.tolerance kumuluzee-fault-tolerance-hystrix ${version.kumuluzee-fault-tolerance} com.kumuluz.ee.health kumuluzee-health ${version.kumuluzee-health} com.kumuluz.ee.metrics kumuluzee-metrics-core ${version.kumuluzee-metrics} com.kumuluz.ee.jwt kumuluzee-jwt-auth ${version.kumuluzee-jwt-auth} com.kumuluz.ee.opentracing kumuluzee-opentracing-jaeger ${version.kumuluzee-opentracing} com.kumuluz.ee.openapi kumuluzee-openapi-mp ${version.kumuluzee-openapi-mp} com.kumuluz.ee.rest-client kumuluzee-rest-client ${version.kumuluzee-rest-client} ================================================ FILE: profiles/micro-profile-2.0/pom.xml ================================================ kumuluzee-profiles com.kumuluz.ee 4.2.0-SNAPSHOT 4.0.0 KumuluzEE MicroProfile 2.0 KumuluzEE MicroProfile 2.0 which includes and tracks the version 2.0 community based specification found at https://microprofile.io, which focuses on technologies best-suited to build modern Java based cloud applications that follow the microservice architecture. The main KumuluzEE profile includes the reference implementations of the profile/specification. kumuluzee-microProfile-2.0 1.3.0 1.1.3 1.0.1 1.1.2 1.1.1 1.2.1 1.0.1 1.1.0 com.kumuluz.ee kumuluzee-core com.kumuluz.ee kumuluzee-servlet-jetty com.kumuluz.ee kumuluzee-cdi-weld com.kumuluz.ee kumuluzee-jax-rs-jersey com.kumuluz.ee kumuluzee-json-p-jsonp com.kumuluz.ee kumuluzee-json-b-yasson com.kumuluz.ee.config kumuluzee-config-mp ${version.kumuluzee-config-mp} com.kumuluz.ee.fault.tolerance kumuluzee-fault-tolerance-hystrix ${version.kumuluzee-fault-tolerance} com.kumuluz.ee.health kumuluzee-health ${version.kumuluzee-health} com.kumuluz.ee.metrics kumuluzee-metrics-core ${version.kumuluzee-metrics} com.kumuluz.ee.jwt kumuluzee-jwt-auth ${version.kumuluzee-jwt-auth} com.kumuluz.ee.opentracing kumuluzee-opentracing-jaeger ${version.kumuluzee-opentracing} com.kumuluz.ee.openapi kumuluzee-openapi-mp ${version.kumuluzee-openapi-mp} com.kumuluz.ee.rest-client kumuluzee-rest-client ${version.kumuluzee-rest-client} ================================================ FILE: profiles/micro-profile-2.1/pom.xml ================================================ kumuluzee-profiles com.kumuluz.ee 4.2.0-SNAPSHOT 4.0.0 KumuluzEE MicroProfile 2.1 KumuluzEE MicroProfile 2.1 which includes and tracks the version 2.1 community based specification found at https://microprofile.io, which focuses on technologies best-suited to build modern Java based cloud applications that follow the microservice architecture. The main KumuluzEE profile includes the reference implementations of the profile/specification. kumuluzee-microProfile-2.1 1.3.0 1.1.3 1.0.1 1.1.2 1.1.1 1.2.1 1.0.1 1.1.0 com.kumuluz.ee kumuluzee-core com.kumuluz.ee kumuluzee-servlet-jetty com.kumuluz.ee kumuluzee-cdi-weld com.kumuluz.ee kumuluzee-jax-rs-jersey com.kumuluz.ee kumuluzee-json-p-jsonp com.kumuluz.ee kumuluzee-json-b-yasson com.kumuluz.ee.config kumuluzee-config-mp ${version.kumuluzee-config-mp} com.kumuluz.ee.fault.tolerance kumuluzee-fault-tolerance-hystrix ${version.kumuluzee-fault-tolerance} com.kumuluz.ee.health kumuluzee-health ${version.kumuluzee-health} com.kumuluz.ee.metrics kumuluzee-metrics-core ${version.kumuluzee-metrics} com.kumuluz.ee.jwt kumuluzee-jwt-auth ${version.kumuluzee-jwt-auth} com.kumuluz.ee.opentracing kumuluzee-opentracing-jaeger ${version.kumuluzee-opentracing} com.kumuluz.ee.openapi kumuluzee-openapi-mp ${version.kumuluzee-openapi-mp} com.kumuluz.ee.rest-client kumuluzee-rest-client ${version.kumuluzee-rest-client} ================================================ FILE: profiles/micro-profile-2.2/pom.xml ================================================ kumuluzee-profiles com.kumuluz.ee 4.2.0-SNAPSHOT 4.0.0 KumuluzEE MicroProfile 2.2 KumuluzEE MicroProfile 2.2 which includes and tracks the version 2.2 community based specification found at https://microprofile.io, which focuses on technologies best-suited to build modern Java based cloud applications that follow the microservice architecture. The main KumuluzEE profile includes the reference implementations of the profile/specification. kumuluzee-microProfile-2.2 1.3.0 2.0.0 1.0.1 1.1.3 1.1.1 1.3.1 1.1.2 1.2.2 com.kumuluz.ee kumuluzee-core com.kumuluz.ee kumuluzee-servlet-jetty com.kumuluz.ee kumuluzee-cdi-weld com.kumuluz.ee kumuluzee-jax-rs-jersey com.kumuluz.ee kumuluzee-json-p-jsonp com.kumuluz.ee kumuluzee-json-b-yasson com.kumuluz.ee.config kumuluzee-config-mp ${version.kumuluzee-config-mp} com.kumuluz.ee.fault.tolerance kumuluzee-fault-tolerance-smallrye ${version.kumuluzee-fault-tolerance} com.kumuluz.ee.health kumuluzee-health ${version.kumuluzee-health} com.kumuluz.ee.metrics kumuluzee-metrics-core ${version.kumuluzee-metrics} com.kumuluz.ee.jwt kumuluzee-jwt-auth ${version.kumuluzee-jwt-auth} com.kumuluz.ee.opentracing kumuluzee-opentracing-jaeger ${version.kumuluzee-opentracing} com.kumuluz.ee.openapi kumuluzee-openapi-mp ${version.kumuluzee-openapi-mp} com.kumuluz.ee.rest-client kumuluzee-rest-client ${version.kumuluzee-rest-client} ================================================ FILE: profiles/micro-profile-3.0/pom.xml ================================================ kumuluzee-profiles com.kumuluz.ee 4.2.0-SNAPSHOT 4.0.0 KumuluzEE MicroProfile 3.0 KumuluzEE MicroProfile 3.0 which includes and tracks the version 3.0 community based specification found at https://microprofile.io, which focuses on technologies best-suited to build modern Java based cloud applications that follow the microservice architecture. The main KumuluzEE profile includes the reference implementations of the profile/specification. kumuluzee-microProfile-3.0 1.3.0 2.0.1 2.0.1 2.0.1 1.1.3 1.3.1 1.1.2 1.3.3 com.kumuluz.ee kumuluzee-core com.kumuluz.ee kumuluzee-servlet-jetty com.kumuluz.ee kumuluzee-cdi-weld com.kumuluz.ee kumuluzee-jax-rs-jersey com.kumuluz.ee kumuluzee-json-p-jsonp com.kumuluz.ee kumuluzee-json-b-yasson com.kumuluz.ee.config kumuluzee-config-mp ${version.kumuluzee-config-mp} com.kumuluz.ee.fault.tolerance kumuluzee-fault-tolerance-smallrye ${version.kumuluzee-fault-tolerance} com.kumuluz.ee.health kumuluzee-health ${version.kumuluzee-health} com.kumuluz.ee.metrics kumuluzee-metrics-core ${version.kumuluzee-metrics} com.kumuluz.ee.jwt kumuluzee-jwt-auth ${version.kumuluzee-jwt-auth} com.kumuluz.ee.opentracing kumuluzee-opentracing-jaeger ${version.kumuluzee-opentracing} com.kumuluz.ee.openapi kumuluzee-openapi-mp ${version.kumuluzee-openapi-mp} com.kumuluz.ee.rest-client kumuluzee-rest-client ${version.kumuluzee-rest-client} ================================================ FILE: profiles/micro-profile-3.1/pom.xml ================================================ kumuluzee-profiles com.kumuluz.ee 4.2.0-SNAPSHOT 4.0.0 KumuluzEE MicroProfile 3.1 KumuluzEE MicroProfile 3.1 which includes and tracks the version 3.1 community based specification found at https://microprofile.io, which focuses on technologies best-suited to build modern Java based cloud applications that follow the microservice architecture. The main KumuluzEE profile includes the reference implementations of the profile/specification. kumuluzee-microProfile-3.1 1.3.0 2.0.1 2.1.1 2.1.0 1.1.3 1.3.1 1.1.2 1.3.3 com.kumuluz.ee kumuluzee-core com.kumuluz.ee kumuluzee-servlet-jetty com.kumuluz.ee kumuluzee-cdi-weld com.kumuluz.ee kumuluzee-jax-rs-jersey com.kumuluz.ee kumuluzee-json-p-jsonp com.kumuluz.ee kumuluzee-json-b-yasson com.kumuluz.ee.config kumuluzee-config-mp ${version.kumuluzee-config-mp} com.kumuluz.ee.fault.tolerance kumuluzee-fault-tolerance-smallrye ${version.kumuluzee-fault-tolerance} com.kumuluz.ee.health kumuluzee-health ${version.kumuluzee-health} com.kumuluz.ee.metrics kumuluzee-metrics-core ${version.kumuluzee-metrics} com.kumuluz.ee.jwt kumuluzee-jwt-auth ${version.kumuluzee-jwt-auth} com.kumuluz.ee.opentracing kumuluzee-opentracing-jaeger ${version.kumuluzee-opentracing} com.kumuluz.ee.openapi kumuluzee-openapi-mp ${version.kumuluzee-openapi-mp} com.kumuluz.ee.rest-client kumuluzee-rest-client ${version.kumuluzee-rest-client} ================================================ FILE: profiles/micro-profile-3.2/pom.xml ================================================ kumuluzee-profiles com.kumuluz.ee 4.2.0-SNAPSHOT 4.0.0 KumuluzEE MicroProfile 3.2 KumuluzEE MicroProfile 3.2 which includes and tracks the version 3.2 community based specification found at https://microprofile.io, which focuses on technologies best-suited to build modern Java based cloud applications that follow the microservice architecture. The main KumuluzEE profile includes the reference implementations of the profile/specification. kumuluzee-microProfile-3.2 1.3.0 2.0.1 2.1.1 2.2.1 1.1.3 1.3.1 1.1.2 1.3.3 com.kumuluz.ee kumuluzee-core com.kumuluz.ee kumuluzee-servlet-jetty com.kumuluz.ee kumuluzee-cdi-weld com.kumuluz.ee kumuluzee-jax-rs-jersey com.kumuluz.ee kumuluzee-json-p-jsonp com.kumuluz.ee kumuluzee-json-b-yasson com.kumuluz.ee.config kumuluzee-config-mp ${version.kumuluzee-config-mp} com.kumuluz.ee.fault.tolerance kumuluzee-fault-tolerance-smallrye ${version.kumuluzee-fault-tolerance} com.kumuluz.ee.health kumuluzee-health ${version.kumuluzee-health} com.kumuluz.ee.metrics kumuluzee-metrics-core ${version.kumuluzee-metrics} com.kumuluz.ee.jwt kumuluzee-jwt-auth ${version.kumuluzee-jwt-auth} com.kumuluz.ee.opentracing kumuluzee-opentracing-jaeger ${version.kumuluzee-opentracing} com.kumuluz.ee.openapi kumuluzee-openapi-mp ${version.kumuluzee-openapi-mp} com.kumuluz.ee.rest-client kumuluzee-rest-client ${version.kumuluzee-rest-client} ================================================ FILE: profiles/micro-profile-3.3/pom.xml ================================================ kumuluzee-profiles com.kumuluz.ee 4.2.0-SNAPSHOT 4.0.0 KumuluzEE MicroProfile 3.3 KumuluzEE MicroProfile 3.3 which includes and tracks the version 3.3 community based specification found at https://microprofile.io, which focuses on technologies best-suited to build modern Java based cloud applications that follow the microservice architecture. The main KumuluzEE profile includes the reference implementations of the profile/specification. kumuluzee-microProfile-3.3 1.4.0 2.1.1 2.2.0 2.3.0 1.1.3 1.3.1 1.2.2 1.4.1.2 com.kumuluz.ee kumuluzee-core com.kumuluz.ee kumuluzee-servlet-jetty com.kumuluz.ee kumuluzee-cdi-weld com.kumuluz.ee kumuluzee-jax-rs-jersey com.kumuluz.ee kumuluzee-json-p-jsonp com.kumuluz.ee kumuluzee-json-b-yasson com.kumuluz.ee.config kumuluzee-config-mp ${version.kumuluzee-config-mp} com.kumuluz.ee.fault.tolerance kumuluzee-fault-tolerance-smallrye ${version.kumuluzee-fault-tolerance} com.kumuluz.ee.health kumuluzee-health ${version.kumuluzee-health} com.kumuluz.ee.metrics kumuluzee-metrics-core ${version.kumuluzee-metrics} com.kumuluz.ee.jwt kumuluzee-jwt-auth ${version.kumuluzee-jwt-auth} com.kumuluz.ee.opentracing kumuluzee-opentracing-jaeger ${version.kumuluzee-opentracing} com.kumuluz.ee.openapi kumuluzee-openapi-mp ${version.kumuluzee-openapi-mp} com.kumuluz.ee.rest-client kumuluzee-rest-client ${version.kumuluzee-rest-client} org.eclipse.microprofile.fault-tolerance microprofile-fault-tolerance-api ================================================ FILE: profiles/pom.xml ================================================ kumuluzee com.kumuluz.ee 4.2.0-SNAPSHOT 4.0.0 pom KumuluzEE Profiles KumuluzEE component profiles with the most common selections of components for easier standardization and bootstrapping of the runtime environment. micro-profile micro-profile-1.0 micro-profile-1.1 micro-profile-1.2 micro-profile-1.3 micro-profile-1.4 micro-profile-2.0 micro-profile-2.1 micro-profile-2.2 micro-profile-3.0 micro-profile-3.1 micro-profile-3.2 micro-profile-3.3 kumuluzee-profiles ================================================ FILE: servlet/jetty/pom.xml ================================================ kumuluzee-servlet com.kumuluz.ee 4.2.0-SNAPSHOT 4.0.0 KumuluzEE Servlet Jetty KumuluzEE servlet component implemented by Jetty kumuluzee-servlet-jetty com.kumuluz.ee kumuluzee-common com.kumuluz.ee kumuluzee-loader true org.eclipse.jetty jetty-alpn-java-server ${jetty.version} org.eclipse.jetty jetty-alpn-java-client ${jetty.version} org.eclipse.jetty jetty-webapp ${jetty.version} org.eclipse.jetty jetty-annotations ${jetty.version} org.eclipse.jetty jetty-jndi ${jetty.version} org.eclipse.jetty.http2 http2-server ${jetty.version} org.eclipse.jetty jetty-alpn-server ${jetty.version} org.eclipse.jetty.http2 http2-http-client-transport ${jetty.version} org.slf4j slf4j-jdk14 ${slf4j.version} junit junit test ================================================ FILE: servlet/jetty/src/main/java/com/kumuluz/ee/jetty/JettyAttributes.java ================================================ /* * Copyright (c) 2014-2017 Kumuluz and/or its affiliates * and other contributors as indicated by the @author tags and * the contributor list. * * Licensed under the MIT License (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://opensource.org/licenses/MIT * * The software is provided "AS IS", WITHOUT WARRANTY OF ANY KIND, express or * implied, including but not limited to the warranties of merchantability, * fitness for a particular purpose and noninfringement. in no event shall the * authors or copyright holders be liable for any claim, damages or other * liability, whether in an action of contract, tort or otherwise, arising from, * out of or in connection with the software or the use or other dealings in the * software. See the License for the specific language governing permissions and * limitations under the License. */ package com.kumuluz.ee.jetty; /** * @author Tilen Faganel * @since 1.0.0 */ public class JettyAttributes { public static final String jarPattern = "org.eclipse.jetty.server.webapp" + ".ContainerIncludeJarPattern"; public static final String dirBrowsing = "org.eclipse.jetty.servlet.Default.dirAllowed"; public static final String etags = "org.eclipse.jetty.servlet.Default.etags"; } ================================================ FILE: servlet/jetty/src/main/java/com/kumuluz/ee/jetty/JettyFactory.java ================================================ /* * Copyright (c) 2014-2017 Kumuluz and/or its affiliates * and other contributors as indicated by the @author tags and * the contributor list. * * Licensed under the MIT License (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://opensource.org/licenses/MIT * * The software is provided "AS IS", WITHOUT WARRANTY OF ANY KIND, express or * implied, including but not limited to the warranties of merchantability, * fitness for a particular purpose and noninfringement. in no event shall the * authors or copyright holders be liable for any claim, damages or other * liability, whether in an action of contract, tort or otherwise, arising from, * out of or in connection with the software or the use or other dealings in the * software. See the License for the specific language governing permissions and * limitations under the License. */ package com.kumuluz.ee.jetty; import com.kumuluz.ee.common.config.ServerConfig; import com.kumuluz.ee.common.config.ServerConnectorConfig; import com.kumuluz.ee.common.utils.StringUtils; import org.eclipse.jetty.alpn.server.ALPNServerConnectionFactory; import org.eclipse.jetty.http.HttpVersion; import org.eclipse.jetty.http2.HTTP2Cipher; import org.eclipse.jetty.http2.server.HTTP2CServerConnectionFactory; import org.eclipse.jetty.http2.server.HTTP2ServerConnectionFactory; import org.eclipse.jetty.server.*; import org.eclipse.jetty.util.ssl.SslContextFactory; import org.eclipse.jetty.util.thread.QueuedThreadPool; import org.eclipse.jetty.util.thread.ThreadPool; import java.util.ArrayList; import java.util.List; import java.util.logging.Logger; import java.util.stream.Collectors; /** * @author Tilen Faganel * @since 1.0.0 */ public class JettyFactory { private static final Logger LOG = Logger.getLogger(JettyFactory.class.getSimpleName()); private final ServerConfig serverConfig; public JettyFactory(ServerConfig serverConfig) { this.serverConfig = serverConfig; } public Server create() { Server server = new Server(createThreadPool()); server.setStopAtShutdown(true); server.setConnectors(createConnectors(server)); return server; } private ThreadPool createThreadPool() { QueuedThreadPool threadPool = new QueuedThreadPool(); threadPool.setMinThreads(serverConfig.getMinThreads()); threadPool.setMaxThreads(serverConfig.getMaxThreads()); LOG.info("Starting KumuluzEE on Jetty with " + serverConfig.getMinThreads() + " minimum " + "and " + serverConfig.getMaxThreads() + " maximum threads"); return threadPool; } private Connector[] createConnectors(final Server server) { ServerConnectorConfig httpConfig = serverConfig.getHttp(); ServerConnectorConfig httpsConfig = serverConfig.getHttps(); List connectors = new ArrayList<>(); if (Boolean.FALSE.equals(httpConfig.getEnabled()) && (httpsConfig == null || Boolean.FALSE.equals(httpsConfig.getEnabled()))) { throw new IllegalStateException("Both the HTTP and HTTPS connectors can not be disabled. Please enable at least one."); } if (serverConfig.getForceHttps() && (httpsConfig == null || !Boolean.TRUE.equals(httpsConfig.getEnabled()))) { throw new IllegalStateException("You must enable the HTTPS connector in order to force redirects to it (`kumuluzee.server" + ".https.enabled` must be true)."); } if (httpConfig.getEnabled() == null || httpConfig.getEnabled()) { HttpConfiguration httpConfiguration = new HttpConfiguration(); httpConfiguration.setRequestHeaderSize(httpConfig.getRequestHeaderSize()); httpConfiguration.setResponseHeaderSize(httpConfig.getResponseHeaderSize()); httpConfiguration.setSendServerVersion(serverConfig.getShowServerInfo()); if (Boolean.TRUE.equals(httpConfig.getProxyForwarding())) { httpConfiguration.addCustomizer(new ForwardedRequestCustomizer()); } if (httpsConfig != null && Boolean.TRUE.equals(httpsConfig.getEnabled())) { httpConfiguration.setSecurePort( httpsConfig.getPort() == null ? ServerConnectorConfig.DEFAULT_HTTPS_PORT : httpsConfig.getPort()); } ServerConnector httpConnector; HttpConnectionFactory http = new HttpConnectionFactory(httpConfiguration); if (httpConfig.getHttp2()) { HTTP2CServerConnectionFactory http2c = new HTTP2CServerConnectionFactory(httpConfiguration); httpConnector = new ServerConnector(server, http, http2c); } else { httpConnector = new ServerConnector(server, http); } httpConnector.setPort(httpConfig.getPort() == null ? ServerConnectorConfig.DEFAULT_HTTP_PORT : httpConfig.getPort()); httpConnector.setHost(httpConfig.getAddress()); httpConnector.setIdleTimeout(httpConfig.getIdleTimeout()); connectors.add(httpConnector); } if (httpsConfig != null && httpsConfig.getEnabled() != null && httpsConfig.getEnabled()) { if (StringUtils.isNullOrEmpty(httpsConfig.getKeystorePath())) { throw new IllegalStateException("Cannot create SSL connector; keystore path not specified."); } if (StringUtils.isNullOrEmpty(httpsConfig.getKeystorePassword())) { throw new IllegalStateException("Cannot create SSL connector; keystore password not specified."); } if (StringUtils.isNullOrEmpty(httpsConfig.getKeyPassword())) { throw new IllegalStateException("Cannot create SSL connector; key password not specified."); } ServerConnector httpsConnector; HttpConfiguration httpsConfiguration = new HttpConfiguration(); httpsConfiguration.setRequestHeaderSize(httpsConfig.getRequestHeaderSize()); httpsConfiguration.setResponseHeaderSize(httpsConfig.getResponseHeaderSize()); httpsConfiguration.addCustomizer(new SecureRequestCustomizer()); httpsConfiguration.setSendServerVersion(serverConfig.getShowServerInfo()); if (Boolean.TRUE.equals(httpsConfig.getProxyForwarding())) { httpsConfiguration.addCustomizer(new ForwardedRequestCustomizer()); } HttpConnectionFactory http = new HttpConnectionFactory(httpsConfiguration); SslContextFactory.Server sslContextFactory = new SslContextFactory.Server(); sslContextFactory.setKeyStorePath(httpsConfig.getKeystorePath()); sslContextFactory.setKeyStorePassword(httpsConfig.getKeystorePassword()); if (httpsConfig.getKeyPassword() != null) { sslContextFactory.setKeyManagerPassword(httpsConfig.getKeyPassword()); } if (StringUtils.isNullOrEmpty(httpsConfig.getKeyAlias())) { sslContextFactory.setCertAlias(httpsConfig.getKeyAlias()); } if (httpsConfig.getSslProtocols() != null) { sslContextFactory.setIncludeProtocols(httpsConfig.getSslProtocols().toArray(new String[0])); } if (httpsConfig.getSslCiphers() != null) { sslContextFactory.setExcludeCipherSuites(); sslContextFactory.setIncludeCipherSuites(httpsConfig.getSslCiphers().toArray(new String[0])); } if (httpsConfig.getHttp2()) { sslContextFactory.setCipherComparator(HTTP2Cipher.COMPARATOR); sslContextFactory.setUseCipherSuitesOrder(true); HTTP2ServerConnectionFactory h2 = new HTTP2ServerConnectionFactory(httpsConfiguration); ALPNServerConnectionFactory alpn = new ALPNServerConnectionFactory(); alpn.setDefaultProtocol(HttpVersion.HTTP_1_1.toString()); SslConnectionFactory ssl = new SslConnectionFactory(sslContextFactory, alpn.getProtocol()); httpsConnector = new ServerConnector(server, ssl, alpn, h2, http); } else { SslConnectionFactory ssl = new SslConnectionFactory(sslContextFactory, http.getProtocol()); httpsConnector = new ServerConnector(server, ssl, http); } httpsConnector.setPort(httpsConfig.getPort() == null ? ServerConnectorConfig.DEFAULT_HTTPS_PORT : httpsConfig.getPort()); httpsConnector.setHost(httpsConfig.getAddress()); httpsConnector.setIdleTimeout(httpsConfig.getIdleTimeout()); connectors.add(httpsConnector); } String ports = connectors.stream() .map(connector -> String.format("%d [%s]", connector.getPort(), String.join(", ", connector.getProtocols()))) .collect(Collectors.joining(", ")); LOG.info(String.format("Starting KumuluzEE on port(s): %s", ports)); return connectors.toArray(new ServerConnector[0]); } } ================================================ FILE: servlet/jetty/src/main/java/com/kumuluz/ee/jetty/JettyJarClasspathUtil.java ================================================ /* * Copyright (c) 2014-2017 Kumuluz and/or its affiliates * and other contributors as indicated by the @author tags and * the contributor list. * * Licensed under the MIT License (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://opensource.org/licenses/MIT * * The software is provided "AS IS", WITHOUT WARRANTY OF ANY KIND, express or * implied, including but not limited to the warranties of merchantability, * fitness for a particular purpose and noninfringement. in no event shall the * authors or copyright holders be liable for any claim, damages or other * liability, whether in an action of contract, tort or otherwise, arising from, * out of or in connection with the software or the use or other dealings in the * software. See the License for the specific language governing permissions and * limitations under the License. */ package com.kumuluz.ee.jetty; import com.kumuluz.ee.loader.EeClassLoader; import java.util.List; /** * Obtains extra classpath jars from {@link EeClassLoader}. Must be in separate file because {@link EeClassLoader} is * not present on the classpath when running in exploded. * * @author Urban Malc * @since 3.1.0 */ public class JettyJarClasspathUtil { public static String getExtraClasspath(List scanLibraries) { if (!(JettyJarClasspathUtil.class.getClassLoader() instanceof EeClassLoader)) { throw new IllegalStateException("Classloader not instance of EeClassLoader"); } EeClassLoader eeClassLoader = (EeClassLoader) JettyJarClasspathUtil.class.getClassLoader(); return String.join(",", eeClassLoader .getJarFilesLocations(scanLibraries)); } } ================================================ FILE: servlet/jetty/src/main/java/com/kumuluz/ee/jetty/JettyServletServer.java ================================================ /* * Copyright (c) 2014-2017 Kumuluz and/or its affiliates * and other contributors as indicated by the @author tags and * the contributor list. * * Licensed under the MIT License (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://opensource.org/licenses/MIT * * The software is provided "AS IS", WITHOUT WARRANTY OF ANY KIND, express or * implied, including but not limited to the warranties of merchantability, * fitness for a particular purpose and noninfringement. in no event shall the * authors or copyright holders be liable for any claim, damages or other * liability, whether in an action of contract, tort or otherwise, arising from, * out of or in connection with the software or the use or other dealings in the * software. See the License for the specific language governing permissions and * limitations under the License. */ package com.kumuluz.ee.jetty; import com.kumuluz.ee.common.ServletServer; import com.kumuluz.ee.common.attributes.ClasspathAttributes; import com.kumuluz.ee.common.config.EeConfig; import com.kumuluz.ee.common.config.GzipConfig; import com.kumuluz.ee.common.config.ServerConfig; import com.kumuluz.ee.common.dependencies.EeComponentType; import com.kumuluz.ee.common.dependencies.ServerDef; import com.kumuluz.ee.common.exceptions.KumuluzServerException; import com.kumuluz.ee.common.servlet.ServletWrapper; import com.kumuluz.ee.common.utils.ResourceUtils; import org.eclipse.jetty.annotations.AnnotationConfiguration; import org.eclipse.jetty.plus.jndi.Resource; import org.eclipse.jetty.plus.jndi.Transaction; import org.eclipse.jetty.plus.webapp.EnvConfiguration; import org.eclipse.jetty.plus.webapp.PlusConfiguration; import org.eclipse.jetty.server.Handler; import org.eclipse.jetty.server.Server; import org.eclipse.jetty.server.handler.HandlerList; import org.eclipse.jetty.server.handler.SecuredRedirectHandler; import org.eclipse.jetty.server.handler.gzip.GzipHandler; import org.eclipse.jetty.servlet.FilterHolder; import org.eclipse.jetty.servlet.ServletHolder; import org.eclipse.jetty.servlet.listener.ELContextCleaner; import org.eclipse.jetty.webapp.*; import javax.naming.NamingException; import javax.servlet.DispatcherType; import javax.servlet.Filter; import javax.servlet.Servlet; import javax.sql.DataSource; import javax.transaction.UserTransaction; import java.io.IOException; import java.util.*; import java.util.logging.Level; import java.util.logging.Logger; import java.util.regex.Pattern; /** * @author Tilen Faganel * @since 1.0.0 */ @ServerDef(value = "Jetty", provides = {EeComponentType.SERVLET}) public class JettyServletServer implements ServletServer { private final Logger log = Logger.getLogger(JettyServletServer.class.getSimpleName()); private Server server; private WebAppContext appContext; private ServerConfig serverConfig; @Override public void initServer() { server = createJettyFactory().create(); } @Override public void startServer() { if (server == null) throw new IllegalStateException("Jetty has to be initialized before starting it"); if (server.isStarted() || server.isStarting()) throw new IllegalStateException("Jetty is already started"); try { server.start(); } catch (Exception e) { log.severe(e.getMessage()); throw new KumuluzServerException(e.getMessage(), e); } } @Override public void stopServer() { if (server == null) throw new IllegalStateException("Jetty has to be initialized before stopping it"); if (server.isStopped() || server.isStopping()) throw new IllegalStateException("Jetty is already stopped"); try { server.stop(); } catch (Exception e) { log.severe(e.getMessage()); throw new KumuluzServerException(e.getMessage(), e.getCause()); } } @Override public void initWebContext(List scanLibraries) { if (server == null) throw new IllegalStateException("Jetty has to be initialized before adding a web context"); if (server.isStarted() || server.isStarting()) throw new IllegalStateException("Jetty cannot be started before adding a web context"); if (EeConfig.getInstance().getDev().getScanLibraries() != null) { scanLibraries.addAll(EeConfig.getInstance().getDev().getScanLibraries()); } appContext = new WebAppContext(); appContext.setConfigurationClasses(createConfigurations()); try { appContext.setClassLoader(getClass().getClassLoader()); } catch (Exception e) { throw new IllegalStateException("Unable to set custom classloader for Jetty", e); } if (ResourceUtils.isRunningInJar()) { appContext.setAttribute(JettyAttributes.jarPattern, ClasspathAttributes.jar); try { appContext.setExtraClasspath(JettyJarClasspathUtil.getExtraClasspath(scanLibraries)); } catch (IOException e) { throw new IllegalStateException("Unable to set extra classpath for Jetty", e); } } else { StringBuilder explodedClasspath = new StringBuilder(ClasspathAttributes.exploded); if (ResourceUtils.isRunningTests()) { explodedClasspath.append("|").append(ClasspathAttributes.exploded_test); } for (String lib : scanLibraries) { if (lib.endsWith(".jar")) { explodedClasspath.append("|^.*/").append(Pattern.quote(lib)).append("$"); } else { explodedClasspath.append("|^.*/").append(Pattern.quote(lib)).append("-[^/]+\\.jar$"); } } log.fine("Using classpath scanning regex: " + explodedClasspath); appContext.setAttribute(JettyAttributes.jarPattern, explodedClasspath.toString()); } appContext.setParentLoaderPriority(true); appContext.setResourceBase(ResourceUtils.getProjectWebResources()); appContext.setContextPath(serverConfig.getContextPath()); if (serverConfig.getForwardStartupException() != null) { appContext.setThrowUnavailableOnStartupException(serverConfig.getForwardStartupException()); } if (!Boolean.TRUE.equals(serverConfig.getDirBrowsing())) { appContext.setInitParameter(JettyAttributes.dirBrowsing, "false"); } if (Boolean.TRUE.equals(serverConfig.getEtags())) { appContext.setInitParameter(JettyAttributes.etags, "true"); } // Since ELContextCleaner cannot perform reflective access to BeanELResolver it logs a warning before container // shutdown. Because Jetty is running in embedded mode, this purge is not necessary and the warning is irrelevant. Logger.getLogger(ELContextCleaner.class.getName()).setLevel(Level.SEVERE); log.info("Starting KumuluzEE with context root '" + serverConfig.getContextPath() + "'"); GzipConfig gzipConfig = serverConfig.getGzip(); if (serverConfig.getForceHttps() || (gzipConfig != null && gzipConfig.getEnabled())) { final ArrayList handlers = new ArrayList<>(); // Set the secured redirect handler in case the force https option is selected if( serverConfig.getForceHttps()) { handlers.add(new SecuredRedirectHandler()); } // Set the gzip handler in case the use gzip option is selected if(gzipConfig != null && gzipConfig.getEnabled()) { GzipHandler gzipHandler = new GzipHandler(); if(gzipConfig.getMinGzipSize() != null) gzipHandler.setMinGzipSize(gzipConfig.getMinGzipSize()); if(gzipConfig.getIncludedMethods() != null) gzipHandler.setIncludedMethods(gzipConfig.getIncludedMethods().toArray(new String[0])); if(gzipConfig.getIncludedMimeTypes() != null) gzipHandler.setIncludedMimeTypes(gzipConfig.getIncludedMimeTypes().toArray(new String[0])); if(gzipConfig.getExcludedMimeTypes() != null) gzipHandler.setExcludedMimeTypes(gzipConfig.getExcludedMimeTypes().toArray(new String[0])); if(gzipConfig.getExcludedPaths() != null) gzipHandler.setExcludedPaths(gzipConfig.getExcludedPaths().toArray(new String[0])); if(gzipConfig.getIncludedPaths() != null) gzipHandler.setIncludedPaths(gzipConfig.getIncludedPaths().toArray(new String[0])); gzipHandler.setHandler(appContext); handlers.add(gzipHandler); } else { handlers.add(appContext); } HandlerList handlerList = new HandlerList(); handlerList.setHandlers(handlers.toArray(new Handler[0])); server.setHandler(handlerList); } else { server.setHandler(appContext); } } @Override public ServerConfig getServerConfig() { return serverConfig; } @Override public void setServerConfig(ServerConfig serverConfig) { this.serverConfig = serverConfig; } @Override public void registerServlet(Class servletClass, String mapping) { registerServlet(servletClass, mapping, null, 0); } @Override public void registerServlet(Class servletClass, String mapping, Map parameters) { registerServlet(servletClass, mapping, parameters, 0); } @Override public void registerServlet(Class servletClass, String mapping, Map parameters, int initOrder) { if (server == null) throw new IllegalStateException("Jetty has to be initialized before adding a servlet "); if (server.isStarted() || server.isStarting()) throw new IllegalStateException("Jetty cannot be started before adding a servlet"); @SuppressWarnings("unchecked") Class servlet = (Class) servletClass; ServletHolder holder = new ServletHolder(servlet); holder.setInitOrder(initOrder); if (parameters != null) { parameters.forEach(holder::setInitParameter); } appContext.addServlet(holder, mapping); } @Override public void registerListener(EventListener listener) { if (server == null) throw new IllegalStateException("Jetty has to be initialized before adding a listener"); if (server.isStarted() || server.isStarting()) throw new IllegalStateException("Jetty cannot be started before adding a listener"); appContext.addEventListener(listener); } @Override public void registerFilter(Class filterClass, String pathSpec) { registerFilter(filterClass, pathSpec, EnumSet.of(DispatcherType.REQUEST)); } @Override public void registerFilter(Class filterClass, String pathSpec, Map parameters) { registerFilter(filterClass, pathSpec, EnumSet.of(DispatcherType.REQUEST), parameters); } @Override public void registerFilter(Class filterClass, String pathSpec, EnumSet dispatches) { registerFilter(filterClass, pathSpec, dispatches, null); } @Override public void registerFilter(Class filterClass, String pathSpec, EnumSet dispatches, Map parameters) { if (server == null) throw new IllegalStateException("Jetty has to be initialized before adding a servlet "); if (server.isStarted() || server.isStarting()) throw new IllegalStateException("Jetty cannot be started before adding a servlet"); FilterHolder holder = new FilterHolder(filterClass); if (parameters != null) { parameters.forEach(holder::setInitParameter); } appContext.addFilter(holder, pathSpec, dispatches); } @Override public void registerDataSource(DataSource ds, String jndiName) { try { Resource resource = new Resource(jndiName, ds); appContext.setAttribute(jndiName, resource); } catch (NamingException e) { throw new IllegalArgumentException("Unable to create naming data source entry with jndi name " + jndiName + "", e); } } @Override public List getRegisteredServlets() { List servlets = new ArrayList<>(); Arrays.stream(this.appContext.getServletHandler().getServlets()) .forEach(s -> servlets.add(new ServletWrapper(s.getName(), s.getContextPath()))); return servlets; } @Override public void registerResource(Object o, String jndiName) { try { Resource resource = new Resource(jndiName, o); appContext.setAttribute(jndiName, resource); } catch (NamingException e) { throw new IllegalArgumentException("Unable to create naming resource entry with jndi name " + jndiName + "", e); } } @Override public void registerTransactionManager(UserTransaction userTransaction) { try { new Transaction(userTransaction); } catch (NamingException e) { throw new IllegalArgumentException("Unable to create transaction manager", e); } } private JettyFactory createJettyFactory() { return new JettyFactory(serverConfig); } private List createConfigurations() { List configurations = new ArrayList<>(); configurations.add(WebAppConfiguration.class.getName()); configurations.add(AnnotationConfiguration.class.getName()); configurations.add(WebInfConfiguration.class.getName()); configurations.add(WebXmlConfiguration.class.getName()); configurations.add(MetaInfConfiguration.class.getName()); configurations.add(FragmentConfiguration.class.getName()); configurations.add(JettyWebXmlConfiguration.class.getName()); configurations.add(EnvConfiguration.class.getName()); configurations.add(PlusConfiguration.class.getName()); return configurations; } } ================================================ FILE: servlet/jetty/src/main/resources/META-INF/services/com.kumuluz.ee.common.KumuluzServer ================================================ com.kumuluz.ee.jetty.JettyServletServer ================================================ FILE: servlet/pom.xml ================================================ kumuluzee com.kumuluz.ee 4.2.0-SNAPSHOT 4.0.0 pom jetty KumuluzEE Servlet KumuluzEE servlet server component kumuluzee-servlet ================================================ FILE: settings.xml ================================================ ossrh ${env.OSSRH_USERNAME} ${env.OSSRH_PASSWORD} ossrh true 8DCC0AFC ${env.GPG_PASSPHRASE} sonatype-snapshots Sonatype Snapshots https://oss.sonatype.org/content/repositories/snapshots false true ================================================ FILE: tools/loader/pom.xml ================================================ kumuluzee-tools com.kumuluz.ee 4.2.0-SNAPSHOT 4.0.0 KumuluzEE Loader KumuluzEE custom class loader implementation kumuluzee-loader ================================================ FILE: tools/loader/src/main/java/com/kumuluz/ee/loader/EeBootLoader.java ================================================ /* * Copyright (c) 2014-2017 Kumuluz and/or its affiliates * and other contributors as indicated by the @author tags and * the contributor list. * * Licensed under the MIT License (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://opensource.org/licenses/MIT * * The software is provided "AS IS", WITHOUT WARRANTY OF ANY KIND, express or * implied, including but not limited to the warranties of merchantability, * fitness for a particular purpose and noninfringement. in no event shall the * authors or copyright holders be liable for any claim, damages or other * liability, whether in an action of contract, tort or otherwise, arising from, * out of or in connection with the software or the use or other dealings in the * software. See the License for the specific language governing permissions and * limitations under the License. */ package com.kumuluz.ee.loader; import com.kumuluz.ee.loader.exception.EeClassLoaderException; import java.util.MissingResourceException; import java.util.ResourceBundle; /** * @author Benjamin Kastelic * */ public class EeBootLoader { public static void main(String[] args) throws Throwable { try { ResourceBundle bootLoaderProperties = ResourceBundle.getBundle("META-INF/kumuluzee/boot-loader"); String mainClass = bootLoaderProperties.getString("main-class"); launch(args, mainClass); } catch (MissingResourceException e) { throw new EeClassLoaderException("KumuluzEE Boot Loader config properties are malformed or missing.", e); } } /** * Start the boot procedure. * Use the {@link EeClassLoader} EeClassLoader to find, load and start the main class. */ private static void launch(String[] args, String mainClass) throws Throwable { EeClassLoader classLoader = new EeClassLoader(); classLoader.invokeMain(mainClass, args); } } ================================================ FILE: tools/loader/src/main/java/com/kumuluz/ee/loader/EeClassLoader.java ================================================ /* * Copyright (c) 2014-2017 Kumuluz and/or its affiliates * and other contributors as indicated by the @author tags and * the contributor list. * * Licensed under the MIT License (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://opensource.org/licenses/MIT * * The software is provided "AS IS", WITHOUT WARRANTY OF ANY KIND, express or * implied, including but not limited to the warranties of merchantability, * fitness for a particular purpose and noninfringement. in no event shall the * authors or copyright holders be liable for any claim, damages or other * liability, whether in an action of contract, tort or otherwise, arising from, * out of or in connection with the software or the use or other dealings in the * software. See the License for the specific language governing permissions and * limitations under the License. */ package com.kumuluz.ee.loader; import com.kumuluz.ee.loader.exception.EeClassLoaderException; import com.kumuluz.ee.loader.jar.FileInfo; import com.kumuluz.ee.loader.jar.JarEntryInfo; import com.kumuluz.ee.loader.jar.JarFileInfo; import java.io.*; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.net.URLDecoder; import java.security.CodeSource; import java.security.ProtectionDomain; import java.security.cert.Certificate; import java.util.*; import java.util.jar.JarEntry; import java.util.jar.JarFile; import java.util.logging.Logger; import java.util.regex.Pattern; import java.util.stream.Collectors; import java.util.zip.ZipFile; /** * @author Benjamin Kastelic * @since 2.4.0 */ public class EeClassLoader extends ClassLoader { /** * Directory name for temporary files. */ private static final String TMP_DIRECTORY = "tmp/EeClassLoader"; private Boolean DEBUG = false; private File tempDir; private List jarFiles; private List files; private Set deleteOnExit; private Map> classes; private JarFileInfo jarFileInfo; /** * Default constructor. * Defines system class loader as a parent class loader. */ public EeClassLoader() { this(ClassLoader.getSystemClassLoader()); } /** * Constructor. */ public EeClassLoader(ClassLoader parent) { super(parent); String debugString = System.getProperty("com.kumuluz.ee.loader.debug"); if (debugString != null) { DEBUG = Boolean.valueOf(debugString); } long startTime = System.currentTimeMillis(); debug("Initialising KumuluzEE classloader"); classes = new HashMap<>(); jarFiles = Collections.synchronizedList(new ArrayList<>()); files = Collections.synchronizedList(new ArrayList<>()); deleteOnExit = new HashSet<>(); String mainJarURLString; ProtectionDomain protectionDomain = getClass().getProtectionDomain(); CodeSource codeSource = protectionDomain.getCodeSource(); URL mainJarURL = codeSource.getLocation(); String protocol = mainJarURL.getProtocol(); // Decoding required for 'space char' in URL: // URL.getFile() returns "/C:/my%20dir/MyApp.jar" for "/C:/my dir/MyApp.jar" try { mainJarURLString = URLDecoder.decode(mainJarURL.getFile(), "UTF-8"); } catch (UnsupportedEncodingException e) { String msg = String.format("Failed to decode URL: %s %s", mainJarURL, e.toString()); throw new EeClassLoaderException(msg, e); } File mainJarFile = new File(mainJarURLString); try { jarFileInfo = new JarFileInfo(new JarFile(mainJarFile, true, ZipFile.OPEN_READ, JarFile.runtimeVersion()), mainJarFile.getName(), null, protectionDomain, null); debug(String.format("Loading from main JAR: '%s' PROTOCOL: '%s'", mainJarURLString, protocol)); } catch (IOException e) { String msg = String.format("Not a JAR: %s %s", mainJarURLString, e.toString()); throw new EeClassLoaderException(msg, e); } // load main JAR: try { // start recursive JAR loading extractMainJar(jarFileInfo); loadJar(jarFileInfo); } catch (Exception e) { String msg = String.format("Not a valid URL: %s %s", mainJarURL, e.toString()); throw new EeClassLoaderException(msg, e); } debug(String.format("Initialised KumuluzEE classloader @%dms", System.currentTimeMillis() - startTime)); } private void createTempDirectory() throws URISyntaxException { // Create temp directory for classpath initialization if (tempDir == null) { ProtectionDomain protectionDomain = getClass().getProtectionDomain(); CodeSource codeSource = protectionDomain.getCodeSource(); URI location = (codeSource == null ? null : codeSource.getLocation().toURI()); String path = (location == null ? null : location.getSchemeSpecificPart()); if (path == null) { throw new IllegalStateException("Unable to determine code source archive"); } File jarDir = new File(path); String jarFolder = jarDir.getParentFile().getPath(); File dir = new File(jarFolder, TMP_DIRECTORY); if (!dir.exists()) { dir.mkdirs(); } dir.deleteOnExit(); chmod777(dir); // Unix - allow temp directory RW access to all users. if (!dir.exists() || !dir.isDirectory()) { throw new EeClassLoaderException("Cannot create temp directory " + dir.getAbsolutePath()); } tempDir = dir; } } private File createFile(JarEntry jarEntry, InputStream is) throws EeClassLoaderException { File tmpFile = null; try { if (jarEntry.isDirectory()) { tmpFile = new File(tempDir + File.separator + jarEntry); tmpFile.mkdirs(); tmpFile.deleteOnExit(); chmod777(tmpFile); return tmpFile; } else { String fileName = jarEntry.getName(); File tempDir = this.tempDir; int lastPathIndex = jarEntry.getName().lastIndexOf("/"); if (lastPathIndex > -1) { String dirPath = jarEntry.getName().substring(0, lastPathIndex); tempDir = new File(tempDir.getPath() + File.separator + dirPath); tempDir.mkdirs(); tempDir.deleteOnExit(); chmod777(tempDir); fileName = fileName.substring(lastPathIndex + 1); } tmpFile = new File(tempDir + File.separator + fileName); tmpFile.deleteOnExit(); chmod777(tmpFile); // Unix - allow temp file deletion by any user BufferedOutputStream os = new BufferedOutputStream(new FileOutputStream(tmpFile)); while(is.available() > 0) { os.write(is.read()); } os.close(); return tmpFile; } } catch (IOException e) { throw new EeClassLoaderException(String.format("Cannot create file '%s' for %s", tmpFile, jarEntry), e); } } private File createJarFile(JarEntryInfo jarEntryInfo) throws EeClassLoaderException { File tmpFile = null; try { tmpFile = new File(tempDir.getPath() + File.separator + jarEntryInfo.getName()); tmpFile.deleteOnExit(); chmod777(tmpFile); // Unix - allow temp file deletion by any user byte[] bytes = jarEntryInfo.getJarBytes(); BufferedOutputStream os = new BufferedOutputStream(new FileOutputStream(tmpFile)); os.write(bytes); os.close(); return tmpFile; } catch (IOException e) { throw new EeClassLoaderException(String.format("Cannot create temp file '%s' for %s", tmpFile, jarEntryInfo.getJarEntry()), e); } } private void extractMainJar(JarFileInfo jarFileInfo) throws URISyntaxException { final String LIB_DIRECTORY = "lib/"; createTempDirectory(); jarFileInfo.getJarFile() .stream() .parallel() .filter(je -> !je.getName().toLowerCase().startsWith(LIB_DIRECTORY)) .forEach(je -> { try { JarEntryInfo jarEntryInfo = new JarEntryInfo(jarFileInfo, je); File tempFile = createFile(je, jarFileInfo.getJarFile().getInputStream(je)); debug(String.format("Loading inner JAR %s from temp file %s", jarEntryInfo.getJarEntry(), getFilenameForLog(tempFile))); files.add(new FileInfo(tempFile, je.getName())); } catch (IOException e) { throw new RuntimeException(String.format("Cannot load jar entries from jar %s", je.getName().toLowerCase()), e); } catch (EeClassLoaderException e) { throw new RuntimeException("ERROR on loading inner JAR: " + e.getMessageAll()); } }); } /** * Loads specified JAR. */ private void loadJar(final JarFileInfo jarFileInfo) { final String JAR_SUFFIX = ".jar"; jarFiles.add(jarFileInfo); jarFileInfo.getJarFile() .stream() .parallel() .filter(je -> !je.isDirectory() && je.getName().toLowerCase().endsWith(JAR_SUFFIX)) .forEach(je -> { try { JarEntryInfo jarEntryInfo = new JarEntryInfo(jarFileInfo, je); File tempFile = createJarFile(jarEntryInfo); debug(String.format("Loading inner JAR %s from temp file %s", jarEntryInfo.getJarEntry(), getFilenameForLog(tempFile))); // Construct ProtectionDomain for this inner JAR: URL url = tempFile.toURI().toURL(); ProtectionDomain pdParent = jarFileInfo.getProtectionDomain(); // 'csParent' is never null: top JAR has it, classloader creates it for child JAR: CodeSource csParent = pdParent.getCodeSource(); Certificate[] certParent = csParent.getCertificates(); CodeSource csChild = certParent == null ? new CodeSource(url, csParent.getCodeSigners()) : new CodeSource(url, certParent); ProtectionDomain pdChild = new ProtectionDomain(csChild, pdParent.getPermissions(), pdParent.getClassLoader(), pdParent.getPrincipals()); loadJar(new JarFileInfo(new JarFile(tempFile, true, ZipFile.OPEN_READ, JarFile.runtimeVersion()), jarEntryInfo.getName(), jarFileInfo, pdChild, tempFile)); } catch (IOException e) { throw new RuntimeException(String.format("Cannot load jar entries from jar %s", je.getName().toLowerCase()), e); } catch (EeClassLoaderException e) { throw new RuntimeException("ERROR on loading inner JAR: " + e.getMessageAll()); } }); } private JarEntryInfo findJarEntry(String name) { for (JarFileInfo jarFileInfo : jarFiles) { JarFile jarFile = jarFileInfo.getJarFile(); JarEntry jarEntry = jarFile.getJarEntry(name); if (jarEntry != null) { return new JarEntryInfo(jarFileInfo, jarEntry); } } return null; } private URL findFile(String name) { for (FileInfo fileInfo : files) { if (fileInfo.getSimpleName().equals(name)) { try { return fileInfo.getFile().toURI().toURL(); } catch (Exception e) { // ignore } } } return null; } private List findJarEntries(String name) { List jarEntryInfoList = new ArrayList<>(); for (JarFileInfo jarFileInfo : jarFiles) { JarFile jarFile = jarFileInfo.getJarFile(); JarEntry jarEntry = jarFile.getJarEntry(name); if (jarEntry != null) { jarEntryInfoList.add(new JarEntryInfo(jarFileInfo, jarEntry)); } } return jarEntryInfoList; } private List findFiles(String name) { List urlList = new ArrayList<>(); for (FileInfo fileInfo : files) { if (fileInfo.getSimpleName().equals(name)) { try { URL fileUrl = fileInfo.getFile().toURI().toURL(); urlList.add(fileUrl); } catch (Exception e) { // ignore } } } return urlList; } /** * Finds native library entry. * * @param libraryName Library name. For example for the library name "Native" * - Windows returns entry "Native.dll" * - Linux returns entry "libNative.so" * - Mac returns entry "libNative.jnilib" or "libNative.dylib" * (depending on Apple or Oracle JDK and/or JDK version) * @return Native library entry. */ private JarEntryInfo findJarNativeEntry(String libraryName) { String name = System.mapLibraryName(libraryName); for (JarFileInfo jarFileInfo : jarFiles) { JarFile jarFile = jarFileInfo.getJarFile(); Enumeration entries = jarFile.entries(); while (entries.hasMoreElements()) { JarEntry jarEntry = entries.nextElement(); if (jarEntry.isDirectory()) { continue; } // Example: name is "Native.dll" String jarEntryName = jarEntry.getName(); // "Native.dll" or "abc/xyz/Native.dll" // name "Native.dll" could be found, for example // - in the path: abc/Native.dll/xyz/my.dll <-- do not load this one! // - in the partial name: abc/aNative.dll <-- do not load this one! String[] token = jarEntryName.split("/"); // the last token is library name if (token.length > 0 && token[token.length - 1].equals(name)) { debug(String.format("Loading native library '%s' found as '%s' in JAR %s", libraryName, jarEntryName, jarFileInfo.getSimpleName())); return new JarEntryInfo(jarFileInfo, jarEntry); } } } return null; } /** * Loads class from a JAR and searches for all jar-in-jar. */ private Class findJarClass(String className) throws EeClassLoaderException { Class clazz = classes.get(className); if (clazz != null) { return clazz; } // Char '/' works for Win32 and Unix. String fullClassName = className.replace('.', '/') + ".class"; JarEntryInfo jarEntryInfo = findJarEntry(fullClassName); String jarSimpleName = null; if (jarEntryInfo != null) { jarSimpleName = jarEntryInfo.getJarFileInfo().getSimpleName(); definePackage(className, jarEntryInfo); byte[] bytes = jarEntryInfo.getJarBytes(); try { clazz = defineClass(className, bytes, 0, bytes.length, jarEntryInfo.getJarFileInfo().getProtectionDomain()); } catch (ClassFormatError e) { throw new EeClassLoaderException(null, e); } } if (clazz == null) { throw new EeClassLoaderException(className); } classes.put(className, clazz); debug(String.format("Loaded %s by %s from JAR %s", className, getClass().getName(), jarSimpleName)); return clazz; } /** * Checks how the application was loaded: from JAR or file system. */ private boolean isLaunchedFromJar() { return jarFiles != null && !jarFiles.isEmpty(); } /** * Invokes main() method on class with provided parameters. */ public void invokeMain(String className, String[] args) throws Throwable { Class clazz = loadClass(className); debug(String.format("Launch: %s.main(); Loader: %s", className, clazz.getClassLoader())); Method method = clazz.getMethod("main", String[].class); if (method == null) { throw new NoSuchMethodException("The main() method in class \"" + className + "\" not found."); } try { method.invoke(null, (Object)args); } catch (InvocationTargetException e) { throw e.getTargetException(); } } @Override protected synchronized Class loadClass(String className, boolean bResolve) throws ClassNotFoundException { debug(String.format("LOADING %s (resolve=%b)", className, bResolve)); Thread.currentThread().setContextClassLoader(this); // !!! Class clazz = null; try { // Step 1. This class is already loaded by system classloader. if (getClass().getName().equals(className)) { return EeClassLoader.class; } // Step 2. Already loaded class. clazz = findLoadedClass(className); if (clazz != null) { debug(String.format("Class %s already loaded", className)); return clazz; } // Step 3. Load from JAR. if (isLaunchedFromJar()) { try { clazz = findJarClass(className); // Do not simplify! See "finally"! return clazz; } catch (EeClassLoaderException e) { if (e.getCause() == null) { debug(String.format("Not found %s in JAR by %s: %s", className, getClass().getName(), e.getMessage())); } else { debug(String.format("Error loading %s in JAR by %s: %s", className, getClass().getName(), e.getCause())); } // keep looking... } } // Step 4. Load by parent (usually system) class loader. try { ClassLoader classLoader = getParent(); clazz = classLoader.loadClass(className); debug(String.format("Loaded %s by %s", className, classLoader.getClass().getName())); return clazz; } catch (ClassNotFoundException e) { // Ignore } // Nothing else to try ... throw new ClassNotFoundException("Failure to load: " + className); } finally { if (clazz != null && bResolve) { resolveClass(clazz); } } } @Override protected Class findClass(String s) throws ClassNotFoundException { return loadClass(s); // same as loadClass(s, false) } @Override protected URL findResource(String name) { debug(String.format("findResource: %s", name)); if (isLaunchedFromJar()) { URL file = findFile(normalizeResourceName(name)); if (file != null) { debug(String.format("found resource: %s", file)); return file; } JarEntryInfo inf = findJarEntry(normalizeResourceName(name)); if (inf != null) { URL url = inf.getURL(); debug(String.format("found resource: %s", url)); return url; } debug(String.format("not found resource: %s", name)); return null; } return super.findResource(name); } @Override public Enumeration getResources(String name) throws IOException { return findResources(name); } @Override public Enumeration findResources(String name) throws IOException { debug(String.format("getResources: %s", name)); if (isLaunchedFromJar()) { List fileUrls = findFiles(normalizeResourceName(name)); List jarEntries = findJarEntries(normalizeResourceName(name)); List urls = new ArrayList<>(fileUrls); for (JarEntryInfo jarEntryInfo : jarEntries) { if (jarEntryInfo.getJarFileInfo().equals(this.jarFileInfo)) { continue; } URL url = jarEntryInfo.getURL(); if (url != null) { urls.add(url); } } return Collections.enumeration(urls); } return super.findResources(name); } @Override protected String findLibrary(String name) { debug(String.format("findLibrary: %s", name)); if (isLaunchedFromJar()) { JarEntryInfo jarEntryInfo = findJarNativeEntry(name); if (jarEntryInfo != null) { try { File file = createJarFile(jarEntryInfo); debug(String.format("Loading native library %s from temp file %s", jarEntryInfo.getJarEntry(), getFilenameForLog(file))); deleteOnExit.add(file); return file.getAbsolutePath(); } catch (EeClassLoaderException e) { debug(String.format("Failure to load native library %s: %s", name, e.toString())); } } return null; } return super.findLibrary(name); } public List getJarFilesLocations(List filenames) { List locations = new ArrayList<>(); for (String filename : filenames) { // try exact match JarFileInfo jarLib = jarFiles.stream() .filter(jfi -> jfi.getSimpleName().contains("!")) .filter(jfi -> jfi.getSimpleName().split("!")[1].equals("lib_" + filename)) .findFirst().orElse(null); if (jarLib == null) { // try artifact name search only String regex = "^.*!lib_" + Pattern.quote(filename) + "-[^/]+\\.jar$"; List matchedFiles = jarFiles.stream().filter(jfi -> jfi.getSimpleName().matches(regex)) .collect(Collectors.toList()); if (matchedFiles.size() == 1) { jarLib = matchedFiles.get(0); } else if (matchedFiles.size() > 1) { // multiple matches, select one with the shortest name jarLib = matchedFiles.stream().min(Comparator.comparingInt(jfi -> jfi.getSimpleName().length())) .orElseThrow(() -> new RuntimeException("Could not find library with shortest name")); // logging should be initialized by now Logger log = Logger.getLogger(EeClassLoader.class.getSimpleName()); log.severe(String.format("Multiple jar files with artifact name similar to '%s' found ([%s]). " + "Using %s. Consider matching by full name.", filename, matchedFiles.stream().map(jfi -> jfi.getSimpleName().split("!")[1].substring(4)) .collect(Collectors.joining(", ")), jarLib.getSimpleName().split("!")[1].substring(4)) ); } // else exception is thrown because jarLib == null } if (jarLib == null) { throw new IllegalArgumentException("Could not locate library " + filename); } locations.add(jarLib.getFileDeleteOnExit().getAbsolutePath()); } return Collections.unmodifiableList(locations); } /** * The default ClassLoader.defineClass() does not create package * for the loaded class and leaves it null. Each package referenced by this * class loader must be created only once before the * ClassLoader.defineClass() call. * The base class ClassLoader keeps cache with created packages * for reuse. * * @param className class to load. * @throws IllegalArgumentException * If package name duplicates an existing package either in this * class loader or one of its ancestors. */ private void definePackage(String className, JarEntryInfo jarEntryInfo) throws IllegalArgumentException { int index = className.lastIndexOf('.'); String packageName = index > 0 ? className.substring(0, index) : ""; if (getPackage(packageName) == null) { JarFileInfo jarFileInfo = jarEntryInfo.getJarFileInfo(); definePackage( packageName, jarFileInfo.getSpecificationTitle(), jarFileInfo.getSpecificationVersion(), jarFileInfo.getSpecificationVendor(), jarFileInfo.getImplementationTitle(), jarFileInfo.getImplementationVersion(), jarFileInfo.getImplementationVendor(), jarFileInfo.getSealURL() ); } } /** * The system class loader could load resources defined as * "com/abc/Foo.txt" or "com\abc\Foo.txt". * This method converts path with '\' to default '/' JAR delimiter. * * @param name resource name including path. * @return normalized resource name. */ private String normalizeResourceName(String name) { return name.replace('\\', '/'); } private void chmod777(File file) { file.setReadable(true, false); file.setWritable(true, false); file.setExecutable(true, false); // Unix: allow content for dir, redundant for file } private String getFilenameForLog(File file) { try { // In form "C:\Documents and Settings\..." return file.getCanonicalPath(); } catch (IOException e) { // In form "C:\DOCUME~1\..." return file.getAbsolutePath(); } } private void debug(String msg) { if (DEBUG) { System.out.println(msg); } } } ================================================ FILE: tools/loader/src/main/java/com/kumuluz/ee/loader/exception/EeClassLoaderException.java ================================================ /* * Copyright (c) 2014-2017 Kumuluz and/or its affiliates * and other contributors as indicated by the @author tags and * the contributor list. * * Licensed under the MIT License (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://opensource.org/licenses/MIT * * The software is provided "AS IS", WITHOUT WARRANTY OF ANY KIND, express or * implied, including but not limited to the warranties of merchantability, * fitness for a particular purpose and noninfringement. in no event shall the * authors or copyright holders be liable for any claim, damages or other * liability, whether in an action of contract, tort or otherwise, arising from, * out of or in connection with the software or the use or other dealings in the * software. See the License for the specific language governing permissions and * limitations under the License. */ package com.kumuluz.ee.loader.exception; /** * @author Benjamin Kastelic * @since 2.4.0 */ public class EeClassLoaderException extends RuntimeException { public EeClassLoaderException(String message) { super(message); } public EeClassLoaderException(String message, Throwable cause) { super(message, cause); } public String getMessageAll() { StringBuilder stringBuilder = new StringBuilder(); for (Throwable e = this; e != null; e = e.getCause()) { if (stringBuilder.length() > 0) { stringBuilder.append(" / "); } String message = e.getMessage(); if (message == null || message.length() == 0) { message = e.getClass().getSimpleName(); } stringBuilder.append(message); } return stringBuilder.toString(); } } ================================================ FILE: tools/loader/src/main/java/com/kumuluz/ee/loader/jar/FileInfo.java ================================================ /* * Copyright (c) 2014-2017 Kumuluz and/or its affiliates * and other contributors as indicated by the @author tags and * the contributor list. * * Licensed under the MIT License (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://opensource.org/licenses/MIT * * The software is provided "AS IS", WITHOUT WARRANTY OF ANY KIND, express or * implied, including but not limited to the warranties of merchantability, * fitness for a particular purpose and noninfringement. in no event shall the * authors or copyright holders be liable for any claim, damages or other * liability, whether in an action of contract, tort or otherwise, arising from, * out of or in connection with the software or the use or other dealings in the * software. See the License for the specific language governing permissions and * limitations under the License. */ package com.kumuluz.ee.loader.jar; import java.io.File; /** * @author Benjamin Kastelic, Sunesis ltd. * @since 1.0.0 */ public class FileInfo { private File file; private String simpleName; public FileInfo(File file, String simpleName) { this.simpleName = simpleName; if (this.simpleName.endsWith("/") && this.simpleName.length() > 1) { this.simpleName = this.simpleName.substring(0 ,this.simpleName.length() - 1); } this.file = file; } public File getFile() { return file; } public void setFile(File file) { this.file = file; } public String getSimpleName() { return simpleName; } public void setSimpleName(String simpleName) { this.simpleName = simpleName; } } ================================================ FILE: tools/loader/src/main/java/com/kumuluz/ee/loader/jar/JarEntryInfo.java ================================================ /* * Copyright (c) 2014-2017 Kumuluz and/or its affiliates * and other contributors as indicated by the @author tags and * the contributor list. * * Licensed under the MIT License (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://opensource.org/licenses/MIT * * The software is provided "AS IS", WITHOUT WARRANTY OF ANY KIND, express or * implied, including but not limited to the warranties of merchantability, * fitness for a particular purpose and noninfringement. in no event shall the * authors or copyright holders be liable for any claim, damages or other * liability, whether in an action of contract, tort or otherwise, arising from, * out of or in connection with the software or the use or other dealings in the * software. See the License for the specific language governing permissions and * limitations under the License. */ package com.kumuluz.ee.loader.jar; import com.kumuluz.ee.loader.exception.EeClassLoaderException; import java.io.DataInputStream; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.net.MalformedURLException; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.util.jar.JarEntry; /** * Class with JAR entry information. Keeps JAR file and entry object. * * @author Benjamin Kastelic * @since 2.4.0 */ public class JarEntryInfo { private JarFileInfo jarFileInfo; private JarEntry jarEntry; public JarEntryInfo(JarFileInfo jarFileInfo, JarEntry jarEntry) { this.jarFileInfo = jarFileInfo; this.jarEntry = jarEntry; } public JarFileInfo getJarFileInfo() { return jarFileInfo; } public void setJarFileInfo(JarFileInfo jarFileInfo) { this.jarFileInfo = jarFileInfo; } public JarEntry getJarEntry() { return jarEntry; } public void setJarEntry(JarEntry jarEntry) { this.jarEntry = jarEntry; } public URL getURL() { // used in findResource() and findResources() try { String jarFileName = new File(jarFileInfo.getJarFile().getName()).toURI().toString(); URI uri = new URI("jar:" + jarFileName + "!/" + jarEntry); return uri.toURL(); } catch (URISyntaxException | MalformedURLException e) { return null; } } public String getName() { // used in createTempFile() and loadJar() return jarEntry.getName().replace('/', '_'); } /** * Read JAR entry and return byte array of this JAR entry. */ public byte[] getJarBytes() throws EeClassLoaderException { DataInputStream dataInputStream = null; byte[] bytes; try { long jarEntrySize = jarEntry.getSize(); if (jarEntrySize <= 0 || jarEntrySize >= Integer.MAX_VALUE) { throw new EeClassLoaderException("Invalid size " + jarEntrySize + " for entry " + jarEntry); } bytes = new byte[(int) jarEntrySize]; InputStream inputStream = jarFileInfo.getJarFile().getInputStream(jarEntry); dataInputStream = new DataInputStream(inputStream); dataInputStream.readFully(bytes); } catch (IOException e) { throw new EeClassLoaderException(null, e); } finally { if (dataInputStream != null) { try { dataInputStream.close(); } catch (IOException e) { // Ignore } } } return bytes; } @Override public String toString() { return "JAR: " + jarFileInfo.getJarFile().getName() + " ENTRY: " + jarEntry; } } ================================================ FILE: tools/loader/src/main/java/com/kumuluz/ee/loader/jar/JarFileInfo.java ================================================ /* * Copyright (c) 2014-2017 Kumuluz and/or its affiliates * and other contributors as indicated by the @author tags and * the contributor list. * * Licensed under the MIT License (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://opensource.org/licenses/MIT * * The software is provided "AS IS", WITHOUT WARRANTY OF ANY KIND, express or * implied, including but not limited to the warranties of merchantability, * fitness for a particular purpose and noninfringement. in no event shall the * authors or copyright holders be liable for any claim, damages or other * liability, whether in an action of contract, tort or otherwise, arising from, * out of or in connection with the software or the use or other dealings in the * software. See the License for the specific language governing permissions and * limitations under the License. */ package com.kumuluz.ee.loader.jar; import java.io.File; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import java.security.ProtectionDomain; import java.util.jar.Attributes; import java.util.jar.JarFile; import java.util.jar.Manifest; /** * Class that holds JAR file information. * * @author Benjamin Kastelic * @since 2.4.0 */ public class JarFileInfo { private JarFile jarFile; // this is the essence of JarFileInfo wrapper private String simpleName; // accumulated for logging like: "topJar!childJar!kidJar" private File fileDeleteOnExit; private Manifest manifest; // required for package creation private ProtectionDomain protectionDomain; /** * @param jarFile * Never null. * @param simpleName * Used for logging. Never null. * @param jarFileParent * Used to make simpleName for logging. Null for top level JAR. * @param fileDeleteOnExit * Used only to delete temporary file on exit. * Could be null if not required to delete on exit (top level JAR) */ public JarFileInfo(JarFile jarFile, String simpleName, JarFileInfo jarFileParent, ProtectionDomain protectionDomain, File fileDeleteOnExit) { this.simpleName = (jarFileParent == null ? "" : jarFileParent.simpleName + "!") + simpleName; this.jarFile = jarFile; this.protectionDomain = protectionDomain; this.fileDeleteOnExit = fileDeleteOnExit; try { this.manifest = jarFile.getManifest(); // 'null' if META-INF directory is missing } catch (IOException e) { // Ignore and create blank manifest } if (this.manifest == null) { this.manifest = new Manifest(); } } public String getSpecificationTitle() { return manifest.getMainAttributes().getValue(Attributes.Name.SPECIFICATION_TITLE); } public String getSpecificationVersion() { return manifest.getMainAttributes().getValue(Attributes.Name.SPECIFICATION_VERSION); } public String getSpecificationVendor() { return manifest.getMainAttributes().getValue(Attributes.Name.SPECIFICATION_VENDOR); } public String getImplementationTitle() { return manifest.getMainAttributes().getValue(Attributes.Name.IMPLEMENTATION_TITLE); } public String getImplementationVersion() { return manifest.getMainAttributes().getValue(Attributes.Name.IMPLEMENTATION_VERSION); } public String getImplementationVendor() { return manifest.getMainAttributes().getValue(Attributes.Name.IMPLEMENTATION_VENDOR); } public URL getSealURL() { String seal = manifest.getMainAttributes().getValue(Attributes.Name.SEALED); if (seal != null) { try { return new URL(seal); } catch (MalformedURLException e) { // Ignore } } return null; } public JarFile getJarFile() { return jarFile; } public void setJarFile(JarFile jarFile) { this.jarFile = jarFile; } public String getSimpleName() { return simpleName; } public void setSimpleName(String simpleName) { this.simpleName = simpleName; } public File getFileDeleteOnExit() { return fileDeleteOnExit; } public void setFileDeleteOnExit(File fileDeleteOnExit) { this.fileDeleteOnExit = fileDeleteOnExit; } public Manifest getManifest() { return manifest; } public void setManifest(Manifest manifest) { this.manifest = manifest; } public ProtectionDomain getProtectionDomain() { return protectionDomain; } public void setProtectionDomain(ProtectionDomain protectionDomain) { this.protectionDomain = protectionDomain; } } ================================================ FILE: tools/maven-plugin/README.md ================================================ # KumuluzEE Maven Plugin > KumuluzEE Maven Plugin for the Kumuluz EE microservice framework TODO - description ## Usage Include the plugin in your project: ```xml com.kumuluz.ee kumuluzee-maven-plugin ${kumuluzee.version} ``` ### Goals * __kumuluzee:copy-dependencies__ Copy dependencies and prepare for execution in an exploded class and dependency runtime. * __kumuluzee:repackage__ Repackages existing JAR archives so that they can be executed from the command line using `java -jar`. ###### Parameters * __finalName__ Final name of the generated "uber" JAR. __Default value is__: `${project.build.finalName}` or `${project.artifactId}-${project.version}` * __outputDirectory__ Directory containing the generated JAR. __Default value is__: `${project.build.directory}` * __kumuluzee:run__ Run the application in an exploded class and dependency runtime. ================================================ FILE: tools/maven-plugin/pom.xml ================================================ kumuluzee-tools com.kumuluz.ee 4.2.0-SNAPSHOT 4.0.0 maven-plugin KumuluzEE Maven Plugin KumuluzEE maven plugin for building single uber jars kumuluzee-maven-plugin false com.kumuluz.ee kumuluzee-loader provided org.apache.maven maven-plugin-api provided org.apache.maven.plugin-tools maven-plugin-annotations provided org.twdata.maven mojo-executor com.fasterxml.jackson.core jackson-databind org.apache.commons commons-lang3 3.6 ${project.build.directory}/generated-resources/loader src/main/resources true org.apache.maven.plugins maven-dependency-plugin ${maven-dependency-plugin.version} include-loader generate-resources copy ${kumuluzee.plugin.test.skip} com.kumuluz.ee kumuluzee-loader ${project.version} kumuluzee-loader.jar ${project.build.directory}/generated-resources/loader/META-INF/loader org.apache.maven.plugins maven-plugin-plugin ${maven-plugin-plugin.version} true mojo-descriptor descriptor help-goal helpmojo ================================================ FILE: tools/maven-plugin/src/main/java/com/kumuluz/ee/maven/plugin/AbstractCopyDependenciesMojo.java ================================================ /* * Copyright (c) 2014-2017 Kumuluz and/or its affiliates * and other contributors as indicated by the @author tags and * the contributor list. * * Licensed under the MIT License (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://opensource.org/licenses/MIT * * The software is provided "AS IS", WITHOUT WARRANTY OF ANY KIND, express or * implied, including but not limited to the warranties of merchantability, * fitness for a particular purpose and noninfringement. in no event shall the * authors or copyright holders be liable for any claim, damages or other * liability, whether in an action of contract, tort or otherwise, arising from, * out of or in connection with the software or the use or other dealings in the * software. See the License for the specific language governing permissions and * limitations under the License. */ package com.kumuluz.ee.maven.plugin; import org.apache.maven.execution.MavenSession; import org.apache.maven.plugin.AbstractMojo; import org.apache.maven.plugin.BuildPluginManager; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugins.annotations.Component; import org.apache.maven.plugins.annotations.Parameter; import org.apache.maven.project.MavenProject; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import static org.twdata.maven.mojoexecutor.MojoExecutor.*; /** * @author Benjamin Kastelic * @since 2.4.0 */ public abstract class AbstractCopyDependenciesMojo extends AbstractMojo { @Parameter(defaultValue = "${project}", readonly = true, required = true) protected MavenProject project; @Parameter(defaultValue = "${session}", readonly = true, required = true) protected MavenSession session; @Component protected BuildPluginManager buildPluginManager; @Parameter private String webappDir; private String outputDirectory; private String baseDirectory; protected void copyDependencies() throws MojoExecutionException { copyDependencies(null); } /** * Copies dependencies to /target/dependency or to target/{outputSubdirectory} if the outputSubdirectory parameter is * provided */ protected void copyDependencies(String outputSubdirectory) throws MojoExecutionException { outputDirectory = project.getBuild().getDirectory(); baseDirectory = project.getBasedir().getAbsolutePath(); String outputDirectory = outputSubdirectory == null ? this.outputDirectory + "/dependency" : this.outputDirectory + "/" + outputSubdirectory; executeMojo( plugin( groupId("org.apache.maven.plugins"), artifactId("maven-dependency-plugin"), version(MojoConstants.MAVEN_DEPENDENCY_PLUGIN_VERSION) ), goal("copy-dependencies"), configuration( element("includeScope", "runtime"), element("overWriteSnapshots", "true"), element("excludeArtifactIds", "kumuluzee-loader"), element("outputDirectory", outputDirectory) ), executionEnvironment(project, session, buildPluginManager) ); copyOrCreateWebapp(); } private void copyOrCreateWebapp() throws MojoExecutionException { boolean webappExists = false; // search for target/classes/webapp Path outputWebApp = Paths.get(outputDirectory, "classes/webapp"); if (Files.isDirectory(outputWebApp)) { webappExists = true; } // search for src/main/webapp if (!webappExists) { Path sourceWebApp = webappDir == null ? Paths.get(baseDirectory, "src", "main", "webapp") : Paths.get(baseDirectory, webappDir); getLog().info(sourceWebApp.toAbsolutePath().toString()); if (Files.isDirectory(sourceWebApp)) { String sourceWebAppDir = webappDir == null ? "src/main/webapp" : webappDir; executeMojo( plugin( groupId("org.apache.maven.plugins"), artifactId("maven-resources-plugin"), version(MojoConstants.MAVEN_RESOURCE_PLUGIN_VERSION) ), goal("copy-resources"), configuration( element(name("outputDirectory"), "${basedir}/target/classes/webapp"), element(name("resources"), element(name("resource"), element(name("directory"), sourceWebAppDir) )) ), executionEnvironment(project, session, buildPluginManager) ); // check if webapp resources were successfully copied if (Files.isDirectory(outputWebApp)) { webappExists = true; } } } if (!webappExists) { try { Files.createDirectories(outputWebApp); } catch (IOException e) { throw new MojoExecutionException("Could not create the necessary `webapp` directory. Please check the target folder " + "permissions.", e); } } } } ================================================ FILE: tools/maven-plugin/src/main/java/com/kumuluz/ee/maven/plugin/AbstractPackageMojo.java ================================================ /* * Copyright (c) 2014-2017 Kumuluz and/or its affiliates * and other contributors as indicated by the @author tags and * the contributor list. * * Licensed under the MIT License (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://opensource.org/licenses/MIT * * The software is provided "AS IS", WITHOUT WARRANTY OF ANY KIND, express or * implied, including but not limited to the warranties of merchantability, * fitness for a particular purpose and noninfringement. in no event shall the * authors or copyright holders be liable for any claim, damages or other * liability, whether in an action of contract, tort or otherwise, arising from, * out of or in connection with the software or the use or other dealings in the * software. See the License for the specific language governing permissions and * limitations under the License. */ package com.kumuluz.ee.maven.plugin; import org.apache.maven.execution.MavenSession; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugins.annotations.Parameter; import org.apache.maven.project.MavenProject; import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.net.URISyntaxException; import java.nio.charset.StandardCharsets; import java.nio.file.*; import java.security.CodeSource; import java.security.ProtectionDomain; import java.util.jar.JarFile; import java.util.zip.ZipFile; import static org.twdata.maven.mojoexecutor.MojoExecutor.*; /** * @author Benjamin Kastelic * @since 2.4.0 */ public abstract class AbstractPackageMojo extends AbstractCopyDependenciesMojo { private static final String LOADER_JAR = "META-INF/loader/kumuluzee-loader.jar"; private static final String TEMP_DIR_NAME_PREFIX = "kumuluzee-loader"; private static final String CLASS_SUFFIX = ".class"; @Parameter(defaultValue = "com.kumuluz.ee.EeApplication") private String mainClass; private String buildDirectory; private String outputDirectory; private String finalName; protected void repackage() throws MojoExecutionException { buildDirectory = project.getBuild().getDirectory(); outputDirectory = project.getBuild().getOutputDirectory(); finalName = project.getBuild().getFinalName(); checkPrecoditions(); copyDependencies("classes/lib"); unpackDependencies(); packageJar(); renameJars(); } private void checkPrecoditions() throws MojoExecutionException { getLog().info("Checking if project meets the preconditions."); // only jar packagins if allowed if (!project.getPackaging().toLowerCase().equals("jar")) { throw new MojoExecutionException("Only projects of \"jar\" packaging can be repackaged into an Uber JAR."); } } private void unpackDependencies() throws MojoExecutionException { getLog().info("Unpacking kumuluzee-loader dependency."); try { // get plugin JAR URI pluginJarURI = getPluginJarPath(); Path pluginJarFile = Paths.get(pluginJarURI); // explicit cast to ClassLoader null is required for Java 15 compilation FileSystem pluginJarFs = FileSystems.newFileSystem(pluginJarFile, (ClassLoader) null); Path loaderJarFile = pluginJarFs.getPath(LOADER_JAR); Path tmpJar = Files.createTempFile(TEMP_DIR_NAME_PREFIX, ".tmp"); Files.copy(loaderJarFile, tmpJar, StandardCopyOption.REPLACE_EXISTING); JarFile loaderJar = new JarFile(tmpJar.toFile(), true, ZipFile.OPEN_READ, JarFile.runtimeVersion()); loaderJar.stream().parallel() .filter(loaderJarEntry -> loaderJarEntry.getName().toLowerCase().endsWith(CLASS_SUFFIX)) .forEach(loaderJarEntry -> { try { Path outputPath = Paths.get(outputDirectory, loaderJarEntry.getName()); Path outputPathParent = outputPath.getParent(); if (outputPathParent != null) { Files.createDirectories(outputPathParent); } InputStream inputStream = loaderJar.getInputStream(loaderJarEntry); Files.copy(inputStream, outputPath, StandardCopyOption.REPLACE_EXISTING); inputStream.close(); } catch (IOException ignored) { } }); loaderJar.close(); Files.delete(tmpJar); // Create the boot loader config file Path loaderConf = Paths.get(outputDirectory, "META-INF", "kumuluzee", "boot-loader.properties"); Path loaderConfParent = loaderConf.getParent(); if (!Files.exists(loaderConfParent)) { Files.createDirectories(loaderConfParent); } String loaderConfContent = "main-class=" + mainClass; Files.write(loaderConf, loaderConfContent.getBytes(StandardCharsets.UTF_8)); } catch (IOException e) { throw new MojoExecutionException("Failed to unpack kumuluzee-loader dependency: " + e.getMessage() + "."); } } private URI getPluginJarPath() throws MojoExecutionException { try { ProtectionDomain protectionDomain = RepackageMojo.class.getProtectionDomain(); CodeSource codeSource = protectionDomain.getCodeSource(); if (codeSource == null) { throw new MojoExecutionException("Failed to retrieve plugin JAR file path. Unobtainable Code Source."); } return codeSource.getLocation().toURI(); } catch (URISyntaxException e) { throw new MojoExecutionException("Failed to retrieve plugin JAR file path.", e); } } private void packageJar() throws MojoExecutionException { // Execute maven-jar-plugin in a separate execution environment, in order not to pollute the current project with // attached artifact. Attached artifact will replace the current main artifact after rename, but reference in // project.getAttachedArtifacts() cannot be removed after it's been added by maven-jar-plugin. MavenProject projectClone = new MavenProject(project); MavenSession sessionClone = session.clone(); sessionClone.setCurrentProject(projectClone); executeMojo( plugin( groupId("org.apache.maven.plugins"), artifactId("maven-jar-plugin"), version(MojoConstants.MAVEN_JAR_PLUGIN_VERSION) ), goal("jar"), configuration( element("finalName", finalName), element("outputDirectory", buildDirectory), element("classifier", "uber"), element("forceCreation", "true"), element("archive", element("manifest", element("mainClass", "com.kumuluz.ee.loader.EeBootLoader") ) ) ), executionEnvironment(projectClone, sessionClone, buildPluginManager) ); } private void renameJars() throws MojoExecutionException { try { Path sourcePath1 = Paths.get(buildDirectory, finalName + ".jar"); getLog().info("Repackaging jar: " + sourcePath1.toAbsolutePath()); if (Files.exists(sourcePath1)) { Files.move( sourcePath1, sourcePath1.resolveSibling(finalName + ".jar.original"), StandardCopyOption.REPLACE_EXISTING ); } Path sourcePath2 = Paths.get(buildDirectory, finalName + "-uber.jar"); if (Files.exists(sourcePath2)) { Files.move( sourcePath2, sourcePath2.resolveSibling(finalName + ".jar"), StandardCopyOption.REPLACE_EXISTING ); } } catch (IOException e) { throw new MojoExecutionException("Unable to rename the final build artifact."); } } } ================================================ FILE: tools/maven-plugin/src/main/java/com/kumuluz/ee/maven/plugin/CopyDependenciesMojo.java ================================================ /* * Copyright (c) 2014-2017 Kumuluz and/or its affiliates * and other contributors as indicated by the @author tags and * the contributor list. * * Licensed under the MIT License (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://opensource.org/licenses/MIT * * The software is provided "AS IS", WITHOUT WARRANTY OF ANY KIND, express or * implied, including but not limited to the warranties of merchantability, * fitness for a particular purpose and noninfringement. in no event shall the * authors or copyright holders be liable for any claim, damages or other * liability, whether in an action of contract, tort or otherwise, arising from, * out of or in connection with the software or the use or other dealings in the * software. See the License for the specific language governing permissions and * limitations under the License. */ package com.kumuluz.ee.maven.plugin; import org.apache.maven.execution.MavenSession; import org.apache.maven.plugin.BuildPluginManager; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugins.annotations.*; import org.apache.maven.project.MavenProject; /** * Copy dependencies and prepare for execution in an exploded class and dependency runtime. * * @author Benjamin Kastelic * @since 2.4.0 */ @Mojo( name = "copy-dependencies", defaultPhase = LifecyclePhase.PACKAGE, requiresDependencyResolution = ResolutionScope.COMPILE_PLUS_RUNTIME, requiresDependencyCollection = ResolutionScope.COMPILE_PLUS_RUNTIME ) public class CopyDependenciesMojo extends AbstractCopyDependenciesMojo { @Override public void execute() throws MojoExecutionException { copyDependencies(); } } ================================================ FILE: tools/maven-plugin/src/main/java/com/kumuluz/ee/maven/plugin/MojoConstants.java ================================================ /* * Copyright (c) 2014-2017 Kumuluz and/or its affiliates * and other contributors as indicated by the @author tags and * the contributor list. * * Licensed under the MIT License (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://opensource.org/licenses/MIT * * The software is provided "AS IS", WITHOUT WARRANTY OF ANY KIND, express or * implied, including but not limited to the warranties of merchantability, * fitness for a particular purpose and noninfringement. in no event shall the * authors or copyright holders be liable for any claim, damages or other * liability, whether in an action of contract, tort or otherwise, arising from, * out of or in connection with the software or the use or other dealings in the * software. See the License for the specific language governing permissions and * limitations under the License. */ package com.kumuluz.ee.maven.plugin; import java.util.ResourceBundle; /** * @author Tilen Faganel * @since 2.4.0 */ public class MojoConstants { public static final String MAVEN_JAR_PLUGIN_VERSION = ResourceBundle.getBundle("META-INF/kumuluzee/plugin-versions").getString("maven-jar-plugin.version"); public static final String MAVEN_RESOURCE_PLUGIN_VERSION = ResourceBundle.getBundle("META-INF/kumuluzee/plugin-versions").getString("maven-resources-plugin.version"); public static final String MAVEN_DEPENDENCY_PLUGIN_VERSION = ResourceBundle.getBundle("META-INF/kumuluzee/plugin-versions").getString("maven-dependency-plugin.version"); } ================================================ FILE: tools/maven-plugin/src/main/java/com/kumuluz/ee/maven/plugin/RepackageMojo.java ================================================ /* * Copyright (c) 2014-2017 Kumuluz and/or its affiliates * and other contributors as indicated by the @author tags and * the contributor list. * * Licensed under the MIT License (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://opensource.org/licenses/MIT * * The software is provided "AS IS", WITHOUT WARRANTY OF ANY KIND, express or * implied, including but not limited to the warranties of merchantability, * fitness for a particular purpose and noninfringement. in no event shall the * authors or copyright holders be liable for any claim, damages or other * liability, whether in an action of contract, tort or otherwise, arising from, * out of or in connection with the software or the use or other dealings in the * software. See the License for the specific language governing permissions and * limitations under the License. */ package com.kumuluz.ee.maven.plugin; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.MojoFailureException; import org.apache.maven.plugins.annotations.LifecyclePhase; import org.apache.maven.plugins.annotations.Mojo; import org.apache.maven.plugins.annotations.ResolutionScope; /** * Repackages existing JAR archives so that they can be executed from the command line using {@literal java -jar}. * * @author Benjamin Kastelic * @since 2.4.0 */ @Mojo( name = "repackage", defaultPhase = LifecyclePhase.PACKAGE, threadSafe = true, requiresDependencyResolution = ResolutionScope.COMPILE_PLUS_RUNTIME, requiresDependencyCollection = ResolutionScope.COMPILE_PLUS_RUNTIME ) public class RepackageMojo extends AbstractPackageMojo { @Override public void execute() throws MojoExecutionException, MojoFailureException { repackage(); } } ================================================ FILE: tools/maven-plugin/src/main/java/com/kumuluz/ee/maven/plugin/RunExplodedMojo.java ================================================ /* * Copyright (c) 2014-2017 Kumuluz and/or its affiliates * and other contributors as indicated by the @author tags and * the contributor list. * * Licensed under the MIT License (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://opensource.org/licenses/MIT * * The software is provided "AS IS", WITHOUT WARRANTY OF ANY KIND, express or * implied, including but not limited to the warranties of merchantability, * fitness for a particular purpose and noninfringement. in no event shall the * authors or copyright holders be liable for any claim, damages or other * liability, whether in an action of contract, tort or otherwise, arising from, * out of or in connection with the software or the use or other dealings in the * software. See the License for the specific language governing permissions and * limitations under the License. */ package com.kumuluz.ee.maven.plugin; import org.apache.maven.execution.MavenSession; import org.apache.maven.plugin.BuildPluginManager; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugins.annotations.*; import org.apache.maven.project.MavenProject; import java.io.File; import static org.twdata.maven.mojoexecutor.MojoExecutor.*; /** * Run the application in an exploded class and dependency runtime. * * @author Benjamin Kastelic * @since 2.4.0 */ @Mojo( name = "run", defaultPhase = LifecyclePhase.PACKAGE, requiresDependencyResolution = ResolutionScope.COMPILE_PLUS_RUNTIME, requiresDependencyCollection = ResolutionScope.COMPILE_PLUS_RUNTIME ) public class RunExplodedMojo extends AbstractCopyDependenciesMojo { @Override public void execute() throws MojoExecutionException { final String CLASSPATH_FORMAT = "target%1$sclasses%2$starget%1$sdependency%1$s*"; copyDependencies(); executeMojo( plugin( groupId("org.codehaus.mojo"), artifactId("exec-maven-plugin"), version("1.6.0") ), goal("java"), configuration( element(name("mainClass"), "com.kumuluz.ee.EeApplication"), element(name("arguments"), element(name("argument"), "-classpath"), element(name("argument"), String.format(CLASSPATH_FORMAT, File.separator, File.pathSeparator))) ), executionEnvironment(project, session, buildPluginManager) ); } } ================================================ FILE: tools/maven-plugin/src/main/java/com/kumuluz/ee/maven/plugin/RunJarMojo.java ================================================ /* * Copyright (c) 2014-2017 Kumuluz and/or its affiliates * and other contributors as indicated by the @author tags and * the contributor list. * * Licensed under the MIT License (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://opensource.org/licenses/MIT * * The software is provided "AS IS", WITHOUT WARRANTY OF ANY KIND, express or * implied, including but not limited to the warranties of merchantability, * fitness for a particular purpose and noninfringement. in no event shall the * authors or copyright holders be liable for any claim, damages or other * liability, whether in an action of contract, tort or otherwise, arising from, * out of or in connection with the software or the use or other dealings in the * software. See the License for the specific language governing permissions and * limitations under the License. */ package com.kumuluz.ee.maven.plugin; import org.apache.maven.execution.MavenSession; import org.apache.maven.plugin.BuildPluginManager; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.MojoFailureException; import org.apache.maven.plugins.annotations.Component; import org.apache.maven.plugins.annotations.Parameter; import org.apache.maven.project.MavenProject; import static org.twdata.maven.mojoexecutor.MojoExecutor.*; /** * Run the application in an executable JAR archive runtime. * * @author Benjamin Kastelic * @since 2.4.0 */ //@Mojo( // name = "run-jar", // defaultPhase = LifecyclePhase.PACKAGE, // requiresDependencyResolution = ResolutionScope.COMPILE_PLUS_RUNTIME, // requiresDependencyCollection = ResolutionScope.COMPILE_PLUS_RUNTIME //) public class RunJarMojo extends AbstractPackageMojo { @Parameter(defaultValue = "${project.build.directory}") private String outputDirectory; @Parameter(defaultValue = "${project.build.finalName}") private String finalName; @Override public void execute() throws MojoExecutionException, MojoFailureException { repackage(); executeMojo( plugin( groupId("org.codehaus.mojo"), artifactId("exec-maven-plugin"), version("1.6.0") ), goal("exec"), configuration( element("executable", "java"), element(name("arguments"), element(name("argument"), "-jar"), element(name("argument"), outputDirectory + "/" + finalName + ".jar") ) ), executionEnvironment(project, session, buildPluginManager) ); } } ================================================ FILE: tools/maven-plugin/src/main/resources/META-INF/kumuluzee/plugin-versions.properties ================================================ maven-jar-plugin.version=${maven-jar-plugin.version} maven-resources-plugin.version=${maven-resources-plugin.version} maven-dependency-plugin.version=${maven-dependency-plugin.version} ================================================ FILE: tools/pom.xml ================================================ kumuluzee com.kumuluz.ee 4.2.0-SNAPSHOT 4.0.0 pom KumuluzEE Tools Various KumuluzEE tools loader maven-plugin kumuluzee-tools