You are viewing a plain text version of this content. The canonical link for it is here.
Posted to dev@brooklyn.apache.org by rdowner <gi...@git.apache.org> on 2015/06/24 12:13:28 UTC

[GitHub] incubator-brooklyn pull request: Clarify operation of `templateOpt...

GitHub user rdowner opened a pull request:

    https://github.com/apache/incubator-brooklyn/pull/714

    Clarify operation of `templateOptions` config key

    Follow on for PR #639; that PR has not been merged, but it's only commit snuck into another PR and has actually been merged. The intention of this PR is to address the review comments.
    
    Resolves the ambiguity around single parameters of type list. Extracts the bulk of the code into a new standalone class and adds tests. Adds documentation.
    
    Tested with this blueprint:
    
    ```yaml
    location: AWS_eu-west-1
    services:
    - type: brooklyn.entity.basic.EmptySoftwareProcess
      provisioningProperties:
        templateOptions:
          subnetId: subnet-041c8373
          securityGroupIds: ['sg-4db68928']
          mapNewVolumeToDeviceName: ["/dev/sda1", 100, true]
    ```
    
    ...and verified that all three parameters (each of which exercise a different code path) had been applied.

You can merge this pull request into a Git repository by running:

    $ git pull https://github.com/rdowner/incubator-brooklyn allow-list-in-templateOptions

Alternatively you can review and apply these changes as the patch at:

    https://github.com/apache/incubator-brooklyn/pull/714.patch

To close this pull request, make a commit to your master/trunk branch
with (at least) the following in the commit message:

    This closes #714
    
----
commit 8d95139d143826719239cf7e05b6159eb4ee5eac
Author: Richard Downer <ri...@apache.org>
Date:   2015-06-24T09:58:11Z

    Clarify operation of `templateOptions` config key
    
    Resolves the ambiguity around single parameters of type list. Extracts
    the bulk of the code into a new standalone class and adds tests. Adds
    documentation.

----


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] incubator-brooklyn pull request: Clarify operation of `templateOpt...

