Friday, June 22, 2018

type-safe message handling with bean-validation

nine years ago i implemented ExtValMessageInterpolatorAdapter. back then it allowed to combine the MessageInterpolator (bv) and the MessageResolver (extval). with that it was easy to load violation-messages from a custom message-source. it was needed because there was no agreement in the eg about it. from my first presentation about bv (in 2009) until now i always hear the same (valid) feedback (that there is a gap). the result (back then) was BVAL-217, but besides that nothing changed. four years ago there was the last (official) extval-release. the main reason was that most projects limited themselves to std. bv, because jsf as well as some component libs filled the most important gaps. years later there are still extval features which aren't part of the spec. (message-resolving is just one of them). as a "replacement" projects drop the corresponding requirement/s, use weird workarounds, "copy" parts of frameworks like extval or they moved away from bv and/or jsf anyway.

recently i was asked if it is possible to load bv-violation-messages from a database. furthermore, it would be beneficial to re-use custom concepts for type-safe messages. in such cases apache codi and later on deltaspike helped a lot to benefit from (or implement) such features easily. however, adding such frameworks isn't always an option (although they would help a lot) and in some cases there are still some limits.

so i extracted some parts from extval, codi and deltaspike and combined it with new ideas.

without type-safe messages available with deltaspike, i usually use something like the following pragmatic approach for type-safe messages:

that's easy to use, refactor and it's even possible to create an extension which autom. detects all enums implementing that interface and check for message-id clashes. however, when it comes to bean-validation we have the issue that we can't reference the message-id in a type-safe manner (due to the limited capability of java-annotations in combination with the fact that bv specifies that the message-attribute of constraint-annotations needs to be a string).

to allow at least one enum-type per bv-constraint we can benefit from the composite-constraint feature which is available since v1.0. with that we can define e.g.:

furthermore, in some cases it's useful to use information about the property in the violation message. in the listing above it's realized with the constraint-attribute propertyLabel. with std. bv you can hardcode that info. the main issue here is that there is no i18n support for the constraint-attribute value. instead of (manually) post-processing the violation-messages, it would be better to use the std. key-syntax to reference a different value in the message-source.

to summarize it, we would like e.g. to store the violation-text:
The length of '{propertyLabel}' should be between '{min}' and '{max}'
in a database, create a custom enum which implements a custom interface like MessageId and optionally (type-safe) labels which support i18n (the label-texts are stored in message-sources as well).
for the property-label we also create the corresponding entries in the database.
using those parts with @Length would e.g. look like:

and the resulting message is e.g.:
The length of 'Surname' should be between '2' and '50'

the propertyLabel attribute can be a string following the std. key-format to support i18n. alternatively it can be also a custom enum (implementing a custom interface). it isn't the same, but similar to the type-safe message-enum itself. due to the autom. interpolation the label-enum needs to be slightly different - e.g.:
the (custom) LabelId interface is just used to distinguish labels from the message itself. since the label is a constraint-attribute it gets interpolated by bv itself and therefore we need to force the key-format to identify the parts which need to be resolved in an own step.

to realize all that you just need to add the ds-bv-label-addon e.g. by adding https://rawgit.com/os890/ds-bv-label-addon/public as maven-repository and afterwards the maven-dependency as well as the custom message-interpolator:

to resolve violation-messages e.g. from a database you can add one or more beans like:
if you like to use message- and/or label-enums you can implement one or more beans like:
the git-repository illustrates different use-cases including one which shows how to share one constraint between different modules without using a shared message-enum (but still keep the type-safe approach) by using a shared composite-constraint in combination with a composite-constraint per module (which delegate to the shared composite-constraint).

Sunday, June 10, 2018

[add-on] no flush with org.apache.deltaspike.jpa.api.transaction.Transactional #readOnly and hibernate

jpa supports FlushModeType COMMIT and AUTO. for some use-cases that isn't enough. in case of org.apache.deltaspike.jpa.api.transaction.Transactional#readOnly(true) you will get a #rollback instead of a #commit at the end of the transaction. however, with some other frameworks you can get special behavior. e.g. some use org.hibernate.FlushMode#MANUAL once they detect hibernate as the jpa-provider. deltaspike only provides portable features and therefore you won't get such a special behavior out-of-the-box. however, deltaspike provides a rich set of extension-points. with a custom org.apache.deltaspike.jpa.spi.transaction.TransactionStrategy it's a matter of less than 100 loc to integrate org.hibernate.FlushMode#MANUAL as mentioned above. you can find a corresponding prototype here.

Saturday, May 26, 2018

[add-on] javax.annotation.security.* with deltaspike

