Conditionally configure instance in StructureMap - inversion-of-control

Preemptive rtfm disclaimer: StructureMap's documentation is a major version out of date, and the API it documents doesn't even exist anymore, not to say anything for the attributes marked obsolete.
I have an environment setting, that for all intents and purposes can be treated as a static application-scoped boolean. The result of this boolean needs to control which implementation of my interface is plugged in. The sample documentation for conditionals is perfect for what I'm looking for, but none of those methods exist in 3.1.1.134 (latest in NuGet as of 9/8/2014).
I am looking for the current version of the following pseudo-syntax, and do not let "GetEnvironmentVariable" be a red herring -- it is just an example of a runtime system-wide boolean that needs to be evaluated on graph building.
public ConditionalInjectionRegistry : Registry
{
For<IBehavior>().UseConditionally(u =>
{
u.Conditionally(() => Environment.GetEnvironmentVariable("foo") == "bar")).Is<FooedBehavior>();
u.Default.Is<NormalBehavior>();
});
}

According to the mailing list, the correct way to do this now is with a lambda inside Use().
For<IIndexResolver>().Use("some description for diagnostics", c => {
// and just do it all with a single anonymous lambda
});

Related

Create a Scala DSL where state is available within a block without being declared as a parameter?

I have some vanilla Scala code that looks like this:
addCooker(new Cooker(getOvenState(), cookingTime, CookieNames.GingerSnaps) {
override def cook(customer: Customer, priority: Priority): Boolean = {
// Use `customer` and `priority` to cook a cookie and return true if successful.
???
}
})
I.e. I create a callback-like Cooker object that's passed to an addCooker method. CookieCutter takes some values (cookingTime etc.) that are available when calling addCooker (these are passed to its ctor) and it takes some values (customer etc.) that will only be available at some later point in time (these will be passed as arguments to its cook method).
I'd like to create a DSL where I can write this as:
addCooker(getOvenState(), cookingTime, CookieNames.GingerSnaps) {
// Somehow make a `customer` and `priority` value (that are not available at
// the time `addCooker` happens) visible to the code within this block.
}
I could declare addCooker as a method like so:
def addCooker(overState: OvenState, cookingTime: Duration, name: CookieName)(
block: () => Boolean
): Unit = ???
But I don't see a way to make cookingTime etc. available such that they can be used within the lambda passed as block.
The best I can do results in something like this:
addCooker(getOvenState(), cookingTime, CookieNames.GingerSnaps) { (customer, priority) =>
true
}
Normally, this would be good enough for me but in this situation, hundreds of such blocks will be written (and there'll be lots of different but similar constructs) and a DSL where many of the values are just there rather than one needing to always declare them as parameters would be ideal.
I guess one way is to make customer etc. protected var variables of the class where the addCooker calls are being made, i.e. they'd be visible not just to my { ... } block but also to the logic that calls addCooker (but without yet being set to anything meaningful).
PS are there any good guides to the kinds of non-obvious tricks that you need to use to create DSLs? I found lots of guides that didn't go very deep (focusing on little more than using implicits to do type conversions or do fun things with operators). The only substantial thing I found was DSLs in Action but it was written in 2010 and uses Scala 2.8 - I imagine the thinking on many things related to implicits and the like has changed noticeably since then.
If the above snippets are unclear, you can them (with supporting stubs such that things will compile) here:
https://gist.github.com/george-hawkins/a9db64f05e14ea7d191bc4cf85dd64f6

Puppet - Duplicate declaration for Registry_key

I have a manifest file to add registry keys and values based on facts (works fine).
registry_key { 'HKLM\SOFTWARE\Policies\Microsoft\Windows\WindowsUpdate':
ensure => present,
}
registry_value { 'HKLM\SOFTWARE\Policies\Microsoft\Windows\WindowsUpdate\TestKey':
ensure => present,
type => dword,
data => $test_key_value,
}
I want to add a second file to remove these if required but when i do i get an error
"Duplicate declaration: Registry_key[HKLM\SOFTWARE\Policies\Microsoft\Windows\WindowsUpdate] is already declared"
Not sure how to get around this - if at all? Any advice appreciated. Obviously a puppet novice...
Thanks
If you want to solve this problem, you would probably use custom or external facts, something like this:
$ensure = $facts['include_windows_update_keys']
registry_key { 'HKLM\SOFTWARE\Policies\Microsoft\Windows\WindowsUpdate':
ensure => $ensure,
}
registry_value { 'HKLM\SOFTWARE\Policies\Microsoft\Windows\WindowsUpdate\TestKey':
ensure => $ensure,
type => dword,
data => $test_key_value,
}
As you have discovered, declaring the same resource more than once but with different attributes is not allowed in Puppet.
There is more on custom facts here in the docs.
In most situations Alex's suggestion is the way I'd proceed. Usually the best way, to default it in common.yaml and override based on node name or another level in hiera. Depending on your use case, a less straight-forward way is to wrap those blocks in a conditional (if/unless/else) where it's present/absent depending on a boolean set in hiera. Something along the lines of unless $exclude_from_testkey or a case statement. Let me know if you're new to hiera and/or parameterization.
You have resource declarations for specifying that a particular registry key and value should be ensured present on the target node. If you also have declarations specifying that one or both should be absent, and Puppet evaluates both sets, then what are you actually telling Puppet to do? It cannot comply with both sets of declarations.
Puppet takes an extremely cautious approach to situations like this, which makes sense given its role in managing infrastructure. In the event that the same resource is declared more than once for the same target, Puppet aborts. This produces practical difficulties from time to time, but I am confident that it has protected many, many systems from misconfiguration.
The solution is to ensure that your manifest set declares only one set of those declarations for each node. You could do that by having only one set, and twiddling their $ensure parameters dynamically, as #AlexHarvey suggests. You could also do it by putting the two sets of declarations in different blocks, and selecting between them with conditional statements. Or you could put them in altogether different classes, and be certain to include just one of them for each node.
But I have to differ with Alex here on the specifics. I would not typically use a custom fact here, because that gives control over which option is exercised to the client. Generally speaking, I want the master to dictate questions of how various nodes are configured. For this purpose, it is a pretty common idiom to use a class parameter to control whether the resources are ensured present or absent:
class mymodule::windows_update(
Enum['absent','present'] $ensure = $present,
$test_key_value
) {
registry_key { 'HKLM\SOFTWARE\Policies\Microsoft\Windows\WindowsUpdate':
ensure => $ensure,
}
registry_value { 'HKLM\SOFTWARE\Policies\Microsoft\Windows\WindowsUpdate\TestKey':
ensure => $ensure,
type => dword,
data => $test_key_value,
}
}

The best way to make Loopback GET query parameters safe?

I'm using Loopback 3.x with loopback-connector-mongodb 3.x
Apparently, many built-in endpoints can take a filter parameter which can be defined as JSON and it may contain complex filter conditions like order, where, skip etc.. For example:
GET /api/activities/findOne?filter={"where":{"id":1234}}
However, although Loopback uses an ORM, it seems the request parameters are passed to mongodb without any kind of pre-processing or escaping.
I was unable to find any Loopback API method which could help me make the value safe.
If, for example, the user puts Javascript into the where filter, or adds unsupported characters (such as null char), the app throws an exception an exits.
I'm sure I'm missing something here. What's the best way to make the value passed in filter={...} safe?
Is there a built-in API method for this?
If there isn't, are there any node module I could use?
Thanks for the help guys!
I turned off Javascript in MongoDB and wrote a little middleware to handle escaping. This is registered in middleware.json and thus it runs before every request and escapes the values.
module.exports = function createEscaper(options) {
return function queryEscape(req, res, next) {
if (req.query.filter) {
// escape various things and update the value..
}
next();
};
}
But I find it really strange that neither the MongoDB connector nor Loopback itself provides any solution for this. I mean, these parameters are defined and handled in framework code. It's kinda crazy there is no built-in escaping whatsoever.
You can create a mixin which validates the JSON you receive.
For example:
module.exports = function(Model, options) {
Model.beforeRemote('find', (ctx, instance, next) => {
// Validate the filter object
}
}

What are configurations in Gradle?

When working with dependency resolution in gradle, you usually see something like this:
configurations {
optional
compile
runtime.extendsFrom compile
testCompile.extendsFrom runtime
}
and I wanted to know of what type is optional or compile? Is it a Class? a string? what methods can I call for it?
Besides all this, is there a way to find out these things automatically, similar to ctrl+space when on something in eclipse?
They are classes that implements org.gradle.api.artifacts.Configuration. The Gradle DSL doc also contains more information about the configuration DSL core type.
To find out more info about internal classes etc, which is useful when for instance looking up classes and methods in the Gradle javadoc, it is often as simple as just printing out the class names. Quite often though, you will end up with some internal implementing class instead of the API interface you're interested in, but regardless of that it's a way get started on what to search for. I tend to keep the source code of all open source projects we're using available in the IDE. That way it's easy to jump into the correct class (even when it's not available through context shortcuts) and look around.
To get more information about configurations in your case, you could add a task that simply prints out the relevant info. E.g. something like:
task configInfo << {
println "configurations.class: ${configurations.class}"
println "configurations.compile class: ${configurations.compile.class}"
println "implements ${Configuration} interface? ${configurations.compile instanceof Configuration}"
}
which in my case results in the following output
$ gradle configInfo
:configInfo
configurations.class: class org.gradle.api.internal.artifacts.configurations.DefaultConfigurationContainer_Decorated
configurations.compile class: class org.gradle.api.internal.artifacts.configurations.DefaultConfiguration_Decorated
implements interface org.gradle.api.artifacts.Configuration interface? true
I am no Gradle expert, but this seems like a simple getter delegated to another object in a DSL fashion. You could write the same with something like this:
class MyDsl {
def config = [:].withDefault { false }
void configure(closure) {
closure.delegate = this
closure()
}
def getOptional() { config.optional = true }
def getCompile() { config.compile = true }
def getTest() { config.test = true }
}
dsl = new MyDsl()
dsl.configure {
optional
compile
}
dsl.config.with {
assert optional
assert compile
assert !test
}
You could return some specific object to pass to runtime.extendsFrom() method.
For auto-complete, IIRC that's what groovy-eclipse DSLD (DSL descriptors) are for. You may want to give a try to this gradle DSLD which is in eclipse-integration-gradle plugin.
As per this ticket it has been done long ago.
The question "what type is optional or compile" isn't really valid. That is kind of like asking what type does "instanceof" have. The instanceof keywword doesn't have a type.
When writing code like you cited, you are taking advantage of a DSL. Treat words like compile and optional as keywords in that DSL. Unless you are writing your own DSL (as opposed to taking advantage of existing one, which is what this question is about), don't think of types being associated with those things.
As for the question about ctrl+space, Eclipse won't do anything special with that in this context unless you are using a plugin which provides support for that. Even with plugin support there will still be limitations because you can define your own configurations. If you were going to define a configuration named "jeffrey" and you typed "jeff" followed by ctrl+space, there is no way for the IDE to know you want it to turn that into "jeffrey".
I hope that helps.

In Scala is there any way to get a parameter's method name and class?

At my work we use a typical heavy enterprise stack of Hibernate, Spring, and JSF to handle our application, but after learning Scala I've wanted to try to replicate much of our functionality within a more minimal Scala stack (Squeryl, Scalatra, Scalate) to see if I can decrease code and improve performance (an Achilles heal for us right now).
Often my way of doing things is influenced by our previous stack, so I'm open to advice on a way of doing things that are closer to Scala paradigms. However, I've chosen some of what I do based on previous paradigms we have in the Java code base so that other team members will hopefully be more receptive to the work I'm doing. But here is my question:
We have a domain class like so:
class Person(var firstName: String, var lastName: String)
Within a jade template I make a call like:
.section
- view(fields)
The backing class has a list of fields like so:
class PersonBean(val person: Person) {
val fields: Fields = Fields(person,
List(
Text(person.firstName),
Text(person.lastName)
))
}
Fields has a base object (person) and a list of Field objects. Its template prints all its fields templates. Text extends Field and its Jade template is supposed to print:
<label for="person:firstName">#{label}</label>: <input type="text" id="person:firstName" value="#{value}" />
Now the #{value} is simply a call to person.firstName. However, to find out the label I reference a ResourceBundle and need to produce a string key. I was thinking of using a naming convention like:
person.firstName.field=First Name
So the problem then becomes, how can I within the Text class (or parent Field class) discover what the parameter being passed in is? Is there a way I can pass in person.firstName and find that it is calling firstName on class Person? And finally, am I going about this completely wrong?
If you want to take a walk on the wild side, there's a (hidden) API in Scala that allows you to grab the syntax tree for a thunk of code - at runtime.
This incantation goes something like:
scala.reflect.Code.lift(f).tree
This should contain all the information you need, and then some, but you'll have your work cut out interpreting the output.
You can also read a bit more on the subject here: Can I get AST from live scala code?
Be warned though... It's rightly classified as experimental, do this at your own risk!
You can never do this anywhere from within Java, so I'm not wholly clear as to how you are just following the idiom you are used to. The obvious reason that this is not possible is that Java is pass-by-value. So in:
public void foo(String s) { ... }
There is no sense that the parameter s is anything other than what it is. It is not person.firstName just because you called foo like:
foo(person.firstName);
Because person.firstName and s are completely separate references!
What you could do is replacing the fields (e.g. firstname) with actual objects, which have a name attribute.
I did something similiar in a recent blog post:http://blog.schauderhaft.de/2011/05/01/binding-scala-objects-to-swing-components/
The property doesn't have a name property (yet), but it is a full object but is still just as easy to use as a field.
I would not be very surprised if the following is complete nonsense:
Make the parameter type of type A that gets passed in not A but Context[A]
create an implicit that turns any A into a Context[A] and while doing so captures the value of the parameter in a call-by-name parameter
then use reflection to inspect the call-by-name parameter that gets passed in
For this to work, you'd need very specific knowledge of how stuff gets turned into call-by-name functions; and how to extract the information you want (if it's present at all).