Posted by mikezaccardo <gi...@git.apache.org>.
Github user mikezaccardo commented on a diff in the pull request:

    https://github.com/apache/incubator-brooklyn/pull/714#discussion_r33174619
  
    --- Diff: core/src/main/java/brooklyn/util/flags/MethodCoercions.java ---
    @@ -0,0 +1,183 @@
    +/*
    + * Licensed to the Apache Software Foundation (ASF) under one
    + * or more contributor license agreements.  See the NOTICE file
    + * distributed with this work for additional information
    + * regarding copyright ownership.  The ASF licenses this file
    + * to you under the Apache License, Version 2.0 (the
    + * "License"); you may not use this file except in compliance
    + * with the License.  You may obtain a copy of the License at
    + *
    + *     http://www.apache.org/licenses/LICENSE-2.0
    + *
    + * Unless required by applicable law or agreed to in writing,
    + * software distributed under the License is distributed on an
    + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
    + * KIND, either express or implied.  See the License for the
    + * specific language governing permissions and limitations
    + * under the License.
    + */
    +package brooklyn.util.flags;
    +
    +import brooklyn.util.exceptions.Exceptions;
    +import brooklyn.util.guava.Maybe;
    +import com.google.common.base.Optional;
    +import com.google.common.base.Predicate;
    +import com.google.common.collect.Iterables;
    +import com.google.common.reflect.TypeToken;
    +
    +import javax.annotation.Nullable;
    +import java.lang.reflect.InvocationTargetException;
    +import java.lang.reflect.Method;
    +import java.lang.reflect.Type;
    +import java.util.Arrays;
    +import java.util.List;
    +
    +import static com.google.common.base.Preconditions.checkNotNull;
    +
    +/**
    + * A way of binding a loosely-specified method call into a strongly-typed Java method call.
    + */
    +public class MethodCoercions {
    +
    +    /**
    +     * Returns a predicate that matches a method with the given name, and a single parameter that
    +     * {@link brooklyn.util.flags.TypeCoercions#tryCoerce(Object, com.google.common.reflect.TypeToken)} can process
    +     * from the given argument.
    +     *
    +     * @param methodName name of the method
    +     * @param argument argument that is intended to be given
    +     * @return a predicate that will match a compatible method
    +     */
    +    public static Predicate<Method> matchSingleParameterMethod(final String methodName, final Object argument) {
    +        checkNotNull(methodName, "methodName");
    +        checkNotNull(argument, "argument");
    +
    +        return new Predicate<Method>() {
    +            @Override
    +            public boolean apply(@Nullable Method input) {
    +                if (input == null) return false;
    +                if (!input.getName().equals(methodName)) return false;
    +                Type[] parameterTypes = input.getGenericParameterTypes();
    +                return parameterTypes.length == 1
    +                        && TypeCoercions.tryCoerce(argument, TypeToken.of(parameterTypes[0])).isPresentAndNonNull();
    +
    +            }
    +        };
    +    }
    +
    +    /**
    +     * Tries to find a single-parameter method with a parameter compatible with (can be coerced to) the argument, and
    +     * invokes it.
    +     *
    +     * @param instance the object to invoke the method on
    +     * @param methodName the name of the method to invoke
    +     * @param argument the argument to the method's parameter.
    +     * @return the result of the method call, or {@link brooklyn.util.guava.Maybe#absent()} if method could not be matched.
    +     */
    +    public static Maybe<?> tryFindAndInvokeSingleParameterMethod(final Object instance, final String methodName, final Object argument) {
    +        Class<?> clazz = instance.getClass();
    +        Iterable<Method> methods = Arrays.asList(clazz.getMethods());
    +        Optional<Method> matchingMethod = Iterables.tryFind(methods, matchSingleParameterMethod(methodName, argument));
    +        if (matchingMethod.isPresent()) {
    +            Method method = matchingMethod.get();
    +            try {
    +                Type paramType = method.getGenericParameterTypes()[0];
    +                Object coercedArgument = TypeCoercions.coerce(argument, TypeToken.of(paramType));
    +                return Maybe.of(method.invoke(instance, coercedArgument));
    +            } catch (IllegalAccessException | InvocationTargetException e) {
    +                throw Exceptions.propagate(e);
    +            }
    +        } else {
    +            return Maybe.absent();
    +        }
    +    }
    +
    +    /**
    +     * Returns a predicate that matches a method with the given name, and parameters that
    +     * {@link brooklyn.util.flags.TypeCoercions#tryCoerce(Object, com.google.common.reflect.TypeToken)} can process
    +     * from the given list of arguments.
    +     *
    +     * @param methodName name of the method
    +     * @param arguments arguments that is intended to be given
    +     * @return a predicate that will match a compatible method
    +     */
    +    public static Predicate<Method> matchMultiParameterMethod(final String methodName, final List<?> arguments) {
    +        checkNotNull(methodName, "methodName");
    +        checkNotNull(arguments, "arguments");
    +
    +        return new Predicate<Method>() {
    +            @Override
    +            public boolean apply(@Nullable Method input) {
    +                if (input == null) return false;
    +                if (!input.getName().equals(methodName)) return false;
    +                int numOptionParams = arguments.size();
    +                Type[] parameterTypes = input.getGenericParameterTypes();
    +                if (parameterTypes.length != numOptionParams) return false;
    +
    +                for (int paramCount = 0; paramCount < numOptionParams; paramCount++) {
    +                    if (!TypeCoercions.tryCoerce(((List) arguments).get(paramCount),
    +                            TypeToken.of(parameterTypes[paramCount])).isPresentAndNonNull()) return false;
    +                }
    +                return true;
    +            }
    +        };
    +    }
    +
    +    /**
    +     * Tries to find a multiple-parameter method with each parameter compatible with (can be coerced to) the
    +     * corresponding argument, and invokes it.
    +     *
    +     * @param instance the object to invoke the method on
    +     * @param methodName the name of the method to invoke
    +     * @param argument a list of the arguments to the method's parameters.
    +     * @return the result of the method call, or {@link brooklyn.util.guava.Maybe#absent()} if method could not be matched.
    +     */
    +    public static Maybe<?> tryFindAndInvokeMultiParameterMethod(final Object instance, final String methodName, final List<?> arguments) {
    +        Class<?> clazz = instance.getClass();
    +        Iterable<Method> methods = Arrays.asList(clazz.getMethods());
    +        Optional<Method> matchingMethod = Iterables.tryFind(methods, matchMultiParameterMethod(methodName, arguments));
    +        if (matchingMethod.isPresent()) {
    +            Method method = matchingMethod.get();
    +            try {
    +                int numOptionParams = ((List)arguments).size();
    +                Object[] coercedArguments = new Object[numOptionParams];
    +                for (int paramCount = 0; paramCount < numOptionParams; paramCount++) {
    +                    Object argument = arguments.get(paramCount);
    +                    Type paramType = method.getGenericParameterTypes()[paramCount];
    +                    coercedArguments[paramCount] = TypeCoercions.coerce(argument, TypeToken.of(paramType));
    +                }
    +                return Maybe.of(method.invoke(instance, coercedArguments));
    +            } catch (IllegalAccessException | InvocationTargetException e) {
    +                throw Exceptions.propagate(e);
    +            }
    +        } else {
    +            return Maybe.absent();
    +        }
    +    }
    +
    +    /**
    +     * Tries to find a method with each parameter compatible with (can be coerced to) the corresponding argument, and invokes it.
    +     *
    +     * @param instance the object to invoke the method on
    +     * @param methodName the name of the method to invoke
    +     * @param argument a list of the arguments to the method's parameters, or a single argument for a single-parameter method.
    +     * @return the result of the method call, or {@link brooklyn.util.guava.Maybe#absent()} if method could not be matched.
    +     */
    +    public static Maybe<?> tryFindAndInvokeBestMatchingMethod(final Object instance, final String methodName, final Object argument) {
    +        if (argument instanceof List) {
    +            List<?> arguments = (List<?>) argument;
    +
    +            // ambiguous case: we can't tell if the user is using the multi-parameter syntax, or the single-parameter
    +            // syntax for a method which takes a List parameter. So we try one, then fall back to the other.
    +
    +            Maybe<?> maybe = tryFindAndInvokeMultiParameterMethod(instance, methodName, arguments);
    +            if (maybe.isAbsent())
    --- End diff --
    
    Personal preference: I like the conciseness of a ternary, so I would do something like:
    
    `return (maybe.isPresent()) ? maybe : tryFindAndInvokeSingleParameterMethod(instance, methodName, argument);`


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] incubator-brooklyn pull request: Clarify operation of `templateOpt...

Posted by mikezaccardo <gi...@git.apache.org>.
Github user mikezaccardo commented on the pull request:

    https://github.com/apache/incubator-brooklyn/pull/714#issuecomment-114960402
  
    All tests pass, LGTM


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] incubator-brooklyn pull request: Clarify operation of `templateOpt...

Posted by mikezaccardo <gi...@git.apache.org>.
Github user mikezaccardo commented on a diff in the pull request:

    https://github.com/apache/incubator-brooklyn/pull/714#discussion_r33172710
  
    --- Diff: core/src/main/java/brooklyn/util/flags/MethodCoercions.java ---
    @@ -0,0 +1,183 @@
    +/*
    + * Licensed to the Apache Software Foundation (ASF) under one
    + * or more contributor license agreements.  See the NOTICE file
    + * distributed with this work for additional information
    + * regarding copyright ownership.  The ASF licenses this file
    + * to you under the Apache License, Version 2.0 (the
    + * "License"); you may not use this file except in compliance
    + * with the License.  You may obtain a copy of the License at
    + *
    + *     http://www.apache.org/licenses/LICENSE-2.0
    + *
    + * Unless required by applicable law or agreed to in writing,
    + * software distributed under the License is distributed on an
    + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
    + * KIND, either express or implied.  See the License for the
    + * specific language governing permissions and limitations
    + * under the License.
    + */
    +package brooklyn.util.flags;
    +
    +import brooklyn.util.exceptions.Exceptions;
    +import brooklyn.util.guava.Maybe;
    +import com.google.common.base.Optional;
    +import com.google.common.base.Predicate;
    +import com.google.common.collect.Iterables;
    +import com.google.common.reflect.TypeToken;
    +
    +import javax.annotation.Nullable;
    +import java.lang.reflect.InvocationTargetException;
    +import java.lang.reflect.Method;
    +import java.lang.reflect.Type;
    +import java.util.Arrays;
    +import java.util.List;
    +
    +import static com.google.common.base.Preconditions.checkNotNull;
    +
    +/**
    + * A way of binding a loosely-specified method call into a strongly-typed Java method call.
    + */
    +public class MethodCoercions {
    +
    +    /**
    +     * Returns a predicate that matches a method with the given name, and a single parameter that
    +     * {@link brooklyn.util.flags.TypeCoercions#tryCoerce(Object, com.google.common.reflect.TypeToken)} can process
    +     * from the given argument.
    +     *
    +     * @param methodName name of the method
    +     * @param argument argument that is intended to be given
    +     * @return a predicate that will match a compatible method
    +     */
    +    public static Predicate<Method> matchSingleParameterMethod(final String methodName, final Object argument) {
    --- End diff --
    
    Could be good to add `@Nonnull` to the params.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] incubator-brooklyn pull request: Clarify operation of `templateOpt...

Posted by asfgit <gi...@git.apache.org>.
Github user asfgit closed the pull request at:

    https://github.com/apache/incubator-brooklyn/pull/714


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---