intro/background:
recently DELTASPIKE-1345 was reported. since i checked the available integration of javax.annotation.security.* as well as JSR-375 just recently, it was clear that there isn't a well-established CDI extension which integrates with the servlet- and ejb-api (at least at this point).

in the past few years we usually used @Secured (or @Secures) to integrate with those and other authentication (and authorization) mechanisms. in most cases that allowed a type-safe and more CDI-like approach in combination with solid security-frameworks like http://shiro.apache.org

however, (currently) projects like keycloak are integrated e.g. with wildfly (and therefore with javax.annotation.security.*), but only for servlet based artifacts and EJBs.

since JSR-375 is integrated with CDI out-of-the-box, only EE6 and EE7 still have a gap in view of those annotations for authentication (in combination with CDI). in most cases it's enough to use @Secures in combination with the std. EE-APIs (like it's illustrated for JSF in one of the wildfly-demos). however, it's for sure inconsistent that those annotations can be used with different EE-APIs, but out-of-the-box not with CDI beans. therefore, i prototyped https://github.com/os890/ds-role-bridge-addon
it's a bridge which supports @DenyAll, @PermitAll, @RolesAllowed and @RunAs. i skipped the support for @DeclareRoles in combination with @RunAs, because a full support with EJBs wouldn't be portable anyway. the remaining annotations are also integrated with EJBs and therefore in most cases it should just work as it would be supported out-of-the-box.

the short story:
as shown in the demo-applications it's just needed to add the bridge as a runtime-dependency and use the javax.annotation.security.* annotations directly at the CDI beans. behind the scenes the final-role check is delegated to the servlet-api or if it isn't available (or there is no active servlet-request), a fallback gets triggered which delegates the check to the EJBContext. only @RunAs required a custom role-evaluation (including an explicit approach for the integration with EJBs).

the result:
https://github.com/os890/ds-role-bridge-addon should allow the same overall usage of @DenyAll, @PermitAll, @RolesAllowed and @RunAs (please report an issue if there is a difference). the main (known) difference is that you need to use annotations like @RolesAllowed explicitly (there is no "default/implicit" protection). furthermore, the result of a violation is a java.lang.SecurityException. however, the bridge also provides a rich set of SPIs which allows to customize the default behavior (in this case e.g. with an @Alternative implementation of AccessDeniedHandler).

btw. since cdi is really powerful it took longer to create the examples then the bridge itself.

Friday, March 30, 2018

multi-profiles in one minute

2012 spring added bean-profiles which is similar to project-stages added in myfaces-codi 2010. deltaspike improved and unified the project-stage concept. for the average case it's (imo) easier to handle than bean-profiles. however, from time to time users come up with some very special edge-cases which can be done with (custom) expressions supported by @Exclude. per definition such cases can get quite complex and usually there is an easier approach with deltaspike. in all the years (on the mailing-lists and in projects) i just saw one case which would really benefit a bit from the (imo) more complex bean-profiles approach. even in that case the result wasn't just "bad luck" and a questionable workaround as a result. instead it is possible to implements bean-profiles as a deltaspike-addon with less than 30 lines of code.


the usage is quite simple.
a type-safe approach based on cdi-stereotypes is supported as well. the usage of the type-safe approach is also straightforward: enabling 1-n profiles can be done with any active config-source.
the implementation including tests are available at ds-multi-profile-addon.

Tuesday, October 27, 2015

type-safe configs the second minute

in my first post about this topic i explained how to create a type-safe config based on interfaces and the partial-bean-module provided by deltaspike.

this second part is about a new possibility which is available since deltaspike v1.5.1.


until deltaspike v1.5.1, you needed to create and inject the type-safe config for accessing configured values. one part of the example shown in the first post looked like:

since deltaspike v1.5.1, you can use @Produces in your type-safe config. with that you can directly inject the result instead of the config-class.

Saturday, October 3, 2015

type-safe configs in one minute

within the last months i heard about more and more projects which move to cdi.
an important aspect of cdi is the type-safe injection including type-safe qualifiers and many other concepts based on type-safety.

"surprisingly" type-safe concepts get ignored quite often when it comes to accessing config-values.
however, there is no technical limitation here. in fact creating even generic approaches for type-safe configs can be easy once the implementation is based on deltaspike.

-> like with many other topics my answer is something like:
"use deltaspike and it's way easier."

in case of config-approaches, deltaspike provides several flexible and extensible concepts.
e.g. the upcoming chapter of http://cdiatwork.irian.at will also describe some of them in detail.

