<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	xmlns:georss="http://www.georss.org/georss" xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#" xmlns:media="http://search.yahoo.com/mrss/"
	>

<channel>
	<title>Blame Laird</title>
	<atom:link href="https://lairdnelson.wordpress.com/feed/" rel="self" type="application/rss+xml" />
	<link>https://lairdnelson.wordpress.com</link>
	<description>Sum ergo mea culpa est.</description>
	<lastBuildDate>Fri, 31 Dec 2021 20:22:36 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>http://wordpress.com/</generator>

<image>
	<url>https://lairdnelson.wordpress.com/wp-content/uploads/2021/12/cropped-640px-flag_of_cascadia.png?w=32</url>
	<title>Blame Laird</title>
	<link>https://lairdnelson.wordpress.com</link>
	<width>32</width>
	<height>32</height>
</image> 
<site xmlns="com-wordpress:feed-additions:1">47283078</site><cloud domain='lairdnelson.wordpress.com' port='80' path='/?rsscloud=notify' registerProcedure='' protocol='http-post' />
<atom:link rel="search" type="application/opensearchdescription+xml" href="https://lairdnelson.wordpress.com/osd.xml" title="Blame Laird" />
	<atom:link rel='hub' href='https://lairdnelson.wordpress.com/?pushpress=hub'/>
	<item>
		<title>New Blog</title>
		<link>https://lairdnelson.wordpress.com/2021/12/31/new-blog/</link>
		
		<dc:creator><![CDATA[Laird Nelson]]></dc:creator>
		<pubDate>Fri, 31 Dec 2021 20:22:36 +0000</pubDate>
				<category><![CDATA[Java]]></category>
		<guid isPermaLink="false">http://lairdnelson.wordpress.com/?p=3759</guid>

					<description><![CDATA[I&#8217;m moving my blog to ljnelson.github.io/blog. I&#8217;ve just posted Java Configuration: JNDI and Naming Operations.]]></description>
										<content:encoded><![CDATA[
<p>I&#8217;m moving my blog to <a href="https://ljnelson.github.io/blog/">ljnelson.github.io/blog</a>.</p>



<p>I&#8217;ve just posted <a href="https://ljnelson.github.io/blog/java-configuration-jndi-and-naming-operations/">Java Configuration: JNDI and Naming Operations</a>.</p>
]]></content:encoded>
					
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">3759</post-id>
		<media:content url="https://2.gravatar.com/avatar/58e3ea56bec4978a64e8ad60274b75cd8691435be2e44e6e69969986ed9b6399?s=96&#38;d=&#38;r=G" medium="image">
			<media:title type="html">lairdnelson</media:title>
		</media:content>
	</item>
		<item>
		<title>Qualifiers and Configuration Coordinates in Configuration</title>
		<link>https://lairdnelson.wordpress.com/2021/12/07/qualifiers-and-configuration-coordinates-in-configuration/</link>
		
		<dc:creator><![CDATA[Laird Nelson]]></dc:creator>
		<pubDate>Wed, 08 Dec 2021 02:04:16 +0000</pubDate>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Uncategorized]]></category>
		<guid isPermaLink="false">http://lairdnelson.wordpress.com/?p=3724</guid>

					<description><![CDATA[This post is part of a larger series, I guess, maybe, that is heading toward what a good Java configuration API might look like. (My usual disclaimers: I work for Oracle on the Helidon project, but never speak for the big red O unless I have to (this is not one of those times). I &#8230; <a href="https://lairdnelson.wordpress.com/2021/12/07/qualifiers-and-configuration-coordinates-in-configuration/" class="more-link">Continue reading<span class="screen-reader-text"> "Qualifiers and Configuration Coordinates in&#160;Configuration"</span></a>]]></description>
										<content:encoded><![CDATA[
<p>This post is part of a larger series, I guess, maybe, that is heading toward what a good Java configuration API might look like.</p>



<p>(My usual disclaimers: I work for Oracle on the <a href="https://helidon.io/">Helidon project</a>, but never speak for the big red O unless I have to (this is not one of those times). I am also a committer on MicroProfile Config (but have reservations about the project) and Jakarta Config (and have reservations about its direction).  I&#8217;m not writing here in any of the roles listed above (I rarely do).)</p>



<p>I&#8217;ve written before about how Java configuration, reduced to its essence, when viewed from an application developer&#8217;s standpoint, has nothing to do with dynamic typing or named properties or converters or tree nodes or all the other things that people immediately think of that look and smell like System properties for no good reason.  Instead, it must be a low-level, deliberately limited precursor to things like dependency injection systems (since it will presumably be used to configure them).  Precursor or no, it is still about asking for a particular kind of object suitable for a particular kind of application running in a particular kind of place and receiving it.  Full stop.</p>



<p>I&#8217;ve also written about how a great example of such a configuration system API, as utterly straitjacketed as it is (on purpose), is <code>java.util.ServiceLoader</code>: pass it a type, get back an object that was configured in a place that doesn&#8217;t require code to be recompiled to reconfigure.</p>



<p>So what does <em>suitability</em> mean here?  What is a <em>place</em>?  What does it mean to have an object suitable for an application?  Isn&#8217;t there just one application?</p>



<p>I like to think of this in terms of <em>configuration space</em>.  Configuration space is a {emulates Carl Sagan} huge multidimensional void that contains all possible deployments of your application.  When you deploy your application, you are, whether you realize it or not, situating it in configuration space.</p>



<p>I will occasionally call the the various points along configuration axes that you use to identify your application in configuration space <em>configuration coordinates</em>.  They&#8217;re like the latitude and longitude that pick out your application in configuration space.</p>



<p>Other times I will call these coordinates <em>qualifiers</em>, after CDI&#8217;s qualifiers: they are additional ways to further describe whatever it is you&#8217;re talking about.  Acquiring a <code>Car</code> may logically require that you specify exactly what <em>kind</em> of <code>Car</code> implementation you&#8217;re looking for, i.e. a <em>suitable</em> one that is <em>qualified</em> by qualifiers you supply.</p>



<p>Dependency injection systems, as noted, almost all have the notion of qualifiers.  The only real difference is that most dependency injection systems begin by assuming that if you have an <em>unqualified</em> injection point, you are asking for the <em>default</em> thing that might satisfy the injection point.</p>



<p>Configuration is different.  An application is implicitly qualified, logically speaking, by the configuration coordinates that describe its location in configuration space.  If I run my application in the test environment and in some specific cloud region with experimental features turned on, the application, as developed by the application developer, really shouldn&#8217;t have to change at all to ask for a different thing (or else we would not, by definition, be talking about configuration!).  So if the application developer is asking for a <code>Car</code>, she should continue asking for a <code>Car</code>, i.e. she shouldn&#8217;t have to recompile her code just because her application is in a different &#8220;place&#8221;.</p>



<p>That would seem to contradict the statement earlier that acquiring a <code>Car</code> may require that you specify exactly what kind of <code>Car</code> implementation you&#8217;re looking for.  You can work around this conceptually by saying, OK, the configuration system, when it comes up, must first figure out what the implicit qualifiers of the application it &#8220;belongs to&#8221; are.  <strong>That is: qualifiers are primordial things to configuration systems.</strong></p>



<p>Consider Java&#8217;s own <code>ResourceBundle</code>, which was not really designed to be a configuration system, but which <em>does</em> acknowledge the primordial nature of implicit qualifiers.  When you ask for a <code>ResourceBundle</code>, the underpinnings of the system figure out what your application&#8217;s coordinates are in resource bundle space, and load a resource bundle for you that is suitable for where your application finds itself.  Less stuffily: if the current locale is German, then you&#8217;ll get the German resource bundle.  If it&#8217;s unset, then you&#8217;ll get the default one.  Your code doesn&#8217;t change.  Locale, in this case, is an example of a qualifier that is implicit and locates your application in a particular kind of space.</p>



<p>Consider Spring, which features configuration profiles, a clumsy and coarse-grained way to give a name to logical bundles of qualifiers.  Ask for a particular thing, and depending on what profile your application has, you might get the profile-specific version of that thing or the default one.  The developer of the application doesn&#8217;t change her code.</p>



<p>Consider Netflix&#8217;s Archaius, which allows you to define a <code><a href="https://javadoc.io/static/com.netflix.archaius/archaius2-api/2.3.16/com/netflix/archaius/api/CascadeStrategy.html">CascadeStrategy</a></code>, under the covers which is a rather clumsy way to emulate a <code><a href="https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/util/ResourceBundle.Control.html#getFormats(java.lang.String)">ResourceBundle.Control</a></code> object.  Same deal; your application ends up being located in configuration space by a mechanism that you don&#8217;t really have to think about as an application developer: if you ask for a particular configuration item, then the one that is most suitable for your application&#8217;s &#8220;location&#8221; will be given to you, without your code having to change.</p>



<p>Many of these configuration or configuration-like systems that work <em>with</em> qualifiers, whether they know it or not, also tend to treat them as hierarchical, and bake them into the configuration names.  Obviously, qualifiers need <em>not</em> be hierarchical, and equally obviously do <em>not</em> change the fundamental name of the thing they qualify, but, oddly, this became convention at some point, and so this is how they are often modeled—a practice which obscures what is really going on.  For example, in English, if you&#8217;re looking for a hostname, even if you&#8217;re looking for one suitable for the development environment, you&#8217;re still looking for a hostname, not a dev.hostname.</p>



<p>If you stretch all of this to the breaking point, then it&#8217;s also the case that a name of a particular configuration item is just another qualifier!  If you&#8217;re looking for a <code>Frobnicator</code> named <code>goop</code>, then you&#8217;re looking for a <code>Frobnicator</code> with qualifiers of <code>name=goop</code>, <code>environment=development</code> (let&#8217;s say), <code>experimentalFeatures=on</code> (let&#8217;s say), and so on.  But a name is as good a qualifier as any to elevate to principal status, so there&#8217;s no need to go crazy here.</p>



<p>So then: we have at the core of our configuration concepts types (the kinds of things the developer is trying to acquire from configuration) and qualifiers (the configuration coordinates identifying the application in configuration space), as well as names (which are really just an obvious elevated kind of qualifier).</p>



<p>This should sound familiar.  Any dependency injection heads out there will recognize that types and qualifiers are exactly what you use in every dependency injection system on the planet to retrieve objects.  Most DI systems will represent them as Java annotations, but if you dig into them you&#8217;ll see that that is mainly for the strict immutability semantics that annotations happen to carry with them, not for anything that is somehow magic about annotations <em>per se</em>.</p>



<p>Finally, there is another Java-centric system out there that does all of the following:</p>



<ol class="wp-block-list"><li>Allows the application developer to request a qualified Java object of a particular type</li><li>Allows the application developer to <em>further</em> qualify that request (and actually qualify individual <em>pieces</em> of a request)</li><li>Allows the application developer to supply representational hints about the Java object being returned</li><li>Mediates between potentially competing result producers to deliver the result that is the most suitable for the caller&#8217;s &#8220;location&#8221; in &#8220;space&#8221;</li></ol>



<p>That system is JAX-RS/Jakarta RESTful Web Services!  Obviously I&#8217;m not suggesting that Jakarta RESTful Web Services is a good configuration system (for one thing, it is too high-level and the concepts involved are at the wrong architectural level).  But I <em>am</em> suggesting that the fact that it deals with paths to Java-typed resources, qualified by header values, media types, locales and all the other implicit coordinates that locate an application in space is worth looking at in the abstract.  I hope to sketch that out in another post.</p>
]]></content:encoded>
					
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">3724</post-id>
		<media:content url="https://2.gravatar.com/avatar/58e3ea56bec4978a64e8ad60274b75cd8691435be2e44e6e69969986ed9b6399?s=96&#38;d=&#38;r=G" medium="image">
			<media:title type="html">lairdnelson</media:title>
		</media:content>
	</item>
		<item>
		<title>Configuration and Dependency Acquisition</title>
		<link>https://lairdnelson.wordpress.com/2021/11/07/configuration-and-dependency-acquisition/</link>
		
		<dc:creator><![CDATA[Laird Nelson]]></dc:creator>
		<pubDate>Sun, 07 Nov 2021 21:21:52 +0000</pubDate>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[config]]></category>
		<guid isPermaLink="false">http://lairdnelson.wordpress.com/?p=3709</guid>

					<description><![CDATA[I&#8217;ve written some prior posts on the strange state of affairs that got those of us in Java-land to MicroProfile Config and the many ways in which I find it bizarre, unpredictable, clumsy and deficient. In this post I&#8217;d like to talk about what configuration systems actually depend on so we can locate them in &#8230; <a href="https://lairdnelson.wordpress.com/2021/11/07/configuration-and-dependency-acquisition/" class="more-link">Continue reading<span class="screen-reader-text"> "Configuration and Dependency&#160;Acquisition"</span></a>]]></description>
										<content:encoded><![CDATA[
<p>I&#8217;ve written some <a href="https://lairdnelson.wordpress.com/2021/10/14/some-of-the-things-i-dont-like-about-microprofile-config/">prior</a> <a href="https://lairdnelson.wordpress.com/2021/08/12/microprofile-config-and-other-configuration-musings/">posts</a> on the strange state of affairs that got those of us in Java-land to <a href="https://github.com/eclipse/microprofile-config/">MicroProfile Config</a> and the <a href="https://lairdnelson.wordpress.com/2021/10/14/some-of-the-things-i-dont-like-about-microprofile-config/">many ways in which I find it bizarre, unpredictable, clumsy and deficient</a>.  In this post I&#8217;d like to talk about what configuration systems actually depend on so we can locate them in architectural space before proceeding further.</p>



<p>I&#8217;ve indirectly <a href="https://lairdnelson.wordpress.com/2021/08/12/microprofile-config-and-other-configuration-musings">made the case that a Java configuration system is fundamentally in the business of loading objects and handing them to you</a>.  That&#8217;s it.  You ask for an object; it is delivered unto you.  It is <em>not</em> fundamentally about conversion, &#8220;properties&#8221; and all the usual stuff people tend to bring up when they talk about Java configuration because they are subconsciously thinking about System properties and environment variables, both of which are different things and are the way they are due to requirements that have nothing to do with Java configuration <em>per se</em>.  (But I digress.)</p>



<p>Next little factoid: Most Java applications these days either knowingly use a dependency injection framework (Spring, CDI) or unknowingly invent a bad version of one.  Dependency injection frameworks load and make objects and hand them to you.  Hmm.  That sounds familiar.</p>



<p>Suppose now you want to use a configuration system to configure, among possibly other things, the dependency injection framework you&#8217;re using.  If configuration is all about loading objects and handing them to you, and, arguably, dependency injection is at least partially about the same thing, then how do the dependencies between these two architectural nuggets work?</p>



<p>Cutting to the chase, the DI framework <em>has</em> to depend on the configuration framework, or the configuration framework couldn&#8217;t configure it before it started.  So no dependency injection for you while you&#8217;re in the configuration system.  That much is obvious, and yet there are still configuration systems of all sorts of stripes that get this wrong.</p>



<p>What may be less obvious at first glance is <em>how</em> to leave object production as much as possible in the hands of the dependency injection framework, and configuration as much as possible in the hands of the configuration framework.  In other words, in CDI I can produce a <code>String</code>, and in a configuration system I can look up a <code>String</code>.  How are these operations different?  Which should I use at which points?</p>



<p>Or to put it another way, for a well-designed configuration system to do its job, it does in fact need to be a very limited version of a dependency <em>acquisition</em> (if not injection) framework itself.  Fortunately, the barrier to entry is much lower for configuration systems than full-blown dependency injection systems.  For example, configuration systems only really have to worry about getting The Things That Make Configured Objects Of Particular Kinds, not any object in the world.  This cuts down dramatically on scope and lifecycle requirements and proxying.  Also, since configuration systems are bootstrappy by their very nature, they don&#8217;t really <em>need</em> injection or circular reference handling or any of the other things that justifiably make dependency injection systems inherently complicated.</p>



<p>One great absolutely minimal example of this sort of thing that is deliberately <em>extremely</em> limited is <code>java.util.ServiceLoader</code>.  This &#8220;configuration framework&#8221; instantiates an assignable class given a superinterface (or superclass) that often you have defined, and hands it to you.  That&#8217;s it.  That&#8217;s still a dependency acquisition framework: wherever you are, whatever architectural layer you inhabit, you ask the <code>ServiceLoader</code> for a provider object, and then manipulate that provider object to get you your dependency.  One of the many things that&#8217;s nice about this is you can supply the types involved, so the configuration system stays out of this business.  The configuration system also tells you exactly how it&#8217;s going to make a match between what you asked for and what&#8217;s available.  None of this involves type conversion, scalar munging, namespaces, weak typing or other frippery.  Said frippery may of course reside &#8220;lower down&#8221; the architectural stack, but that&#8217;s not the business of the <code>ServiceLoader</code> nor should it be.</p>



<p>Suppose <code>ServiceLoader</code> were enhanced a little bit (let&#8217;s pretend) to be able to sort through multiple service providers to hand you one that was the most suitable for you in some fashion (right now, <code>ServiceLoader</code> just reports all the providers it found).  That would be a great example of a helpful configuration system: you ask it for a <code>Car</code>, and it sorts through all the various <code>Car</code> providers to find the one that is suited to where your application happens to be located in configuration space and picks that one.  Then it tells the selected provider to get you your <code>Car</code>.  Is it a perfect match?  Maybe, but maybe not.  But it is a <em>suitable</em> match.  Will the provider supply the same <code>Car</code> every time it&#8217;s asked for one?  Maybe, but maybe not.  If the application wants a stable <code>Car</code>, then it caches the <code>Car</code>.  If it does not, then it asks the provider for a <code>Car</code> again.  This is not the business of the enhanced hypothetical <code>ServiceLoader</code> either.</p>



<p>(As an aside: MicroProfile Config dimly glimpses that this is the way to go (a <code>Config</code> finds a suitable <code>ConfigSource</code>, but falls down by then forcing all such service providers to be in the business of producing strings that other service providers (<code>Converters</code>) convert into what you need.  Now because you are producing things of a type the application developer didn&#8217;t hand you, you have to worry about names, weak typing and namespaces when that&#8217;s not anything at all that the application developer wants to work with, and that&#8217;s how you get such a strange API.)</p>



<p>Anyway, armed with such a thing, then you can cause those configured objects to surface in your dependency injection framework however you like.  If, for example, you&#8217;re in the middle of writing a CDI portable extension (so something executing before the dependency injection system has completed initializing), you could use the configuration system to acquire objects you need to figure out how your extension should behave, and then if they&#8217;re relevant elsewhere in the application, you could write producer methods for them, or the provider that makes them, and now the rest of your ordinary CDI code could just use them as any other bean.  If you carry the dependency injection mindset to its logical conclusion, an application really shouldn&#8217;t, itself, need to consult some special system for configuration data.  It will just use its normal objects, some of which will have been configured and produced by DI system internals.</p>



<p>If you think of things this way, then you can start to see what shape a configuration system in Java should take.  More (obviously) on this topic to come.</p>
]]></content:encoded>
					
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">3709</post-id>
		<media:content url="https://2.gravatar.com/avatar/58e3ea56bec4978a64e8ad60274b75cd8691435be2e44e6e69969986ed9b6399?s=96&#38;d=&#38;r=G" medium="image">
			<media:title type="html">lairdnelson</media:title>
		</media:content>
	</item>
		<item>
		<title>Some of the Things I Don&#8217;t Like About MicroProfile Config</title>
		<link>https://lairdnelson.wordpress.com/2021/10/14/some-of-the-things-i-dont-like-about-microprofile-config/</link>
		
		<dc:creator><![CDATA[Laird Nelson]]></dc:creator>
		<pubDate>Thu, 14 Oct 2021 18:36:44 +0000</pubDate>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[config]]></category>
		<guid isPermaLink="false">http://lairdnelson.wordpress.com/?p=3661</guid>

					<description><![CDATA[Here are some things I don&#8217;t like about the MicroProfile Config APIs (and really also most APIs like them) and the ways in which they are defined (or not defined) to work. I&#8217;m writing them down in no particular order so I don&#8217;t forget. This is obviously related to my prior post. If I&#8217;m handed &#8230; <a href="https://lairdnelson.wordpress.com/2021/10/14/some-of-the-things-i-dont-like-about-microprofile-config/" class="more-link">Continue reading<span class="screen-reader-text"> "Some of the Things I Don&#8217;t Like About MicroProfile&#160;Config"</span></a>]]></description>
										<content:encoded><![CDATA[
<p>Here are some things I don&#8217;t like about the MicroProfile Config APIs (and really also most APIs like them) and the ways in which they are defined (or not defined) to work.  I&#8217;m writing them down in no particular order so I don&#8217;t forget.  This is obviously related to my <a href="https://lairdnelson.wordpress.com/2021/08/12/microprofile-config-and-other-configuration-musings/">prior post</a>.</p>



<p>If I&#8217;m handed an opaque application that uses MicroProfile Config, I don&#8217;t know the names or types of the configuration properties it will seek, if any.  So I don&#8217;t know what configuration to author.</p>



<p>If your opaque library happens to seek &#8220;<code>fred</code>&#8221; (and it&#8217;s opaque so I can&#8217;t know this up front; see above; but let&#8217;s say I use <code>strings</code> or something and get a good guess) and my library also seeks &#8220;<code>fred</code>&#8220;, and yours expects a certain <code>String</code> format for &#8220;<code>fred</code>&#8221; (so that it can convert it to some specialized object), and mine expects a different <code>String</code> format for &#8220;<code>fred</code>&#8220;, and I combine the two libraries into an application, and there are <code>Converter</code>s from you and <code>Converter</code>s from me and various <code>ConfigSource</code>s involved, there&#8217;s no way that I can see to reconcile this other than trial and error at runtime.</p>



<p>If I put a <code>ConfigSource</code> on the classpath with ordinal <code>Integer.MAX_VALUE</code> that returns a random <code>String</code> for every value sought, or do something well-intentioned but accidental like this, pretty much everything will fail at runtime and it&#8217;s difficult to understand why.  (In general, if you have to resort to ordinals or priorities in anything, you have already lost; what you&#8217;re actually after is a reduction algorithm.)</p>



<p>A <code>ConfigSource</code> can report whatever it wants from <code>getOrdinal</code>, so even if you set a <code>config_ordinal</code> property in its backing data somehow, you don&#8217;t know if your setting will be used.</p>



<p>A <code>ConfigSource</code> can return whatever it likes as its name, and since this is used as a tiebreaker in sorting, sorting is indeterminate.  So which <code>ConfigSource</code> &#8220;answers the phone&#8221; is also indeterminate from run to run.</p>



<p>We insist that developers model business objects because developers know the names and types of the data they use (<code>Person</code> has a <code>getAgeInYears()</code> method that returns a positive <code>int</code>, not a method like <code>getProperty(String name, Class&lt;?&gt; type)</code>).  But MicroProfile Config forces configuration (where the application also knows the names and types of the configuration data it consumes) to be consumed via dynamically-typed, <code>Map</code>-like probe requests (<code>Config.getValue("personAge", int.class)</code>).  That&#8217;s very odd.</p>



<p>A <code>Config</code> can return an empty set for the configuration property names it claims to support because the set of such available names may change from moment to moment, or may not be able to be determined for any reason.  So an application developer doesn&#8217;t know what she can ask for via the probing APIs.  (Can she ask for &#8220;<code>fred</code>&#8220;? If she asks for &#8220;<code>fred</code>&#8221; twice and gets two <code>null</code> responses, does that mean that &#8220;<code>fred</code>&#8221; is never supported?  Or maybe just that coincidentally &#8220;<code>fred</code>&#8221; couldn&#8217;t be retrieved during that particular time window?  She doesn&#8217;t know, and can&#8217;t know.)</p>



<p>A <code>ConfigSource</code> can do whatever it wants, as can a <code>Converter</code>, as can <code>ConfigSourceProviders</code>, and they can all come from the classpath, whether user-, application-, application-server- or library-supplied, or all four, and a <code>Config</code> is essentially just a shell around these <code>ConfigSources</code> and <code>Converter</code>s and <code>ConfigSourceProviders</code>, so not only do you not know what you can ask for, you don&#8217;t know whether it will be delivered to you for any given call you make, or, if it can, whether it can be delivered to you with the type you want, or, if you make it this far, whether such typed data can be delivered to you again with the same type if you make the same call, or if you restart the application if the same things you observed last time will hold true this time.</p>



<p>Since a <code>Converter</code> can do whatever it wants and can be user- or system-supplied, then even with the <code>Config::getConverter</code> method you don&#8217;t know what kind of suitable conversion is available at any given point for any given property.</p>



<p>Given a configuration property named &#8220;<code>fred</code>&#8220;, there&#8217;s no way to know what type(s) its value may successfully be converted to (other than <code>String</code>).</p>



<p>Configuration, in other words, is <em>by spec</em> unpredictable in name, type, availability, idempotency and determinism. That&#8217;s bizarre.</p>



<p>While the APIs and specified behavior for the <code>Config</code>-locating-and-assembly subsystem (<code>ConfigProviderResolver</code>) to conceivably work with any <code>ConfigSource</code> and <code>Converter</code> and <code>Config</code> implementations, in practice doing things like mixing and matching one vendor&#8217;s <code>ConfigProviderResolver</code> with another&#8217;s <code>ConfigProvider</code> doesn&#8217;t work.</p>



<p>Applications are associated with <code>ClassLoader</code> instances in some vague way.  They could be associated with <code>Object</code> instead (provided the <code>Object</code>-in-question&#8217;s <code>equals</code> and <code>hashCode</code> methods are stable) and everything would still work.  This tells you that <code>ClassLoader</code> association is unnecessary.</p>



<p>When a classloader is unloaded, various internal resources inside any MicroProfile Config implementation must be released, but there&#8217;s no real specification about how this should be done.  In practice, to do this properly</p>



<p>There&#8217;s no specified way to configure MicroProfile Config with MicroProfile Config.  There are occasional places where the need for this is visible and an attempt has been made to address it (<code>config_ordinal</code>, <code>ConfigSourceProvider</code>), but with no real systemic approach.</p>



<p>Notions of how to close and otherwise release resources including <code>Converters</code> inside any MicroProfile Config implementation require absurdly complicated <code>WeakReference</code> machinations in any specification-compliant implementation for no really good reason (see above).  Otherwise you leak <code>ClassLoader</code>s.</p>



<p>Since you don&#8217;t know from call to call whether &#8220;<code>fred</code>&#8221; is available, let alone what type it can be converted to (since its format could change or conversion could be random), then injection of its value via CDI should really be defined in terms of <em>only</em> <code>Provider</code> injection.  Alas.  So an <code>Integer</code>-typed, <code>@ConfigProperty</code>-annotated CDI injection point that was &#8220;validated early&#8221; can fail later, or not, at runtime, which is the very sort of thing CDI is designed to prevent.</p>



<p>Overall, the APIs conflate the problems of object acquisition (&#8220;get me a ham sandwich&#8221;) with those of object production (&#8220;make a ham sandwich out of its parts and hand it over&#8221;), binding (&#8220;to make a ham sandwich, find bread, ham, cheese, mayo, mustard and lettuce&#8221;) and sourcing (&#8220;you find the bread in the breadbox unless it&#8217;s already out and then it&#8217;s on the counter, the cheese is in the cheese drawer, and the mayo is usually on the top shelf of the fridge, unless you have to open a new bottle….&#8221;). Then the results are served up with unpredictable scalar probing methods (unless I&#8217;m using CDI injection, I have to ask for the bread, then the condiments, then the lettuce and put them together, assuming I actually got results for these).  This is all very strange.  I just want a ham sandwich.  The person <em>making</em> the ham sandwich probably cares a great deal about all this stuff, but I wouldn&#8217;t be asking them for a ham sandwich if I wanted to make it myself!  (Also I&#8217;m never going to convert bread to mustard.)</p>



<p>Finally, an application developer also basically just wants a ham sandwich.  She wants to receive a <code>HerApplicationConfigThatSheDesigned</code> object in some ceremony-free manner that&#8217;s appropriate for the environment her application is in, and call typed methods on it at various points during the lifespan of her application to get the information she needs, handling errors in the way that she sees fit.  You can <a href="https://www.eclipse.org/lists/config-dev/msg00102.html">see examples of this in the wild</a>.  Consider this, and then re-read what&#8217;s above and sit with it.</p>



<p>There are so, so, so many ways this whole area could be better.  I hope to say more soon.</p>
]]></content:encoded>
					
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">3661</post-id>
		<media:content url="https://2.gravatar.com/avatar/58e3ea56bec4978a64e8ad60274b75cd8691435be2e44e6e69969986ed9b6399?s=96&#38;d=&#38;r=G" medium="image">
			<media:title type="html">lairdnelson</media:title>
		</media:content>
	</item>
		<item>
		<title>MicroProfile Config and Other Configuration Musings</title>
		<link>https://lairdnelson.wordpress.com/2021/08/12/microprofile-config-and-other-configuration-musings/</link>
		
		<dc:creator><![CDATA[Laird Nelson]]></dc:creator>
		<pubDate>Thu, 12 Aug 2021 17:58:52 +0000</pubDate>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Uncategorized]]></category>
		<guid isPermaLink="false">http://lairdnelson.wordpress.com/?p=3617</guid>

					<description><![CDATA[Disclaimer: I work for Oracle but never speak for them when I can help it, and especially not on this blog. Here are some unstructured musings on MicroProfile Config and configuration in Java in general. Extremely Quick MicroProfile Config Overview MicroProfile Config is a Java-centric, read-only configuration library. At its most fundamental level, you ask &#8230; <a href="https://lairdnelson.wordpress.com/2021/08/12/microprofile-config-and-other-configuration-musings/" class="more-link">Continue reading<span class="screen-reader-text"> "MicroProfile Config and Other Configuration&#160;Musings"</span></a>]]></description>
										<content:encoded><![CDATA[
<p>Disclaimer: I work for Oracle but never speak for them when I can help it, and especially not on this blog.</p>



<p>Here are some unstructured musings on MicroProfile Config and configuration in Java in general.</p>



<h1 class="wp-block-heading">Extremely Quick MicroProfile Config Overview</h1>



<p><a href="https://github.com/eclipse/microprofile-config/">MicroProfile Config</a> is a Java-centric, read-only configuration library.  At its most fundamental level, you ask it for a named textual value, tell the system what Java type in your program the textual value should have for this request, and get that typed value back.  For example, you might ask the system for a value corresponding to the name <code>wheel.circumference</code>, and specify that it should be returned as an <code>Integer</code>:</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: java; title: ; notranslate">
final Integer wheelCircumference = config.getValue("wheel.circumference", Integer.class);
</pre></div>


<p>Then, unbeknownst to the requesting application developer, MicroProfile Config uses at least three different abstractions to hide where this named scalar value comes from and how it is muscled into its final typed form.</p>



<p>Incidentally, by &#8220;scalar&#8221;, I mean, very loosely, something like very simple textual values.  That is, the atomic nugget of information in MicroProfile config is individual &#8220;flat&#8221; strings named by opaque names.  At the lowest level, you are always asking MicroProfile Config for individual text nuggets, not anything more complicated.  Everything else is built on top of that.</p>



<p>For example, MicroProfile Config <a href="https://github.com/eclipse/microprofile-config/blob/2.0/tck/src/main/java/org/eclipse/microprofile/config/tck/ConfigPropertiesTest.java">does layer some Java Beans-like object building facilities on top of this scalar value manufacturing system</a>.  You can sprinkle some annotations around and cause a <code>Wheel</code> object to come into being with <code>getCircumference()</code> and <code>getSpokes()</code> accessors, but this <code>Wheel</code> object will in such a case always be produced out of the scalar values for (say) <code>wheel.circumference</code> and <code>wheel.spokes</code> with appropriate data type conversion applied (a primitive form of part of the concept of <em>object binding</em>).  I&#8217;ll term these kinds of values made up of multiple other values <em>composites</em>: the <code>Wheel</code> type is a composite; its individual properties here all happen to be scalars.</p>



<p>So much for a quick overview of MicroProfile Config.</p>



<h1 class="wp-block-heading">Of Names And (Typed) Values</h1>



<p>One of the problems you have when you have any scalar-centric key-value system like MicroProfile Config is: if you ask for something by name, then you have to determine what the (Java) type of that thing is in order to use it.  Either there is exactly one type (for example, <code>System.getenv("foobar")</code> always yields a <code>String</code>), or you have to somehow know what the type of the named thing is, potentially applying appropriate type conversions along the way (for example, <code>System.getProperties().get("foobar")</code> returns an <code>Object</code>; it is now up to you to figure out what to do with that value).</p>



<p>MicroProfile Config forces the application developer to specify the type during lookup (e.g. <code>config.getValue("wheel.circumference", Integer.class)</code>).  (There&#8217;s no way to learn if it makes sense to type a <code>wheel.circumference</code> property as an <code>Integer</code>; you just kind of have to know that it is.  Or if you want to look at it the other way, equivalently, the configuration author has to use common sense to figure out what kind of usage her textual configuration nugget will have within any arbitrary application.  This is of course a problem, and we&#8217;ll talk about it later.)</p>



<p>One of the questions that immediately arises is: suppose the configuration information is fundamentally textual in nature.  Who converts <code>"27"</code> into (effectively) <code>Integer.valueOf(27)</code>?  (What if the configuration value is <code>"27 inches"</code>?)</p>



<p>MicroProfile Config has the concept of a stateless <code>Converter</code> that accepts a <code>String</code> and converts it to a particular type if possible.  There can be user-supplied <code>Converter</code>s and built-in ones.  All of them are overridable.  So somewhere in the system there will be a <code>Converter</code> that can convert <code>String</code>s to <code>Integer</code>s, so it will kick in and the application developer will get back a value equal to (say) <code>Integer.valueOf(27)</code>.  So far so good.</p>



<p>Of course, if the application developer calls <code>config.getValue("wheel.circumference", java.awt.Point)</code>, there may be no such <code>Converter</code> so she may be out of luck, but won&#8217;t learn this until runtime.  So, of course, she can supply her own <code>Converter</code> that converts <code>String</code>s to <code>Point</code>s, and hope that it is used (and not overridden deliberately or accidentally by some other component&#8217;s <code>Converter</code> that also converts <code>String</code>s to <code>Point</code>s but in a different way, by reading a different kind of textual format, for example).</p>



<p>This is where we start talking about the fact that <code>Converter</code>s can have priorities and are sorted in a particular way, can be packaged with any library or container, and discovered from various locations, and—</p>



<p>But let&#8217;s back way up.</p>



<p><strong>Why is the application developer looking up values by arbitrary names in the first place?</strong>  Is that really what she wants to do?  Isn&#8217;t this just an unfortunate means to an end?  Take some time to think about this.</p>



<p>Suppose she were magically able to call a typed method on a hypothetical configuration object sourced from a hypothetical configuration system instead:</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: java; title: ; notranslate">
final Integer circumference = HypotheticalConfiguration.get().getWheel(FRONT).getCircumference();
</pre></div>


<p>From <em>her</em> point of view, how the circumference of the front wheel is found or produced or manufactured by the configuration system is entirely immaterial.  Maybe it was deserialized.  Maybe it was a Java <code>Record</code> that got assembled out of its record components somehow.  Maybe it fell from the sky.  Maybe Jackson kicked in and did object binding from JSON.  Maybe it&#8217;s a JPA entity retrieved, already constructed and converted, from the database.  Maybe it sprang full-fledged from an underlying directory system.  Maybe it was built by a JNDI <code>ObjectFactory</code>.  Maybe it resulted from a storm of Java Beans <code>PropertyEditor</code> operations.  She doesn&#8217;t know, and she doesn&#8217;t care.  Nor does she have to worry about accidentally making typos in configuration value names, or about supplying the wrong data conversion type.  If you look carefully, her use case does not mention the production side of things at all.  There&#8217;s a wheel circumference, you get it by calling <code>getCircumference()</code> on a <code>Wheel</code> object, and it returns an <code>Integer</code>.  The end.</p>



<p>Remember, she is an application developer, so she can (and ultimately must) express her requirements using the Java language—as she does here.  Here, she defines the composite <code>Wheel</code> type to feature whatever properties of whatever type she wishes.  There is no need to &#8220;go after&#8221; those properties individually as textual scalars by some kind of name.  It is up to whatever &#8220;back end&#8221; of the <strong>hypothetical</strong> configuration system to make whatever is needed, however it wants to, which may involve textual scalars and object binding or may not.  Those kinds of problems are now pushed off entirely into the domain where they properly belong: that of production, object binding and instantiation, which are none of her concerns.  But more on that aspect a little later.</p>



<p>So why <em>are</em> there these arbitrarily-typed key-value Java configuration systems, if there are so many opportunities to make mistakes with them?</p>



<p>For environment variables, of course, the answer is simple: environment variables can be passed to programs of any type, not just Java, so they are expressed in the lowest common denominator of the operating system: simple humble strings, so that&#8217;s what you ask for as an application developer, and exactly what you receive.</p>



<p>And something like <code>System.getProperty("foobar")</code> is a convenient wrapper around <code>(String) Hashtable.get("foobar")</code> because system properties can be supplied on the command line where, again, they must be strings.  (However, note that it is possible for someone to install a <code>Glorp</code>-typed object into the <code>Properties</code> object returned by <code>System.getProperties()</code> under the name &#8220;<code>foobar</code>&#8221; in which case <code>System.getProperty("foobar")</code> will of course fail.  There&#8217;s our old friend type conversion again and all the problems it entails.)</p>



<p>And for systems like JNDI or <code>java.util.Preferences</code> that allow for reading <em>and</em> binding you need to make sure that the application developer can write things into the abstracted directory that other programs written in other languages can read.  So scalars are the way to go here.</p>



<p>But for Java-only, read-only configuration?  Where the application developer doesn&#8217;t have to write anything &#8220;back&#8221; to the configuration system?  <strong>There is nothing in her use cases that requires untyped lookups by arbitrary name.</strong>  It is, to be sure, a pattern that we&#8217;ve all gotten used to because we all look up system properties and environment variables by arbitrary name, and system properties and environment variables are some of the things that configuration systems usually abstract over, but, again, there&#8217;s no <em>requirement</em> that this be so of a configuration system that supports application developer use cases.</p>



<p>Back to MicroProfile Config for a moment.</p>



<p>In MicroProfile Config, you <em>can</em> inject a composite object like this (though I don&#8217;t think you can look one up programmatically?):</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: java; title: ; notranslate">
// Somewhere in your program
@Inject
@ConfigProperties
@Front
private Wheel wheel;

// …provided that somewhere else you also have something like:
@ConfigProperties(prefix = "wheel")
@Front
public interface Wheel {
  public Integer getCircumference();
  public Integer getSpokes();
}
</pre></div>


<p>So they recognize the utility of composite configuration objects even if it&#8217;s clumsy for them to make one.</p>



<p>Now <code>wheel</code> in the example above will receive an instance of <code>Wheel</code> whose <code>getCircumference()</code> method will return an <code>Integer</code> created from the <code>wheel.circumference</code> textual property as converted by some <code>Converter&lt;Integer&gt;</code> somewhere (likewise, the <code>getSpokes()</code> method will return an <code>Integer</code> created from the <code>wheel.spokes</code> textual property as converted by some <code>Converter&lt;Integer&gt;</code> somewhere).</p>



<p>This is nicer for the application developer, because now she doesn&#8217;t have to worry about spelling out scalar names (typos!) and (often non-discoverable) data conversions (oops, wrong type) herself.</p>



<p>But even here it strikes me as bizarre that MicroProfile Config leaks concerns from one domain into another.  Specifically, it leaks object binding concerns (the fiddly bits about how a <code>Wheel</code> is produced, including the <code>prefix</code> element of the strangely-named <code>ConfigProperties</code> annotation) into the application developer&#8217;s usage domain (she doesn&#8217;t give a flying hoot about how a <code>Wheel</code> is produced, but oddly here has to indicate binding information herself even though binding isn&#8217;t her concern, and either the configuration author has to make sure that her named textual configuration nuggets have exactly the names dictated by the object binding requirements—e.g. drop &#8220;<code>get</code>&#8220;, lowercase the first character of what follows—or the application developer has to make sure that her composite object has accessors that line up with the configuration author&#8217;s textual configuration nugget names).</p>



<p>Why not leave binding concerns where they belong (on the &#8220;production&#8221; side), and usage concerns where they belong (on the &#8220;consumption&#8221; side)?</p>



<h1 class="wp-block-heading">On DropWizard</h1>



<p>Let&#8217;s take a hopefully relevant detour into DropWizard land for a moment.  Disclaimer: I have no affiliation with or opinion about DropWizard; it is just an example of a larger point I want to make.</p>



<p>In <a href="https://www.dropwizard.io/en/latest/getting-started.html#creating-an-application-class">DropWizard</a>, a master configuration object is handed to you.  You can&#8217;t escape it.  You must define such a configuration object.  Here&#8217;s what I mean; look for where <code>HelloWorldConfiguration</code> shows up:</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: java; title: ; notranslate">
public class HelloWorldApplication extends Application&lt;HelloWorldConfiguration&gt; {
    public static void main(String&#91;] args) throws Exception {
        new HelloWorldApplication().run(args);
    }

    @Override
    public String getName() {
        return &quot;hello-world&quot;;
    }

    @Override
    public void initialize(Bootstrap&lt;HelloWorldConfiguration&gt; bootstrap) {
        // nothing to do yet
    }

    @Override
    public void run(HelloWorldConfiguration configuration,
                    Environment environment) {
        // nothing to do yet
    }
}
</pre></div>


<p>When your <code>HelloWorldApplication</code> starts (via its <code>main</code> method), the <code>run</code> method will eventually be called, and you can see that it is supplied with a master configuration object (in this case a <code>HelloWorldConfiguration</code> object).  How did it get there?  It doesn&#8217;t matter.</p>



<p>Here&#8217;s what the <code>HelloWorldConfiguration</code> object might look like (I&#8217;ve cribbed this whole thing from the DropWizard documentation itself):</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: java; title: ; notranslate">
import io.dropwizard.Configuration;
import com.fasterxml.jackson.annotation.JsonProperty;
import javax.validation.constraints.NotEmpty;

public class HelloWorldConfiguration extends Configuration {
    @NotEmpty
    private String template;

    @NotEmpty
    private String defaultName = "Stranger";

    @JsonProperty
    public String getTemplate() {
        return template;
    }

    @JsonProperty
    public void setTemplate(String template) {
        this.template = template;
    }

    @JsonProperty
    public String getDefaultName() {
        return defaultName;
    }

    @JsonProperty
    public void setDefaultName(String name) {
        this.defaultName = name;
    }
}
</pre></div>


<p>If you&#8217;ve been around the block a few times, you can see that there are <a href="https://javadoc.io/doc/com.fasterxml.jackson.core/jackson-annotations/latest/index.html">Jackson annotations</a> all over it.  (You&#8217;ll also know that the setters are not necessary!)  But apart from that (and even the annotations aren&#8217;t necessary depending on how Jackson is used), it&#8217;s a POJO.  As it should be!</p>



<p>Now look back at the<code>HelloWorldApplication</code>.  The application developer has no idea where the <code>HelloWorldConfiguration</code> object came from or how it was made, <em>when you look at the actual application code</em>.  That is, the use case made manifest by the application code itself has no object binding or production concerns in it whatsoever.  At an abstract level, the application developer has:</p>



<ul class="wp-block-list"><li>Defined what her configuration looks like (by virtue of creating the <code>HelloWorldConfiguration</code> type and defining the getters she&#8217;ll call on the <code>HelloWorldConfiguration</code> object in her <code>run</code> method)</li><li><em>Advertised</em> this configuration to whoever and/or whatever is going to supply her with such a thing</li></ul>



<p>By <em>advertising</em>, I mean an abstract notion of: has put this class somewhere where people (such as configuration authors) know to look for it.  Advertising can take many forms, from placing a file in a well-known spot to listing the file&#8217;s location in a file that is itself in a well-known spot (e.g. the Java <code>ServiceLoader</code> contract), or a variety of other means.  In DropWizard, some of the advertising is baked into the application itself: if you were, for example, to <code>javap</code> the <code>HelloWorldApplication.class</code> file, you would be able to figure out what the master configuration object is.</p>



<p>Anyway, the master configuration object here is just Java code.  There are no name-based lookups involved.  There&#8217;s no data conversion.  There are no conventions to follow.  The application developer will call <code>configuration.getTemplate()</code>, for example, and get exactly what she is expecting as an instance of exactly the Java type she&#8217;s expecting it.  If she added <code>getComplicatedHairball()</code> to it, then she&#8217;d get a <code>ComplicatedHairball</code> object back to work with.  She can&#8217;t make typos, or her class won&#8217;t compile.  She can&#8217;t specify the wrong data types for conversion.  Namespace clashes between components are no longer a thing.  All of this is because use case concerns are in the right place and don&#8217;t leak.</p>



<p>Back to DropWizard specifics.  On the production and unmarshaling side, DropWizard is opinionated: it turns out that the configuration author must write her configuration in YAML, and Jackson is used to muscle this YAML into an instance of the master configuration object, following its usual object binding conventions.  (Many of you will know that this of course does not require that there be any annotations on the <code>HelloWorldConfiguration</code> object at all, and that any customizations can be made using mixin annotations or Jackson <code>ObjectMapper</code> incantations.  The point here is that even the Jackson bits are not required to sully the <code>HelloWorldConfiguration</code> if you really want to keep things pure.)</p>



<p>They&#8217;ve also left themselves some wiggle room with this sensible architecture: even though DropWizard is currently opinionated, if you squint you can see that if it decided to change its configuration-object-producing machinery from YAML-and-Jackson to XML-and-JAXB, the application developer&#8217;s code would not really change.</p>



<h1 class="wp-block-heading">Fantasyland</h1>



<p>DropWizard is opinionated on how configuration objects are unmarshaled, but as noted there&#8217;s some architectural wiggle room, and so now let&#8217;s travel to fantasyland for a moment.</p>



<p>Let&#8217;s pretend there exists in the world some kind of facility like DropWizard&#8217;s configuration machinery, but instead of requiring the configuration author to write YAML (or JSON) in a specific file or classpath resource, and instead of requiring Jackson to be used for object binding—in fact, instead of requiring object binding at all—let&#8217;s pretend this &#8220;back end&#8221; production mechanism is pluggable.  Let&#8217;s pretend a hypothetical configuration system can locate what back end it&#8217;s going to use to make configuration objects.  Seriously, let&#8217;s pretend.</p>



<p>Oh look, nothing really changes from the application developer&#8217;s use cases or standpoint!</p>



<p>Specifically, she doesn&#8217;t have to change any names or data type conversion code.  She doesn&#8217;t have to make sure that composites have names that &#8220;work with&#8221; the configuration system.  She still can&#8217;t make typos and still can&#8217;t provide incorrect typing information.  Component namespaces are still safe.  All of those problems are now (properly!) the concern of whatever concrete back end provider is in the picture, and the concrete back end provider doesn&#8217;t have to deal in scalars at all.</p>



<p>Let&#8217;s further pretend that the back end provider is not one that uses object binding, Jackson- or MicroProfile Config-based or otherwise.  Perhaps it is something like Hibernate that loads an entity straight out of a database.  In this example, the data conversion happens at the native database level so there&#8217;s no need for data conversion to surface at the configuration system level at all, because it&#8217;s already being handled by a combination of the database, JDBC and Hibernate.</p>



<p>Or let&#8217;s say that MicroProfile Config is the back end provider, and uses a whole bunch of <code>config.getValue("someScalar", SomeType.class)</code> invocations to assemble a composite, namely the master configuration object.  Or maybe somehow it uses the same mechanism that it uses to produce <code>@ConfigProperties</code>-annotated objects today.  The usual problems that MicroProfile Config has with things like &#8220;which <code>Converter</code> will be used&#8221; and &#8220;which <code>ConfigSource</code> will produce scalar value <code>x</code>&#8221; and &#8220;how do I set an empty string&#8221; and &#8220;what do we do about nondeterministic <code>ConfigSource</code> ordering&#8221; and so on are still in play, but now they are isolated where they belong, namely in the domain of object production and binding, and do not impact the application developer use cases in any way.  The configuration author—the person responsible for authoring the scalar textual values that MicroProfile Config will fundamentally consume—also now has the benefit that she can at least have the possibility of discovering what configuration she must supply since the master configuration object type is advertised, and contains all relevant naming and typing information.</p>



<p>Or maybe the master configuration object itself simply <em>is</em> a MicroProfile Config <code>Config</code> object, if the application developer desperately wants to work fundamentally with it for some reason, in which case the back end is absurdly simple.  Who am I to stop her?  Or maybe it&#8217;s a <code>Properties</code> object.  Or a JNDI <code>Context</code>.  Or a <code>File</code>.  Or anything else, really.  Fantasyland handles this too because all that is required is that it be able to produce a Java object of some kind that the application developer can work with.</p>



<h1 class="wp-block-heading">On Configuration in General</h1>



<p>This starts to get into: now we&#8217;re just talking about plain Java objects, so just what <em>is</em> configuration anyway?  That of course is an enormous question and I don&#8217;t have the time, space or inclination to deal with that here.  But!  I can say that as far as a configuration system is concerned: configuration objects should probably be able to be whatever you want them to be.  On the reading end, it&#8217;s just POJOs.  On the production/writing end, it&#8217;s just how those objects get built.</p>



<p>Often times here is an unspoken assumption that configuration systems that produce &#8220;rich&#8221; Java objects—composites—should tread carefully, as there are many other subsystems that deal with the production and management of such objects.  For example, CDI lets you write producer methods that produce rich objects out of other objects.  So shouldn&#8217;t CDI be in charge of producing rich objects?  In some vague unspecified way you want configuration to not really tread on these subsystems&#8217; toes.</p>



<p>Here I tend to think that a configuration object is whatever the application developer wants it to be.  If she wants a configuration system to produce a ferociously complicated master configuration object singleton, then that is her (possibly ill-advised) right.  It may not be a very good choice, but it isn&#8217;t really something that the configuration system should have an opinion about.</p>



<p>An application developer will <em>probably</em> want to work with a master configuration object that is <em>relatively</em> simple that can then be used as raw materials for higher order Java objects.  &#8220;Relatively&#8221; simple is of course fuzzy:  A <code>Bicycle</code> CDI bean, for example, might be produced by a CDI producer method, not by configuration, but using two <code>Wheel</code> objects sourced from the master configuration object and injected into the producer method&#8217;s parameter list.</p>



<p>At some point I hope to prototype such a system so it&#8217;s easier to talk about; stay tuned.</p>
]]></content:encoded>
					
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">3617</post-id>
		<media:content url="https://2.gravatar.com/avatar/58e3ea56bec4978a64e8ad60274b75cd8691435be2e44e6e69969986ed9b6399?s=96&#38;d=&#38;r=G" medium="image">
			<media:title type="html">lairdnelson</media:title>
		</media:content>
	</item>
		<item>
		<title>CDI Production</title>
		<link>https://lairdnelson.wordpress.com/2021/05/21/cdi-production/</link>
		
		<dc:creator><![CDATA[Laird Nelson]]></dc:creator>
		<pubDate>Fri, 21 May 2021 18:21:23 +0000</pubDate>
				<category><![CDATA[CDI]]></category>
		<category><![CDATA[Java]]></category>
		<guid isPermaLink="false">http://lairdnelson.wordpress.com/?p=3579</guid>

					<description><![CDATA[Dependency injection involves making things. Here&#8217;s a condensed version of how things are made in CDI. You may also be interested in my larger CDI tutorial. This is a living document that I intend to update frequently. I may break it up into separate posts later. We&#8217;re going to start from the bottom and inside, &#8230; <a href="https://lairdnelson.wordpress.com/2021/05/21/cdi-production/" class="more-link">Continue reading<span class="screen-reader-text"> "CDI Production"</span></a>]]></description>
										<content:encoded><![CDATA[
<p>Dependency injection involves making things.  Here&#8217;s a condensed version of how things are made in CDI.  You may also be interested in my <a href="/2019/05/18/a-cdi-primer-part-0/">larger CDI tutorial</a>.</p>



<p>This is a living document that I intend to update frequently.  I may break it up into separate posts later.</p>



<p>We&#8217;re going to start from the bottom and inside, and work our way up and out.  That means we&#8217;ll look at the low-level, internal machinery of CDI first, which most users rarely see.  Then we will work up and out to annotated classes, from which the low-level constructs are derived, and which are what users create and manipulate.</p>



<p>Finally, terms in CDI can refer to each other, so it is definitely a challenge to present things in order.  There will be times where I will ask you to take things on faith, and then will circle back to address them in more detail once the terms I need to talk about them are more firmly in place.</p>



<p>OK, off we go.</p>



<h1 class="wp-block-heading">Contextuals</h1>



<p>At the bottom of CDI you have <code><a href="https://jakarta.ee/specifications/cdi/3.0/apidocs/jakarta/enterprise/context/spi/Contextual.html">Contextual</a></code>s.  <code>Contextual</code>s are stateless factories that create and destroy <em><a href="https://jakarta.ee/specifications/cdi/3.0/jakarta-cdi-spec-3.0.html#concepts">contextual instances</a></em>.  Think of a contextual instance, for now, as a regular Java object, although they can be more complicated than that.</p>



<p>One kind of <code>Contextual</code> is a <code><a href="https://jakarta.ee/specifications/cdi/3.0/apidocs/jakarta/enterprise/context/spi/Bean.html">Bean</a></code>.  A <code>Bean</code> is a <code>Contextual</code> paired with some descriptive and lifecycle-related attributes.  We&#8217;ll assume that <code>Bean</code>s are the only kind of <code>Contextual</code> in the world, so we&#8217;ll just talk about them instead.</p>



<h1 class="wp-block-heading">Beans and Contextual Instances</h1>



<p>The lifecycle of any contextual instances that a <code>Bean</code> creates is not under its control.  It is instead reified by a <code><a href="https://jakarta.ee/specifications/cdi/3.0/apidocs/jakarta/enterprise/context/spi/Context.html">Context</a></code> that the <code>Bean</code> is indirectly affiliated with.  A <code>Context</code> doesn&#8217;t create or destroy contextual instances, but it controls when they are created by <code>Bean</code>s, stores them, and controls when they are destroyed by <code>Bean</code>s.</p>



<p>When a <code>Context</code> needs a new instance—because, for example, it has been asked for one and doesn&#8217;t have one already stored—it always asks an affiliated, appropriate <code>Bean</code> to create one.  This is why an instance created by a <code>Bean</code> and stored by a <code>Context</code> is therefore called a <em>contextual</em> instance.  We will discuss why a <code>Context</code> might be asked for a contextual instance, and by whom, soon.</p>



<p>Even though we can&#8217;t really fully talk about them, there are some other characteristics of contextual instances that are worth mentioning up front, just to locate them in architectural space.  They&#8217;re worth mentioning now because it is a <code>Bean</code>&#8216;s <a href="https://jakarta.ee/specifications/cdi/3.0/apidocs/jakarta/enterprise/context/spi/Contextual.html#create-jakarta.enterprise.context.spi.CreationalContext-"><code>create</code> method</a> that is ultimately responsible for them, not some other piece of CDI machinery.  Don&#8217;t worry if you don&#8217;t understand these characteristics yet.</p>



<p>First, a contextual instance may be <em>intercepted</em> or <em>decorated</em>.  Because of this, it may be a proxy object—proxying is a common strategy for implementing interception and decoration—or it may not.  A <code>Bean</code> does not have to implement decoration or interception at all, but if they <em>are</em> to be implemented, they must be implemented, ultimately, by a <code>Bean</code>&#8216;s <code>create</code> method, in whatever way it chooses.  A <code>Bean</code> does not necessarily have to use proxying to implement these features.  Don&#8217;t worry that we haven&#8217;t discussed interception, decoration or what it means for something to be a proxy object yet.</p>



<p>Second, under no circumstances will a contextual instance be a <em><a href="https://jakarta.ee/specifications/cdi/3.0/jakarta-cdi-spec-3.0.html#client_proxies">client proxy</a></em>, a very specific CDI term that we will also cover later (that is sadly unrelated to the possible proxying discussed above).  <code>Bean</code>s never create client proxies.  This will be relevant when we discuss dependency injection in more detail.  For now, it is just an interesting fact using a term that has yet to be defined.</p>



<p>Third, a contextual instance is often an instance of a type that depends on other types.  A <code>Unicycle</code> interface might depend on a <code>Wheel</code> class, for example: when a new <code>Unicycle</code> implementation of some kind is created (by a <code>Bean</code>), it may need to be supplied with a <code>Wheel</code> object.  Acquiring and supplying these objects is, loosely speaking, <em>dependency injection</em>.  We can&#8217;t fully talk about dependency injection yet, but for now just know that it is a <code>Bean</code>&#8216;s <code>create</code> method&#8217;s job to perform it.</p>



<p>So much for <code>Bean</code>s and the basics of who calls them and what they do.</p>



<h1 class="wp-block-heading">Contexts</h1>



<p>Rising up and out a level, low-level machinery within CDI can ask a <code>Context</code> for a contextual instance of something.  It supplies a <code>Context</code> with a relevant <code>Bean</code>, and asks for an appropriate contextual instance that the <code>Context</code> manages on behalf of that <code>Bean</code>.  The <code>Context</code>, in turn, may discover that it does not have an appropriate contextual instance yet, and so might turn around and ask the supplied <code>Bean</code> to create one.  A <code>Context</code> never creates contextual instances itself.</p>



<p>A <code>Context</code> can be <em><a href="https://jakarta.ee/specifications/cdi/3.0/jakarta-cdi-spec-3.0.html#active_context">active</a></em> or not with respect to a given <code>Thread</code>. There can be only one <code>Context</code> active for a <code>Thread</code> at a time and its activeness can change at any point for any reason.</p>



<h2 class="wp-block-heading">Scopes</h2>



<p>A <code>Context</code> is the partial or full implementation of a notional lifecycle represented by the concept of a <em><a href="https://jakarta.ee/specifications/cdi/3.0/jakarta-cdi-spec-3.0.html#scopes">scope</a></em>.  This means a <code>Context</code> stores a contextual instance created by a <code>Bean</code> for some period of time, for a given <code>Thread</code>.  Or, perhaps it never stores anything but just arranges for contextual instances to be created every time it is asked for them.  That is legal too, and in fact <a href="https://jakarta.ee/specifications/cdi/3.0/jakarta-cdi-spec-3.0.html#dependent_context">CDI depends on the existence of such a <code>Context</code></a>.</p>



<p>If a <code>Context</code> stores contextual instances, it typically (but, I suppose, not necessarily) does so by affiliating them in storage with the <code>Bean</code> that created them.  This means that a <code>Bean</code> is both a mechanism for creating a contextual instance, and, often, a key to identify that contextual instance later.</p>



<p>As noted above, a <code>Context</code> implements part, or all, of a scope.  A scope is a concept representing a notional lifecycle and is associated with one or more <code>Context</code>s.  Sometimes people talk about scopes and <code>Context</code>s as if they are the same thing.  They are not, since a scope may be implemented by one or more <code>Context</code>s.  Finally, a scope is notionally identified by its <em>scope type</em>, which is another notion that exists only to identify its scope.  A scope may be identified by only one scope type and a scope type identifies only one scope.</p>



<p>A scope type is reified by a Java annotation type that itself must be annotated with either <code><a href="https://jakarta.ee/specifications/dependency-injection/2.0/apidocs/jakarta/inject/Scope.html">jakarta.inject.Scope</a></code> or <code><a href="https://jakarta.ee/specifications/cdi/3.0/apidocs/jakarta/enterprise/context/NormalScope.html">jakarta.enterprise.context.NormalScope</a></code>.  A scope is said to be a <em><a href="https://jakarta.ee/specifications/cdi/3.0/jakarta-cdi-spec-3.0.html#normal_scope">normal scope</a></em> if its reifying annotation type is annotated with <code>jakarta.enterprise.context.NormalScope</code>, and a <em><a href="https://jakarta.ee/specifications/cdi/3.0/jakarta-cdi-spec-3.0.html#normal_scope">pseudo scope</a></em> otherwise.  (There are ways in CDI to programmatically register other kinds of arbitrary annotation types as scopes, but for now we&#8217;ll ignore those.)  We will talk about scopes—particularly normal scopes—more fully in a little bit.</p>



<p>A <a href="https://jakarta.ee/specifications/cdi/3.0/apidocs/jakarta/enterprise/context/spi/Context.html#getScope--"><code>Context</code> has a method that can retrieve its associated scope type</a>.</p>



<h2 class="wp-block-heading">Linking Scopes, Contexts, Beans and Contextual Instances</h2>



<p>Low-level machinery within CDI often finds itself armed with just a <code>Bean</code> and the need to get a contextual instance that a given <code>Bean</code> can create.  To do this, it does <em>not</em> ask the <code>Bean</code> to create such an instance directly.  If it did, it would bypass the useful lifecycle management machinery that <code>Context</code>s implement.</p>



<p>Instead, it <a href="https://jakarta.ee/specifications/cdi/3.0/apidocs/jakarta/enterprise/inject/spi/BeanAttributes.html#getScope--">asks the <code>Bean</code> for its scope type</a>—something every <code>Bean</code> has as part of its descriptive and lifecycle-related attributes—and then asks other low-level CDI machinery for all the <code>Context</code>s that also have that scope annotation type and thus collectively implement the corresponding scope (usually there&#8217;s just one).  From the resulting set of <code>Context</code>s, it <a href="https://jakarta.ee/specifications/cdi/3.0/apidocs/jakarta/enterprise/inject/spi/BeanManager.html#getContext-java.lang.Class-">gets the one that is active for the current <code>Thread</code></a>.  Then it passes the <code>Bean</code> to the <code>Context</code> and asks for a corresponding contextual instance.  The contextual instance that is returned may have been a cached one or a new one; the caller does not know.</p>



<p>So much for the basics of <code>Context</code>s and how they interact with <code>Bean</code>s.</p>



<h1 class="wp-block-heading">Normal and Pseudo Scopes</h1>



<p>Rising up and out another level, recall that a scope may be a normal scope or a pseudo scope.  A normal scope is, loosely speaking, one whose contract guarantees the user that any objects she sees whose types logically belong to that scope will be suitable no matter where they are used.</p>



<p>For example, consider a normal scope representing a request-oriented lifecycle, and a caller who takes delivery of an object whose type logically belongs to that request scope.  Wherever in her system that object shows up, regardless of what she does with it, it should be the right object, i.e. the one for the current request, or should be invalid in some way if there is no current request, and so on.  So she can&#8217;t just take delivery of an ordinary contextual instance, because an object can&#8217;t replace itself with another in some magic way.</p>



<p>To help with this, if a <code>Context</code> indicates that it implements a normal scope (remember, a <code>Context</code> can supply its scope annotation type, as can the <code>Bean</code>s that make the contextual instances it manages), then a CDI implementation must do some prescribed things to ensure the normal scope contract is honored.</p>



<p>First, from the user&#8217;s perspective, if she receives a <code>Unicycle</code> object from as-yet-unspecified machinery that plays by the normal scope contract rules, that <code>Unicycle</code> object must behave like a &#8220;real&#8221; <code>Unicycle</code> object.  Methods that she can invoke on a &#8220;real&#8221; <code>Unicycle</code> object must work as expected.  <code>instanceof</code> tests must succeed.  And so on.</p>



<p>Second, when she invokes a method on her received <code>Unicycle</code> object, it must, because of normal scope rules, somehow just-in-time find the &#8220;real&#8221; underlying <code>Unicycle</code> that is appropriate for the usage.  In CDI, the &#8220;real&#8221; underlying <code>Unicycle</code> in this usage scenario will always be a contextual instance definitionally managed by a <code>Context</code> partially implementing the normal scope in question.  We have seen how a <code>Context</code> supplies contextual instances, so we can see a glimmer of a way that this might be implemented generally.  Then the method in question that the user invoked must arrange for this &#8220;real&#8221; <code>Unicycle</code> contextual instance that was found to receive the same method invocation in such a way that the user is none the wiser.</p>



<p>This is a classic example of <em>proxying</em>.  A proxy in this general sense is a wrapper that (a) behaves as <em>if</em> it were a &#8220;real&#8221; object itself but actually (b) forwards all calls it receives to the &#8220;real&#8221; object it notionally wraps.  Typically embedded within its innards is a strategy for finding the &#8220;real&#8221; object just-in-time (or perhaps it requires the real object to be supplied to it initially) and re-invoking on the &#8220;real&#8221; object whatever method the user invoked on <em>it</em>.  Here, our user has taken delivery of a proxy that behaves just like a <code>Unicycle</code> but looks up the &#8220;real&#8221; <code>Unicycle</code> contextual instance just-in-time under the covers when a method is called on the proxy.</p>



<h1 class="wp-block-heading">Client Proxies and Contextual References</h1>



<p>A proxy object like this that implements these rules of CDI&#8217;s normal scopes is a very specific kind of proxy.  It is known in CDI as a <em><a href="https://jakarta.ee/specifications/cdi/3.0/jakarta-cdi-spec-3.0.html#client_proxies">client proxy</a></em>.  A user who takes delivery of objects from upper-level CDI machinery receives client proxies when the lower-level machinery recognizes the <code>Bean</code> in play is affiliated with a normal scope.  (There are some other edge cases where client proxies might also be involved, but we won&#8217;t cover them here.)</p>



<p>A client proxy always wraps, or delegates to, a contextual instance served up (definitionally) by a <code>Context</code>.  A client proxy never wraps, or delegates to, another client proxy.  As we&#8217;ve seen earlier, a <code>Bean</code> never creates a client proxy.  We haven&#8217;t yet talked about what <em>does</em> create a client proxy, where exactly they come from, how long they live, how you might use one or detect that you are using one, or any of that, but we will soon.</p>



<p>A client proxy is one kind of two kinds of <em><a href="https://jakarta.ee/specifications/cdi/3.0/jakarta-cdi-spec-3.0.html#contextual_reference">contextual reference</a></em>.  A contextual reference is either a client proxy or a contextual instance stored and supplied by a <code>Context</code> implementing a pseudo scope.  Ordinary users doing ordinary things always interact with contextual references and ideally don&#8217;t know whether they are client proxies or contextual instances.</p>



<p>A caller can ask a <code><a href="https://jakarta.ee/specifications/cdi/3.0/apidocs/jakarta/enterprise/inject/spi/BeanManager.html">BeanManager</a></code> for a contextual reference.  The <code><a href="https://jakarta.ee/specifications/cdi/3.0/apidocs/jakarta/enterprise/inject/spi/BeanManager.html#getReference-jakarta.enterprise.inject.spi.Bean-java.lang.reflect.Type-jakarta.enterprise.context.spi.CreationalContext-">getReference(Bean,Type,CreationalContext)</a></code> method accepts:</p>



<ul class="wp-block-list"><li>a <code>Bean</code> (so that <code>Bean</code> can ultimately be supplied to a <code>Context</code> when contextual instances need to be retrieved)</li><li>a <code>Type</code> representing how that contextual reference will be used and a type that the contextual reference must implement</li><li>a <code>CreationalContext</code> which is not relevant for our purposes yet</li></ul>



<p>(Additionally, the <code>Type</code> needs to designate a kind of contextual instance the <code>Bean</code> in question can create.)</p>



<p>The <code>BeanManager</code> will ensure that the right kind of contextual reference—properly implementing at least the supplied <code>Type</code>—will be returned.  If the scope governing the lifecycle of the kind of reference to be returned is a normal scope, then the contextual reference that is returned will be a client proxy (that knows how to get the right kind of contextual instance when needed, and that forwards method calls to it transparently).  If instead the scope is a pseudo scope, then the contextual reference that is returned will be a contextual instance.  (Recall from earlier that the contextual instance may still be <em>another</em> kind of proxy, e.g. to handle interception and decoration, but it will never be a <em>client</em> proxy.)</p>



<h2 class="wp-block-heading">Client Proxy Creation and Rules</h2>



<p>When the contextual reference that is returned <em>is</em> a client proxy, CDI does not dictate how a CDI implementation must implement it, but <em>does</em> dictate precisely how such a client proxy must behave.  It also imposes <a href="https://jakarta.ee/specifications/cdi/3.0/jakarta-cdi-spec-3.0.html#unproxyable">some restrictions on proxiable types</a> to make it easier for CDI implementations to build it.</p>



<p>First, any <code>Type</code> that the client proxy must implement can&#8217;t denote a <code>final</code> class.  This makes sense because one common way of implementing a proxy for a type is to extend the type in question and override its methods to find the &#8220;real&#8221; object and dispatch the relevant method invocation to it.  Obviously if the methods of a given class are <code>final</code>, a CDI implementation cannot build a client proxy that overrides them.</p>



<p>Second, any <code>Type</code> that the client proxy must implement that is a <code>Class</code> (as opposed to an interface) must have a zero-argument constructor.  This is so that a CDI implementation can actually create an instance of the class to be proxied, so that it can return it to the caller, and so that it is at least <em>possible</em> to do using something as simple as <code>Class::getDeclaredConstructor</code>.  Remember, the client proxy <em>itself</em> is not a contextual instance.  Rather, it is an object that wraps the machinery to find one and to delegate method invocations to it.  It is not therefore managed by a <code>Context</code>.  It is created &#8220;by hand&#8221; by the CDI implementation when needed.  The constructor is allowed to be <code>public</code>, <code>protected</code> or package-level.</p>



<p><a href="/2021/05/19/weld-and-client-proxy-creation/">Some CDI implementations use proprietary methods to avoid even this restriction</a>, but that behavior is not portable.</p>



<p>The most common strategy employed by CDI implementations to create client proxy classes is to use just-in-time bytecode generation.  With this strategy, a CDI implementation typically has a repeatable algorithm to generate a proxy class name given the name of a &#8220;real&#8221; class and <code>Bean</code> information.  If that generated class is not already found, a bytecode generation library such as ASM is used to generate a class with that name that extends the &#8220;real&#8221; class (or that implements the &#8220;real&#8221; interface) and plays by <a href="https://jakarta.ee/specifications/cdi/3.0/jakarta-cdi-spec-3.0.html#client_proxy_invocation">very specific rules</a>.</p>



<p>Once the client proxy class is generated, it is instantiated in whatever way the CDI implementation wants to instantiate it.  After all, it generated the code!  Weld chooses to do this in a very flexible manner that <a href="/2021/05/19/weld-and-client-proxy-creation/">I&#8217;ve written about previously</a>.  (The <em>simplest</em> way for a CDI implementation to do this is of course to simply invoke a zero-argument, non-<code>private</code> constructor reflectively, as noted above.)</p>



<p>Once this client proxy extending or implementing at least this particular <code>Type</code> is created, it is basically reusable, so most implementations choose to stash it away somewhere so that all this code generation and instantiation doesn&#8217;t have to happen again.</p>



<p>The client proxy so created now has to obey <a href="https://jakarta.ee/specifications/cdi/3.0/jakarta-cdi-spec-3.0.html#client_proxy_invocation">the rules</a> that govern all client proxies.  Specifically, it must, for every business method invoked on it:</p>



<ul class="wp-block-list"><li>Get the relevant contextual instance (the &#8220;real&#8221; object).  We&#8217;ve seen how that works in general.<ul><li>This can work here because at the time that the <code>BeanManager::getReference</code> call is made, and the client proxy class is generated, the <code>Bean</code> in question is supplied, so the generated client proxy code has access to the <code>Bean</code>&#8216;s information and can save it away (<code>Bean</code>s are immutable).  This means it can find the proper <code>Context</code> from which to acquire the right kind of contextual instance because it can ask the <code>Bean</code> for its scope annotation, and can then ask a <code>BeanManager</code> for a corresponding active <code>Context</code>.</li><li>We also know that it is the responsibility of a <code>Bean</code> to perform dependency injection, interception and decoration (if applicable), though we still haven&#8217;t delved into those topics yet.  So when the contextual instance is &#8220;loaded&#8221; by the innards of the client proxy, it is fully ready for business.</li></ul></li><li>Invoke the method in question on the contextual instance.  There&#8217;s no further processing that happens.</li></ul>



<p>You can see from these (very simple) rules that any logic related to interception, decoration and dependency injection must be located in the <code>Bean</code>&#8216;s <code>create</code> method, as noted several times above.  That is, client proxies are quite straightforward and just dispatch method calls.  They doesn&#8217;t do any interception or further proxying themselves.</p>



<p>So much for contextual references and one of their subtypes (client proxies).  The main takeaway is: If a user calls <code>BeanManager::getReference</code>, all the hard stuff is handled for her.</p>



<h2 class="wp-block-heading">Acquiring Contextual References in Beans</h2>



<p>Let&#8217;s circle back all the way down to the lowest level again and look, again, at the lowly <code>Bean</code> and, this time, at its <code>create</code> method.  We&#8217;ll do this because, recall, dependency injection must be performed (if it is to be performed at all) in this method, and to &#8220;do&#8221; dependency injection in CDI a <code>Bean</code> will need to acquire contextual references (the dependencies to inject), which we&#8217;ve just learned about.</p>



<p>As we&#8217;ve seen, the <code>Bean::create</code> method can do whatever it wants to make a contextual instance.  We&#8217;ve also seen that there is a method on <code>BeanManager</code> that allows the acquisition of contextual references for a given <code>Bean</code> and <code>Type</code>.</p>



<p>It doesn&#8217;t matter who is authoring a <code>Bean</code> implementation.  It could be an ordinary user, who is using CDI&#8217;s <em><a href="https://jakarta.ee/specifications/cdi/3.0/jakarta-cdi-spec-3.0.html#spi">portable extension</a></em> facilities to install that <code>Bean</code> into the CDI implementation, or it could be the CDI implementation itself, when everything starts up and it inspects annotated classes for relevant annotations and creates <code>Bean</code> objects to represent them.  All <code>Bean</code>s in the system use their <code>create</code> methods to create contextual instances.</p>



<p>Usually a <code>Bean</code> can get access to a <code>BeanManager</code> from within its <code>create</code> method.  For example, when the CDI implementation itself is creating a <code>Bean</code> object, often it installs a <code>BeanManager</code> into its <code>Bean</code> implementation.  Or in a custom <code>Bean</code> put together in a portable extension, often a <code>BeanManager</code> is available as a &#8220;reachable&#8221; object in the enclosing portable extension method.  Regardless, what is important is that it is relatively trivial for a <code>Bean</code> to get its hands on a <code>BeanManager</code> inside its <code>create</code> method.</p>



<p>Let&#8217;s consider a <code>Bean</code> implementation that a CDI implementation builds, i.e. <em>not</em> a custom <code>Bean</code> installed via an end-user portable extension, but one built as part of the CDI implementation itself to represent an annotated class.  Let&#8217;s say the <code>Bean</code> in question is the one that was creating <code>Unicycle</code> instances in our earlier example.</p>



<p>With just the tools covered above, even if the <code>Unicycle</code> class has a constructor that takes a <code>Wheel</code> object, you can see—perhaps faintly—that using the <code>BeanManager</code> the CDI implementation vendor employee implementing this <code>Bean</code> <code>create</code> method can:</p>



<ul class="wp-block-list"><li>first call <code>BeanManager::getReference</code> on the available <code>BeanManager</code> and pass in <code>Wheel.class</code> as the <code>Type</code>.  Assuming she can also use that <code>BeanManager</code> to find a <code>Bean</code> that makes <code>Wheel</code>-typed contextual instances, she can pass that <code>Bean</code> too to the <code>getReference</code> call, and she&#8217;ll get back a <code>Wheel</code>-typed contextual reference as we&#8217;ve discussed above, that she knows will be suitable for this usage point, regardless of what scope the <code>Wheel</code> may belong to</li><li>then call the ordinary constructor on the <code>Unicycle</code> class that takes a <code>Wheel</code> object and supply it with the contextual reference she just acquired</li><li>then return the plain simple <code>Unicycle</code> object as-is (assuming, for simplicity, that interception and decoration are no applicable here).</li></ul>



<p>Note that the only slightly odd thing this user has to do is acquire a contextual reference to a <code>Wheel</code> so that she can then stuff it in the <code>Unicycle</code> constructor.  She didn&#8217;t have to generate any bytecode or do anything magic with proxies or any of that.  If some other user now asks a <code>BeanManager</code> for a contextual reference implementing the <code>Unicycle</code> type, they&#8217;ll get a contextual reference to this <code>Unicycle</code> contextual instance.  If the scope in question for the <code>Bean</code> in question is a normal scope, then automatically the contextual reference they receive will be a client proxy.</p>



<p>More to come.</p>
]]></content:encoded>
					
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">3579</post-id>
		<media:content url="https://2.gravatar.com/avatar/58e3ea56bec4978a64e8ad60274b75cd8691435be2e44e6e69969986ed9b6399?s=96&#38;d=&#38;r=G" medium="image">
			<media:title type="html">lairdnelson</media:title>
		</media:content>
	</item>
		<item>
		<title>Weld and Client Proxy Creation</title>
		<link>https://lairdnelson.wordpress.com/2021/05/19/weld-and-client-proxy-creation/</link>
		
		<dc:creator><![CDATA[Laird Nelson]]></dc:creator>
		<pubDate>Wed, 19 May 2021 22:31:26 +0000</pubDate>
				<category><![CDATA[CDI]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Uncategorized]]></category>
		<guid isPermaLink="false">http://lairdnelson.wordpress.com/?p=3557</guid>

					<description><![CDATA[(Taking a break from my blog post series in progress to write down stuff that I stepped through today on how Weld creates client proxies.) The CDI specification says that if you have a managed bean in a normal scope (think: class with something like @ApplicationScoped or @RequestScoped on it), it must have a non-private, &#8230; <a href="https://lairdnelson.wordpress.com/2021/05/19/weld-and-client-proxy-creation/" class="more-link">Continue reading<span class="screen-reader-text"> "Weld and Client Proxy&#160;Creation"</span></a>]]></description>
										<content:encoded><![CDATA[
<p>(Taking a break from my blog post series in progress to write down stuff that I stepped through today on how Weld creates client proxies.)</p>



<p>The CDI specification says that if you have a managed bean in a normal scope (think: class with something like <code>@ApplicationScoped</code> or <code>@RequestScoped</code> on it), it must have a non-private, zero-argument constructor (and must not be <code>final</code>) so that a CDI implementation can proxy it.</p>



<p>You may have noticed when using Weld&#8217;s implementation of CDI SE that this seems not to be required.  I can do this:</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: plain; title: ; notranslate">
@ApplicationScoped // normal scope
public class B {
  private B() {} // hmm, seems to violate specification
  @Override public String toString() { return "B"; }
}
</pre></div>


<p>…and can inject an instance of that wherever I like:</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: plain; title: ; notranslate">
@Dependent
public class A {
  @Inject
  public A(final B b) { // hmm; how does CDI/Weld make b?
    super();
    System.out.println(b); // you'll see "B" on the console
  }
}
</pre></div>


<p>Here is how that works.</p>



<p>When Weld&#8217;s CDI SE implementation starts up, it <a href="https://docs.jboss.org/weld/reference/latest/en-US/html/configure.html#relaxedConstruction">looks for a configuration item that indicates <em>relaxed construction</em></a>.  This can be supplied in a few different ways, but the easiest way to supply it is by setting the <code>org.jboss.weld.construction.relaxed</code> System property to a textual representation of a boolean value (i.e. &#8220;<code>true</code>&#8221; or &#8220;<code>false</code>&#8220;).  <strong>In Weld&#8217;s implementation of CDI SE, if you do nothing, the value of this configuration item is effectively <code>true</code>.  In Weld&#8217;s implementation of CDI as found in application servers, the value of this configuration item is effectively <code>false</code>.</strong>  This is worth noting.</p>



<p>First, the easy path: if for whatever reason relaxed construction is not enabled, then we stop here. My example above will fail and Weld will correctly tell you that it has no way to create a <code>B</code> instance because <code>B</code> is &#8220;unproxyable [<em>sic</em>]&#8221; according to <a href="https://jakarta.ee/specifications/cdi/3.0/jakarta-cdi-spec-3.0.html#unproxyable">the rules laid out by the specification</a>.</p>



<p>Let&#8217;s assume that relaxed construction <em>is</em> enabled.  Weld begins by looking for a <a href="https://github.com/weld/core/blob/be7382b01c4a56c54f92873c1c2ebf0445714bfe/impl/src/main/java/org/jboss/weld/bean/proxy/ProxyInstantiator.java#L45"><code>ProxyInstantiator</code> implementation</a>:</p>



<p><a href="https://github.com/weld/core/blob/be7382b01c4a56c54f92873c1c2ebf0445714bfe/impl/src/main/java/org/jboss/weld/bootstrap/WeldStartup.java#L335">https://github.com/weld/core/blob/be7382b01c4a56c54f92873c1c2ebf0445714bfe/impl/src/main/java/org/jboss/weld/bootstrap/WeldStartup.java#L335</a></p>



<p>That causes the <code>create</code> method to be called on the <code>ProxyInstantiator.Factory</code> class with access to the configuration subsystem:</p>



<p><a href="https://github.com/weld/core/blob/151e1fedcc16d6d2dfec3ecdf1c095f75fdd995d/impl/src/main/java/org/jboss/weld/bean/proxy/ProxyInstantiator.java#L128-L129">https://github.com/weld/core/blob/151e1fedcc16d6d2dfec3ecdf1c095f75fdd995d/impl/src/main/java/org/jboss/weld/bean/proxy/ProxyInstantiator.java#L128-L129</a></p>



<p>The <code>create</code> method begins by assuming that the <code>ProxyInstantiator</code> that will be used is the <code><a href="https://github.com/weld/core/blob/be7382b01c4a56c54f92873c1c2ebf0445714bfe/impl/src/main/java/org/jboss/weld/bean/proxy/DefaultProxyInstantiator.java#L28-L34">DefaultProxyInstantiator</a></code>:</p>



<p><a href="https://github.com/weld/core/blob/151e1fedcc16d6d2dfec3ecdf1c095f75fdd995d/impl/src/main/java/org/jboss/weld/bean/proxy/ProxyInstantiator.java#L90">https://github.com/weld/core/blob/151e1fedcc16d6d2dfec3ecdf1c095f75fdd995d/impl/src/main/java/org/jboss/weld/bean/proxy/ProxyInstantiator.java#L90</a></p>



<p>Then, if relaxed construction is enabled (which it is in this example), Weld will try two other hard-coded implementations in order, using the first &#8220;valid&#8221; one (we&#8217;ll see what that means shortly):</p>



<p><a href="https://github.com/weld/core/blob/151e1fedcc16d6d2dfec3ecdf1c095f75fdd995d/impl/src/main/java/org/jboss/weld/bean/proxy/ProxyInstantiator.java#L91-L103">https://github.com/weld/core/blob/151e1fedcc16d6d2dfec3ecdf1c095f75fdd995d/impl/src/main/java/org/jboss/weld/bean/proxy/ProxyInstantiator.java#L91-L103</a></p>



<p>The first of these implementations is the <code><a href="https://github.com/weld/core/blob/be7382b01c4a56c54f92873c1c2ebf0445714bfe/impl/src/main/java/org/jboss/weld/bean/proxy/UnsafeProxyInstantiator.java#L28-L35">UnsafeProxyInstantiator</a></code>, whose instantiation strategy is to use the <code>sun.misc.Unsafe</code> class (redirected in modern JDKs to the <code>jdk.internal.misc.Unsafe</code> class) to <a href="https://github.com/openjdk/jdk/blob/b961f2535c9508d6f8e580b8bf53538d6f72b27c/src/java.base/share/classes/jdk/internal/misc/Unsafe.java#L1332-L1338">create an instance of a class without using constructors at all</a>:</p>



<p><a href="https://github.com/weld/core/blob/151e1fedcc16d6d2dfec3ecdf1c095f75fdd995d/impl/src/main/java/org/jboss/weld/bean/proxy/UnsafeProxyInstantiator.java#L47-L49">https://github.com/weld/core/blob/151e1fedcc16d6d2dfec3ecdf1c095f75fdd995d/impl/src/main/java/org/jboss/weld/bean/proxy/UnsafeProxyInstantiator.java#L47-L49</a></p>



<p><strong>This is worth noting because you might be logging proxy instantiation inside your zero-argument constructor, but if this strategy is selected for whatever reason, your constructor won&#8217;t be called.</strong>  I&#8217;ve personally been burned by this and have now seen others burned by it as well.</p>



<p>If that <code>UnsafeProxyInstantiator</code> class is not available or can&#8217;t be used for any reason, then a second non-standard <code>ProxyInstantiator</code> implementation is tried instead, which uses <code>sun.reflect.ReflectionFactory</code> under the covers (which in modern JDKs is sort of redirected to <code>jdk.internal.reflect.ReflectionFactory</code>).  This class will happily use a <code>private</code> zero-argument constructor:</p>



<p><a href="https://github.com/weld/core/blob/151e1fedcc16d6d2dfec3ecdf1c095f75fdd995d/impl/src/main/java/org/jboss/weld/bean/proxy/ReflectionFactoryProxyInstantiator.java#L52-L60">https://github.com/weld/core/blob/151e1fedcc16d6d2dfec3ecdf1c095f75fdd995d/impl/src/main/java/org/jboss/weld/bean/proxy/ReflectionFactoryProxyInstantiator.java#L52-L60</a></p>



<p>(In this case of course your <code>private</code> zero-argument constructor will be called so any logging you do in there will show up.)</p>



<p>(You can see how it does this here:)</p>



<figure class="wp-block-embed"><div class="wp-block-embed__wrapper">
<a href="https://github.com/openjdk/jdk/blob/b961f2535c9508d6f8e580b8bf53538d6f72b27c/src/java.base/share/classes/jdk/internal/reflect/ReflectionFactory.java#L435-L457" rel="nofollow">https://github.com/openjdk/jdk/blob/b961f2535c9508d6f8e580b8bf53538d6f72b27c/src/java.base/share/classes/jdk/internal/reflect/ReflectionFactory.java#L435-L457</a>
</div></figure>



<p>Finally, if neither of these non-standard instantiation strategies works, then the already-constructed <code>DefaultProxyInstantiator</code> is used instead, which does what you think it does, and adheres to the standard:</p>



<p><a href="https://github.com/weld/core/blob/be7382b01c4a56c54f92873c1c2ebf0445714bfe/impl/src/main/java/org/jboss/weld/bean/proxy/DefaultProxyInstantiator.java#L42-L44">https://github.com/weld/core/blob/be7382b01c4a56c54f92873c1c2ebf0445714bfe/impl/src/main/java/org/jboss/weld/bean/proxy/DefaultProxyInstantiator.java#L42-L44</a></p>



<p>That is how the proxy object itself is created.  Note that this does not create the actual underlying instance.  For that, a <code>private</code> constructor is just fine (in Weld&#8217;s CDI implementations, anyway).</p>



<p>Note also that the underlying instance is not created until a business method on the proxy is invoked.  Note as well that any method defined by <code>java.lang.Object</code>, other than <code>toString()</code>, is <a href="https://jakarta.ee/specifications/cdi/3.0/jakarta-cdi-spec-3.0.html#client_proxy_invocation">not considered a business method</a>.</p>



<p>Hopefully this helps someone!</p>
]]></content:encoded>
					
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">3557</post-id>
		<media:content url="https://2.gravatar.com/avatar/58e3ea56bec4978a64e8ad60274b75cd8691435be2e44e6e69969986ed9b6399?s=96&#38;d=&#38;r=G" medium="image">
			<media:title type="html">lairdnelson</media:title>
		</media:content>
	</item>
		<item>
		<title>On Portability</title>
		<link>https://lairdnelson.wordpress.com/2021/04/21/on-portability/</link>
		
		<dc:creator><![CDATA[Laird Nelson]]></dc:creator>
		<pubDate>Wed, 21 Apr 2021 17:53:32 +0000</pubDate>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Uncategorized]]></category>
		<guid isPermaLink="false">http://lairdnelson.wordpress.com/?p=3532</guid>

					<description><![CDATA[I’m primarily (as always) talking Java, here. This post has a larger purpose but I’m not there yet. If all goes according to plan this post will make sense with some others to follow. At the moment it probably doesn’t make much sense. If that’s your thing, read on. You may be interested in the &#8230; <a href="https://lairdnelson.wordpress.com/2021/04/21/on-portability/" class="more-link">Continue reading<span class="screen-reader-text"> "On Portability"</span></a>]]></description>
										<content:encoded><![CDATA[
<p>I’m primarily (as always) talking Java, here. This post has a larger purpose but I’m not there yet. If all goes according to plan this post will make sense with some others to follow. At the moment it probably doesn’t make much sense. If that’s your thing, read on.  You may be interested in the <a href="/2021/04/20/on-platforms/">prior post</a> in this series.</p>



<p>What is portability?</p>



<p>&#8220;Portable&#8221; just means <a href="https://www.merriam-webster.com/dictionary/portable">capable of being carried</a>.  If you can pick it up and put it down, it&#8217;s portable.  If you can take it from one &#8220;place&#8221; to another, it&#8217;s portable.  My knapsack is portable.  My piano is not, at least by me alone.  Nor, really, is my crushing sense of self-doubt, but that&#8217;s another story.</p>



<p>Unless you&#8217;re just waving your hands, in computers and software when you&#8217;re talking about portability you have to talk about where the carrying is happening.  Usually the word &#8220;across&#8221; or &#8220;between&#8221; is involved: A program might be portable across operating systems; a framework extension might be portable across different implementations of the framework; and so on.</p>



<p>In computers and software, we also usually add concepts of functionality and immutability to this.  An <em>application</em> or a binary or a script is portable across computers or environments if, when you pick it up from one computer or environment and put it down on or into another computer or environment without changing it, it still works or can work.  A pure Java application is portable across operating systems (or should be) because assuming you have <code>java</code> lying about at the destination you can pick up your <code>CatsLOL.class</code> file from a Windows computer and put it down on a Linux computer and run it in the same way without changing it.  A binary resulting from a compiled and linked C program may not be (and usually is not) portable from one operating system to another.</p>



<p>A software <em>component</em> (like a library or a jar file or an individual Java class that is not a program) is also portable, even if you&#8217;re not switching operating systems or languages.  You can pick a component up and put it (or a copy of it) down in multiple applications and incorporate it that way.  In some sense you have &#8220;carried&#8221; it from wherever it was to several different destinations without changing it.  This can happen even if you leave it in place: dynamic loading of libraries and classes is kind of a form of carrying, if you look at it right; the program doing the dynamic loading imports the library or class, thus notionally carrying it from one place to its own address space.  &#8220;Reusability&#8221; is another (awful) word for this, along with other real winners like &#8220;composability&#8221;.</p>



<p>There are other sorts of more abstract things (let&#8217;s restrict ourselves to the software industry) that can be carried from one &#8220;place&#8221; to another and used without modification.  If I leave one employer and go to another, I take my brain (hopefully) and experience with me, or at least the parts that are not signed away to the former employer somewhere.  Publicly available stuff I learned from books, videos, websites, reference manuals and even certain source code may be portable from one work environment to another and I may be able to get up to speed more quickly as a result.</p>



<p>Things can be more or less portable.  Sometimes something is 100% portable provided that the new environment it is being carried to is juuuuuuust right.  If it is, then you put the thing down, it plugs into the new environment and runs exactly the same way as it did in the old environment.  A pure Java program is a good example of this.  A Java program that relies on a native library, by contrast, may find in the new environment that the environment-specific native library it needs for that environment is missing.  If that library is put in the right place, then everything works.  Another Java-centric example is: a Java framework extension or participant may be more or less portable depending on which features of the framework it uses or extends and how likely those features are to exist across the environments the Java framework extension or participant might be ported to.  Then, even more abstractly, my knowledge of the JAX-RS API is fully portable from one job to another to the extent that the new job mandates proper use of the JAX-RS API.  My knowledge of C++, on the other hand, probably isn&#8217;t very portable from one job to another because C++ permits lots of flavors and styles and maybe the old job and new job feature completely different styles of C++ programming.  Also I&#8217;m joking about my knowledge of C++.  So is everyone else.</p>



<p>To talk about software portability, particularly application portability, you often have to talk about <a href="/2021/04/20/on-platforms/">platforms</a> and platform implementations, because often what you&#8217;re <em>really</em> saying is that a given application is portable across a given <em>platform&#8217;s</em> multiple implementations.  So then: an application is fully portable across platform implementations to the extent that there is more than one implementation of that platform and it doesn&#8217;t matter which platform implementation you pick to run it.  Pick it up from one platform implementation; put it down in another: did it run?  It&#8217;s portable! Congratulations! I probably didn&#8217;t write it.</p>



<p>So is a <a href="https://jakarta.ee/">Jakarta EE</a> application fully portable?  It can be.  If your application follows the platform specification, then you know it will (at least theoretically) run on platform implementations A and B in exactly the same way.  If it uses features from one platform implementation, then you cannot necessarily pick it up from platform implementation A and run it unchanged in platform B, because platform B might not have those features.</p>



<p>Is a <a href="https://jakarta.ee/specifications/cdi/3.0/jakarta-cdi-spec-3.0.html#part_2">CDI SE</a> application fully portable?  This is sort of a nonsensical question, because <a href="/2021/04/20/on-platforms/#cdise">CDI SE is not really a platform, but a framework</a>.  Regarding application portability, therefore, the answer is no.  Now, certainly a CDI SE <em>component</em> (an extension, a bean, etc.) can be portable between CDI SE implementations and can be reused in various CDI SE applications: it can be picked up and carried from one CDI SE program and repackaged into another CDI SE program.  If it uses Weld APIs, though, for example, then it is not fully portable across CDI SE implementations (like OpenWebBeans).</p>



<p>Is a <a href="https://spring.io/">Spring</a> application fully portable?  Yes and no.  A Spring application packaged as a fat jar is just a Java program, so yes, you can port it from one Java environment to another, but given Java&#8217;s program portability promises this is almost tautological.  Or, if you like: there aren&#8217;t two implementations of the Spring platform.  From that perspective, therefore, a Spring application isn&#8217;t portable because there&#8217;s nothing to port it to.  A Spring program packaged as a .war file, on the other hand, could conceivably be fully portable across Jakarta EE platform implementations provided that it carries all of its baggage with it (i.e. a Jakarta EE server will almost certainly not have any Spring libraries preinstalled).  At this point, though, it just collapses into being a Jakarta EE application, so see above.</p>



<p>Is a <a href="https://www.dropwizard.io/en/latest/">DropWizard</a> application portable?  No.  There&#8217;s nothing to port it to.  There aren&#8217;t two implementations of a hypothetical DropWizard platform.</p>



<p>Is a Java application portable?  Well, yes, but trivially so, and at a different sort of level.  You can indeed run a Java program on different operating systems, and Java is a platform, so therefore a Java program is portable across operating systems.  But given that we&#8217;re talking about portability across platforms, this foundational level of portability isn&#8217;t very interesting for this article.</p>



<p>Is a <a href="https://microprofile.io/">MicroProfile</a> application portable?  No, because <a href="/2021/04/20/on-platforms/#microprofile">there is no such thing as a MicroProfile platform</a>, so there&#8217;s nothing to port it to.  There are things that use MicroProfile APIs and even implement them but there&#8217;s no standard way to make some kind of hypothetical MicroProfile application and somehow run it in all of them.</p>



<p>Is an arbitrary binary portable?  No; we&#8217;ve already covered that above. </p>



<p>If I make a binary using <a href="https://www.graalvm.org/reference-manual/native-image/">GraalVM&#8217;s native image facility</a>, is the resulting binary portable?  No, for the same reasons.</p>



<p>Is a <a href="https://quarkus.io/">Quarkus</a> application portable?  No; it&#8217;s just a binary.  There&#8217;s nothing to port it to.</p>



<p>Is a <a href="https://helidon.io/">Helidon</a> SE application portable?  No; it&#8217;s just a Java program that uses some libraries.  There&#8217;s nothing to port it to.</p>



<p>Is a <a href="https://helidon.io/docs/v2/#/mp/introduction/01_introduction">Helidon MP</a> application portable?  No; it too is just a Java program that uses some libraries, some of which happen to be partially specified.  There&#8217;s nothing to port it to.</p>



<p>Is an <a href="https://openliberty.io/">OpenLiberty</a> application portable?  To the extent that it is a Jakarta EE application, yes; to the extent that it is not, no.</p>



<p>Is a <a href="https://www.payara.fish/">Payara</a> application portable?  Same answer: to the extent that it is a Jakarta EE application, yes; to the extent that it is not, no.</p>



<p>Is an <a href="https://www.oracle.com/middleware/technologies/weblogic.html">Oracle WebLogic Server</a> application portable?  Same answer.</p>



<p>OK, there are a lot of &#8220;no&#8221;s above.  That&#8217;s not to say component and knowledge portability isn&#8217;t in play across the board.  Some arbitrary examples:</p>



<ul class="wp-block-list"><li>A CDI component can be portable between CDI SE-, Helidon MP-, MicroProfile- and Jakarta EE-based applications</li><li>A Spring component can be portable between Spring applications</li><li>A JAX-RS resource class can be portable between DropWizard, Helidon MP, MicroProfile- and Jakarta EE-based applications</li><li>A component that uses <code>org.eclipse.microprofile.config.Config</code> is portable to any library or application that has MicroProfile Config available to it</li></ul>



<p>…and so on.</p>



<p>More to come that may tie back to this article.</p>
]]></content:encoded>
					
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">3532</post-id>
		<media:content url="https://2.gravatar.com/avatar/58e3ea56bec4978a64e8ad60274b75cd8691435be2e44e6e69969986ed9b6399?s=96&#38;d=&#38;r=G" medium="image">
			<media:title type="html">lairdnelson</media:title>
		</media:content>
	</item>
		<item>
		<title>On Platforms</title>
		<link>https://lairdnelson.wordpress.com/2021/04/20/on-platforms/</link>
		
		<dc:creator><![CDATA[Laird Nelson]]></dc:creator>
		<pubDate>Wed, 21 Apr 2021 03:34:07 +0000</pubDate>
				<category><![CDATA[Java]]></category>
		<guid isPermaLink="false">http://lairdnelson.wordpress.com/?p=3517</guid>

					<description><![CDATA[I&#8217;m primarily (as always) talking Java, here. This post has a larger purpose but I&#8217;m not there yet. If all goes according to plan this post will make sense with some others to follow. At the moment it probably doesn&#8217;t make much sense. If that&#8217;s your thing, read on. You may also be interested in &#8230; <a href="https://lairdnelson.wordpress.com/2021/04/20/on-platforms/" class="more-link">Continue reading<span class="screen-reader-text"> "On Platforms"</span></a>]]></description>
										<content:encoded><![CDATA[
<p>I&#8217;m primarily (as always) talking Java, here.  This post has a larger purpose but I&#8217;m not there yet.  If all goes according to plan this post will make sense with some others to follow.  At the moment it probably doesn&#8217;t make much sense.  If that&#8217;s your thing, read on.  You may also be interested in the <a href="/2021/04/21/on-portability/">next post</a> in this series.</p>



<p>What is a platform?</p>



<p>If I have one library with one class in it, with one function, do I have a platform?  What about two functions?  Two classes?  Two libraries?</p>



<p>In my opinion, it depends on what it does.</p>



<p>Maybe I&#8217;m naïve, but I think a platform has to have a definition of what a packaged application looks like, a way to create such a packaged application (or at least verbiage about how to do it), and a way to run a packaged application that is handed to it.  It may or may not also include a framework or libraries that the application may or must use.</p>



<p>You write and package an application to run <em>on</em> a platform, optionally (or not) using the platform&#8217;s facilities, and the application and the platform are distinct entities and have notionally different lifespans (that may of course nevertheless line up).</p>



<p><em>How</em> the packaged application is expected to look and <em>how</em> it runs is dictated by the platform.  Also, in most cases, but I suppose not all, a platform dictates how the application must <em>look</em> but not how it is <em>produced</em>.</p>



<p>So Docker, for example, is a platform, because, among other things, it tells you <a href="https://github.com/moby/moby/blob/master/image/spec/v1.2.md#docker-image-specification-v120">what a packaged application is</a>, one way among several to package your application (<code>docker build</code>) and how to run it (<code>docker run</code>).  Docker itself doesn&#8217;t really include any kind of  framework that your application would use: your application is responsible, wholly, for doing whatever it wants to do.  Here you can start to argue semantics about things like volume mounts and whatnot if you so choose, and if you do that I will start checking my phone and waiting for you to leave.</p>



<p>Is Kubernetes a platform?  Unquestionably, it seems to me, by the same logic.  (Also, anything with that many metric tons of YAML is probably a platform by fiat, or at least a ZIP code.)</p>



<p><a href="https://jakarta.ee/">Jakarta EE</a> (and <a href="https://javaee.github.io/">Java EE</a> before it) is a platform because it tells you how to package your application (<code>mvn {war plugin incantations}</code>) such that a very specific ZIP file with a very specific filename suffix is created, or at least what an application so packaged must look like, and how to run (deploy) it.  Well, hmm; no, <em>it</em> doesn&#8217;t <em>really</em> tell you how to run such an application, although it does say that any compliant Jakarta EE <em>implementation</em> must allow the user to <em>perform a deploy operation</em> on a standard packaged application.  So more accurately: <em>any given Jakarta EE implementation</em> is a platform: you hand it a standard application, and its tooling can run that application.</p>



<p id="cdise">Is <a href="https://jakarta.ee/specifications/cdi/3.0/jakarta-cdi-spec-3.0.html#part_2">CDI SE</a> a platform?  No.  It is a framework.  A framework is a library that, should <em>it</em> be poked through some other means, will arrange for your framework extension or participant to be called back (and hence started or poked, whatever that might mean, as well).  CDI SE will look for certain classpath resources, but that&#8217;s not really packaging, exactly, and you can turn it off anyway, so ultimately <em>you</em> are the one doing the starting or poking of the framework and telling it what, in turn, to start or poke itself.  Once <em>you</em> take care of that one way or another, your CDI SE framework extension or participant (your application) will do whatever the framework says it should do.  So: framework yes, platform no.</p>



<p>Is <a href="https://spring.io/">Spring</a> a platform?  Yes and no.  It is probably fundamentally a framework by the same logic, plus a collection of useful libraries you can use outside of the framework, plus some other stuff, plus a grand piano, some lead shot, the kitchen sink, a bank safe, and the fluff found in your front pockets.  It also however does define a packaging format: if you build your Spring application a certain way, an executable archive pops out the other end that can be run by the Java platform (which also relies on a very complicated custom classloader embedded into the tail end of the ZIP-formatted archive by Spring!) or by a suitable Jakarta EE web container.  So in that sense that part of Spring is a platform.  On the other hand it leans on Java itself to do the heavy lifting if you execute one of its fat (and I do mean fat!) jars, so the recognizing that there is a <code>Main-Class</code> that has to be executed is done by Java itself, not by Spring.</p>



<p>Is <a href="https://www.dropwizard.io/en/latest/">DropWizard</a> a platform?  No, not really.  DropWizard, like Spring, is a collection of libraries it defines and, unlike Spring, those from other places.  It recommends, but does not define, various packaging formats.  It wants you to run your program as a plain old Java program.  Notably, DropWizard, while strictly speaking is probably a framework, delegates to other frameworks (like Jetty) to do the heavy lifting.  Bottom line: not a platform, but a collection of useful libraries and frameworks.</p>



<p>Is Java a platform?  Yes.  It defines how you package your application and how such packaged applications are run.  Using the same command line tool (<code>java</code>) you can run several different applications (executable jar files, exploded class directories, JPMS modules) depending on what you supply to the tool.  (Also Java is obviously a collection of useful libraries!)</p>



<p>So is Java running a program that is a Jakarta EE implementation that deploys a Jakarta EE application two platforms?  Yes, but in that picture presumably only the Jakarta EE implementation would be the platform of interest.</p>



<p id="microprofile">Is <a href="https://microprofile.io/">MicroProfile</a> a platform?  No.  It is a framework as currently constituted, kind of.  Actually, it&#8217;s not even <em>really</em> that, since there&#8217;s no entry point to a MicroProfile application, so no real defined way to poke it or start it.  Like DropWizard, it relies (exclusively) on other frameworks (like JAX-RS) to do the heavy lifting, which do define such entry points.  Nor is there a notion of a MicroProfile application that you start in any way.  Nor is there a notion of deployment.  Nor is there any common way to package a MicroProfile application even if there were a notion of what one is.  Instead, I suppose it is a collection of useful libraries, and in some cases only parts of useful libraries, where the other parts are off-limits in some currently unspecified way.  To use the language of Jakarta EE, it is, as currently constituted, &#8220;<a href="https://jakarta.ee/specifications/platform/9/jakarta-platform-spec-9.html#profiles">little more than bundles of APIs with few or no tie-ins</a>&#8221; to a (nonexistent) larger platform.  Maybe this will change.</p>



<p>If I have some arbitrary executable binary in my hand and I ask my computer to run it, is there a platform involved?  Of course at some level there is, but I personally stop here, so therefore, dear reader, you will too: yes, a Unix system is a platform that runs, say, <a href="https://en.wikipedia.org/wiki/Executable_and_Linkable_Format">ELF</a> executables, but in that parlance I guess I would be interested only in ELF executables that run other packaged applications.  So, for this discussion, no, if I have an arbitrary executable (such as a compiled and linked C program) that just runs and does its thing, it is not a platform.</p>



<p>If I make a binary using <a href="https://www.graalvm.org/reference-manual/native-image/">GraalVM&#8217;s native image facility</a>, is the resulting binary a platform?  No (unless I&#8217;ve deliberately created a binary to run well-defined packaged applications of some kind, of course).  See the logic above.</p>



<p>So is <a href="https://quarkus.io/">Quarkus</a> a platform?  No, because it just results in single purpose binaries.  Quarkus is, really, a kind of compiler, I guess.</p>



<p>Is <a href="https://helidon.io/">Helidon</a> SE a platform?  No; it&#8217;s a <a href="https://helidon.io/docs/v2/#/about/01_overview">collection of libraries</a>.</p>



<p>Is <a href="https://helidon.io/docs/v2/#/mp/introduction/01_introduction">Helidon MP</a> a platform?  No; it&#8217;s a MicroProfile implementation and you&#8217;ll see above that MicroProfile isn&#8217;t a platform.</p>



<p>Is <a href="https://openliberty.io/">OpenLiberty</a> a platform?  Weirdly, although they define a runtime that can run well-defined packaged applications, they define <em>themselves</em> as a framework.  I disagree; they are a platform: you deploy a well-defined packaged application to a simple server.  Platform all the way.</p>



<p>Is <a href="https://www.payara.fish/">Payara</a> a platform?  Yes.  Depending on the product in question, it is either a Jakarta EE implementation of some kind (and hence a platform; see above) or defines a way of running applications (it is a MicroProfile implementation, and although as noted above MicroProfile is not a platform a runtime that defines a packaging format that happens to use MicroProfile&#8217;s useful collection of libraries is thus itself a platform).</p>



<p>Is <a href="https://www.oracle.com/middleware/technologies/weblogic.html">Oracle WebLogic Server</a> a platform?  Yes; among many other things it is a Jakarta EE implementation.</p>



<p>More to come that may tie back to this article.</p>
]]></content:encoded>
					
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">3517</post-id>
		<media:content url="https://2.gravatar.com/avatar/58e3ea56bec4978a64e8ad60274b75cd8691435be2e44e6e69969986ed9b6399?s=96&#38;d=&#38;r=G" medium="image">
			<media:title type="html">lairdnelson</media:title>
		</media:content>
	</item>
		<item>
		<title>CreationalContext Observations</title>
		<link>https://lairdnelson.wordpress.com/2020/12/31/creationalcontext-observations/</link>
		
		<dc:creator><![CDATA[Laird Nelson]]></dc:creator>
		<pubDate>Thu, 31 Dec 2020 21:24:19 +0000</pubDate>
				<category><![CDATA[CDI]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Uncategorized]]></category>
		<guid isPermaLink="false">http://lairdnelson.wordpress.com/?p=3451</guid>

					<description><![CDATA[Here are some random observations concerning CreationalContext, a funky little architecturally polluting blemish on the surface of CDI&#8217;s otherwise pretty good set of APIs. (I&#8217;ve written before on this little nugget.) There is no documentation that says what a CreationalContext is. The class javadoc reads, in total: Provides operations that are used by the&#160;Contextual&#160;implementation during &#8230; <a href="https://lairdnelson.wordpress.com/2020/12/31/creationalcontext-observations/" class="more-link">Continue reading<span class="screen-reader-text"> "CreationalContext Observations"</span></a>]]></description>
										<content:encoded><![CDATA[
<p>Here are some random observations concerning <code><a href="https://jakarta.ee/specifications/cdi/3.0/apidocs/jakarta/enterprise/context/spi/creationalcontext">CreationalContext</a></code>, a funky little architecturally polluting blemish on the surface of CDI&#8217;s otherwise pretty good set of APIs.  (I&#8217;ve written before on this little nugget.)</p>



<p>There is no documentation that says what a <code>CreationalContext</code> is.  The class javadoc reads, in total:</p>



<blockquote class="wp-block-quote is-layout-flow wp-block-quote-is-layout-flow"><p>Provides operations that are used by the&nbsp;<a href="https://jakarta.ee/specifications/cdi/3.0/apidocs/jakarta/enterprise/context/spi/Contextual.html"><code>Contextual</code></a>&nbsp;implementation during instance creation and destruction.</p></blockquote>



<p>So its purpose is exactly that of its two operations, one of which (<code>push()</code>) can be properly implemented as a no-op as we&#8217;ll see below.  That means its purpose is solely to house the <code>release()</code> method.</p>



<p>To portably create a <code>CreationalContext</code>, you use <code>BeanManager#createCreationalContext(Contextual)</code>.  For the purposes of destroying dependent objects, which is the interface&#8217;s sole documented purpose, the supplied <code>Contextual</code> is never used.</p>



<p>A <code>CreationalContext</code> is architecturally tightly coupled to a <code>Context</code> implementation for the <code>Dependent</code> scope.  If you implement one, you have to implement the other because there is no portable way for an arbitrary <code>Context</code> implementing the <code>Dependent</code> scope to indicate to a <code>CreationalContext</code> that a dependent object needs to be tracked for subsequent destruction by the <code>release()</code> method.  But in Weld you <em>cannot</em> supply your own instance of a <code>Context</code> for the <code>Dependent</code> scope, because the Weld-supplied one is always active, and there can be at most one active <code>Context</code> for a scope, and there is no way to remove a <code>Context</code>.  So therefore you cannot supply your own implementation of <code>CreationalContext</code> in Weld unless you couple it to Weld interfaces and abstract classes…in which case why are you supplying one in the first place?</p>



<p>Weld implements <code>CreationalContext</code> by constructing a tree of them: each one tracks dependent objects added by its child.  This means that Weld&#8217;s <code>CreationalContext</code> implementation is also tightly coupled to Weld&#8217;s implementation of <code>BeanManager</code>: <a href="https://github.com/weld/core/blob/6ac53159efe0b09f63e21ce7a07d0d0e1dd4828b/impl/src/main/java/org/jboss/weld/manager/BeanManagerImpl.java#L679-L682">every time a contextual reference is acquired, whether via injection or programmatically, a new &#8220;child&#8221; <code>CreationalContext</code> is created</a>.  This tree structure is not necessarily needed to perform dependent object cleanup (since, for example, OpenWebBeans implements <code>CreationalContext</code> without such a tree structure).  The result is that in Weld many <code>CreationalContextImpl</code> objects get created that do nothing.</p>



<p><code>push()</code> and <code>release()</code> have nothing to do with each other.  In fact you can pass the TCK by <a href="https://github.com/apache/openwebbeans/blob/d787fc5521ca519dea8251026ee163621d59c921/webbeans-impl/src/main/java/org/apache/webbeans/context/creational/CreationalContextImpl.java#L172-L181">implementing <code>push()</code> as a no-op</a>.  Many developers you talk to think that these methods are related.  Almost nobody knows how to use them properly.  You are, it turns out, supposed to always (probably within a <code>finally</code> block) call <code>release()</code> as the last thing you do in a custom bean&#8217;s <code>destroy()</code> method.  Otherwise it is possible that your program will leak memory.</p>



<p><code>release()</code> means, simply, &#8220;destroy dependent objects tracked by this <code>CreationalContext</code>&#8220;.  Of course it may not be exactly <em>this</em> <code>CreationalContext</code>, because it might be a tree of such <code>CreationalContext</code>s.  Or maybe it&#8217;s &#8220;destroy all dependent objects reachable from the creation of whatever it was that caused this <code>CreationalContext</code> to come into existence&#8221;.  No specification language indicates whether <code>release()</code> must be idempotent.  Obviously it would sure be nice if it were, so CDI implementations tend to make it so.</p>



<p>Remember that <a href="https://jakarta.ee/specifications/cdi/3.0/jakarta-cdi-spec-3.0.html#dependent_destruction">according to the specification a CDI implementation can destroy an unreferenced dependent object at any point by any means for any reason</a>, so strictly speaking <code>release()</code> isn&#8217;t really a method that should have ended up in the specification (it&#8217;s an implementation detail).  It&#8217;s clearly convenient so maybe that&#8217;s why it ended up in here.</p>



<p>The only time you need a <code>CreationalContext</code> is when you know that a contextual instance is going to be created.  If you know that a contextual instance already exists, then the <code>CreationalContext</code> will never be used by the <code>Context#get(Contextual, CreationalContext)</code> method.</p>



<p>I often wonder why instead of this strange API there wasn&#8217;t a <code>DependentContext</code> interface, extending <code>Context</code>, that would allow you to add and destroy dependent object hierarchies, since <a href="https://jakarta.ee/specifications/cdi/3.0/jakarta-cdi-spec-3.0.html#dependent_context">we already know that <code>Dependent</code> is a special scope</a>.  There&#8217;s probably a good reason but I can&#8217;t think of what it is at the moment.</p>



<p></p>
]]></content:encoded>
					
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">3451</post-id>
		<media:content url="https://2.gravatar.com/avatar/58e3ea56bec4978a64e8ad60274b75cd8691435be2e44e6e69969986ed9b6399?s=96&#38;d=&#38;r=G" medium="image">
			<media:title type="html">lairdnelson</media:title>
		</media:content>
	</item>
	</channel>
</rss>