beyond that it's easy to implement your own concepts based on mechanisms provided by deltaspike.
the following listing illustrates how to implement your own type-safe config.

this implementation is based on the partial-bean module of http://deltaspike.apache.org (@TypeSafeConfig is annotated with @org.apache.deltaspike.partialbean.api.PartialBeanBinding). in a second step it's required to annotate an implementation of java.lang.reflect.InvocationHandler with our own binding-annotation (see @TypeSafeConfig) and implement the logic to load and parse the config-values. in our example we delegate the lookup of the config-values to ConfigResolver#getProjectStageAwarePropertyValue. ConfigResolver is provided by deltaspike and allows to integrate even custom config-sources easily.

with those two simple classes, we can create custom type-safe configs by just creating interfaces and annotating them with our own binding-annotation (see @TypeSafeConfig). the following listings show two examples how to define and use such a custom config (see AppConfig and BatchConfig).

the last snippet shows how to inject and use both configs in any cdi-bean. in the illustrated example we use them in CustomBatchStarter, which is a cdi-enabled implementation of org.quartz.Job (see @org.apache.deltaspike.scheduler.api.Scheduled).

Saturday, October 25, 2014

openwebbeans custom resources

cdi itself allows to add beans to integrate other frameworks and containers.
so it's possible to inject them via @Inject.
however, sometimes you need to use other annotations like @EJB or @Autowired.
in an ee-server ee-annotations like @EJB work out-of-the-box. however, in case of a manual setup e.g. in combination with a servlet-container like tomcat, you might not be able to inject references to remote-ejbs. in any case you can't use non-ee annotations like @Autowired in cdi-beans out-of-the-box.

as mentioned in previous posts apache openwebbeans is very flexible.
owb is based on a simple plugin architecture which allows to customize parts easily.
some years ago i published an add-on for owb which allows to inject remote-ejbs via @EJB into cdi-beans in non-ee environments.
the add-on injects references resolved by a custom ejb-resolver into injection-points annotated with @EJB.

with the same approach it's possible to use 3rd party annotations in cdi-beans.
today i prototyped a similar add-on for owb, which allows to use @Autowired in cdi-beans to inject spring-beans based on the (field-)name or type. compared to the cdi-spring bridge i described here, it allows a simpler implementation which delegates to a started spring-container (instead of bootstrapping it). the major downside is that it isn't a portable cdi-extension (per definition) and therefore you can only use it with owb. furthermore, there is no validation of those injection-points during the startup you (might) know from cdi and injection of cdi-beans into spring-beans isn't supported as well.

Friday, October 24, 2014

[deltaspike] restricting the amount of windows

with codi it was possible to restrict the number of windows and old windows are dropped if the maximum was reached and a new window should get created.
deltaspike doesn't allow that before v1.1.0, however, it's very easy to implement it manually:

Wednesday, October 22, 2014

duke arrived!


today duke arrived - thx to the whole community!

Friday, July 4, 2014

[slides] apache deltaspike

Wednesday, June 18, 2014

8th release of deltaspike -> v1

The Apache DeltaSpike team is pleased to announce the 8th release of DeltaSpike. It's v1.0.0!

Friday, June 6, 2014

openwebbeans on wls

some time ago, i described how to run openwebbeans on glassfish and wls.
the described approach works pretty well. however, once deltaspike added an optional ee7-support (esp. for jsf 2.2+), wls fails during the startup, because v12.1.2 doesn't support optional classes which contain imports of unknown classes (ee7 classes unknown to an ee6-server) like the other ee6 servers do.
therefore i created a new branch for ds-owb-bundle which filters those optional ee7 classes.
with that deltaspike works on wls without issues.

Saturday, May 31, 2014

openwebbeans on glassfish

some time ago, i described how to run openwebbeans on glassfish3 and wls12.
in my previous post i described how to run openwebbeans on wildfly8 (and as7).
with the latest commit for ds-owb-bundle and the trunk of owb add-on,
the demo-application also works on glassfish4.

Friday, May 30, 2014

openwebbeans on wildfly8

recently i showed how to run owb on as7. the same owb add-on works with wildfly8 as well. however, wildfly8 ships a version of weld which implements cdi 1.1. therefore, i had to update the repackaged version of deltaspike. with the latest commit for ds-owb-bundle, the demo-application also works on wildfly8.

Thursday, May 29, 2014

openwebbeans on as7

some time ago, i described how to run openwebbeans on a weld based ee6 server.
i mentioned that the used classpath-scanner doesn't support the virtual-file-system.
however, today i rewrote the scanner-service.
now it uses the "Corn Classpath Scanner" lib, which supports the vfs.
therefore, i tested the result with as7 (v7.2.0) and owb works fine as expected.
you can have a look at the result at the as7-branch of the same repository.

Wednesday, May 21, 2014

apache deltaspike pmc chair

now it's official - i'm the new pmc chair of deltaspike for this year.
i'll try to continue the great work of the previous chair!

furthermore, i would like to thank mark for being such a great chair!

in my first blog-post as new pmc chair i would like to mention:
everybody is welcome to join our awesome community!

Saturday, May 10, 2014

[add-on] fast event processing with disruptor + deltaspike

cdi offers synchronous events. they are more like a decoupled method call. that's fine for a lot of use-cases.

in some cases the processing can take some time (in the observer method). a common trick is to use an ejb + @Asynchronous for the observer-method. with that the event-source can continue and the observer operates in a new thread.

however, that isn't enough if there is a huge amount of such events. for use-cases like that i've prototyped an add-on for apache deltaspike which allows to use disruptor for firing and observing events. it includes a simple qualifier support, however, it doesn't provide an 1:1 implementation of the cdi event rules. it can be used the same way as cdi events:

  and

the add-on creates a disruptor-processor for every observer methods. the method gets invoked on the cdi-bean itself. the cdictrl-module provided by deltaspike is used for starting the cdi request- and session-scope before an observer method gets called (and to stop it afterwards). with that the application-, session- and request-scope (as well as all scopes based on them which start autom.) can be used for such beans.
since the observer methods are invoked on the contextual-instance, cdi features like dependency-injection can be used as expected. the result is really nice. there is a huge difference in view of the pure event-processing performance of the events:




the result might look strange at the first view. however, the effects are quite clear. since the observer-logic in the demo is fast, the benefit of using @Asynchronous is lost. here the pure invocation of observers in ejbs is slower (than observers in a cdi-bean), because the container has to handle additional ejb features like transactions. the cdi bean as well as the stateful ejb is application-scoped and therefore only one (cached) instance is needed.

in the charts above it's hard to see, but the numbers show that tomee is faster in case of the deltaspike/disruptor add-on (due to the highly optimized proxies of openwebbeans 1.2.x) and as7 is a bit faster with dispatching standard cdi events.

currently the add-on works with tomee and as7 (tested with v7.2) and is available here. the repository also contains several tests, which illustrate the supported use-cases.

Monday, May 5, 2014

[add-on] mock cdi-beans with deltaspike

i've prototyped an add-on for apache deltaspike which allows to mock cdi-beans manually or with a mocking-framework.

an example for a simple cdi-bean:
an example for a simple manual-mock for the cdi-bean: an example for a simple mockito-mock for the cdi-bean: the same is possible in combination with qualifiers as well as with producers and @Typed beans.

the add-on is available here. the repository also contains several tests, which illustrate the supported use-cases. the tests use manual-mocks as well as mockito-mocks. however, you can provide any object as mock which is a subclass of the original implementation.

Sunday, April 20, 2014

[add-on] monitoring lite with deltaspike

there are quite a lot of different use-cases for monitoring and auditing. for more advanced use-cases projects like apache sirona are reasonable. however, in several cases it's enough to have a simple interceptor which collects information (which can get processed at the end of a request). since a lot of projects implemented it on their own and end up with similar solutions, i've created an add-on for apache deltaspike which supports several common use-cases like exception monitoring, performance monitoring (via execution time) and auditing (with or without method-parameter values).

after adding the add-on to a project based on deltaspike the usage is simple, just annotate a method or the whole class with @InvocationMonitored and create a cdi-observer for MonitoredMethodInvocationsEvent. the add-on will collect information about the monitored method-invocations during a request and you can process the entries based on your requirements. the following example illustrates a sample usage. it's up to you which information you use and how you process it (e.g. logging it, storing it in a persistent store,...).


asynchronous processing is also supported via an @Asynchronous observer in an ejb.

the optional jsf module allows to record the current view-id per entry and the processing after the rendering-phase.

the add-on is available here.

Friday, April 18, 2014

simple cdi and ejb tests with deltaspike

apache deltaspike v0.6+ provides an easy to use, but quite powerful junit test-runner. it's based on the container-control api of deltaspike. deltaspike itself currently provides implementations for openwebeans, weld and openejb (tomee).

the last one is important, if you need to test a cdi+ejb based application. just by using a different container-control implementation (deltaspike-cdictrl-openejb) in your build config and adding openejb (/tomee) via org.apache.openejb:openejb-core, you can test cdi-beans as well as ejbs. just inject them as usual via @Inject (also @EJB works as expected).

an example can be found here.