You are viewing a plain text version of this content. The canonical link for it is here.
Posted to dev@brooklyn.apache.org by robertgmoss <gi...@git.apache.org> on 2015/09/23 15:22:07 UTC

[GitHub] incubator-brooklyn pull request: Allow sensors to be aggregated us...

GitHub user robertgmoss opened a pull request:

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

    Allow sensors to be aggregated using a Reducer

    Combines sensors using a function and publishes into a target sensor, e.g
    
    ```
    location: localhost
    services:
    - type: org.apache.brooklyn.entity.stock.BasicApplication
    
      brooklyn.enrichers:
      - type: org.apache.brooklyn.enricher.stock.reducer.StringStringReducer
        brooklyn.config:
          enricher.sourceSensors:
          - $brooklyn:sensor("first.name")
          - $brooklyn:sensor("last.name")
          enricher.targetSensor:
            $brooklyn:sensor("full.name")
          enricher.reducerFunction.untyped: formatString
          enricher.reducerFunction.parameters:
            format: "%s %s"
    
      brooklyn.initializers:
      - type: brooklyn.entity.software.StaticSensor
        brooklyn.config:
          name: first.name
          targetType: String
          static.value: Foo
      - type: brooklyn.entity.software.StaticSensor
        brooklyn.config:
          name: last.name
          targetType: String
          static.value: Bar
    ```

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

    $ git pull https://github.com/robertgmoss/incubator-brooklyn reducer-enricher-additions

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

    https://github.com/apache/incubator-brooklyn/pull/919.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 #919
    
----
commit 0285da829e69a9003cd4b74a21fe207cce851a02
Author: Martin Harris <gi...@nakomis.com>
Date:   2015-09-22T13:56:02Z

    Adds reducer enricher

commit f592da401a0d29dd11b1a5a2b9048ff6c5996804
Author: Robert Moss <ro...@gmail.com>
Date:   2015-09-23T11:24:24Z

    add generic type reducer and tests

commit d9f8c33ad9367b67897d40ad21865fa9a4e6cb13
Author: Robert Moss <ro...@gmail.com>
Date:   2015-09-23T13:16:47Z

    adds formatString function

----


---
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: Allow sensors to be aggregated us...

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/919#discussion_r40340556
  
    --- Diff: core/src/main/java/org/apache/brooklyn/enricher/stock/reducer/GenericStringReducer.java ---
    @@ -0,0 +1,39 @@
    +/*
    + * 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 org.apache.brooklyn.enricher.stock.reducer;
    +
    +import java.util.List;
    +import java.util.Map;
    +
    +import com.google.common.base.Function;
    +import com.google.common.base.Preconditions;
    +
    +public abstract class GenericStringReducer<T> extends Reducer<T, String>{
    +
    +    @Override
    +    protected Function<List<T>, String> createReducerFunction(
    +            String reducerName, Map<String, ?> parameters) {
    +        if (reducerName.equals("formatString")){
    +            String format = Preconditions.checkNotNull((String)parameters.get("format"), "format");
    --- End diff --
    
    The second argument should be an error message rather than `"format"`, right?


---
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: Allow sensors to be aggregated us...

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

    https://github.com/apache/incubator-brooklyn/pull/919#discussion_r41168616
  
    --- Diff: core/src/main/java/org/apache/brooklyn/util/core/sensor/SensorPredicates.java ---
    @@ -0,0 +1,49 @@
    +/*
    + * 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 org.apache.brooklyn.util.core.sensor;
    +
    +import org.apache.brooklyn.api.sensor.Sensor;
    +
    +import com.google.common.base.Predicate;
    +
    +public class SensorPredicates {
    +
    +    private SensorPredicates() {
    +        // not instantiable
    +    }
    +    
    +    public static Predicate<Sensor<?>> sensorNameEqualTo(String sensorName) {
    +        return new SensorNameEquals(sensorName);
    --- End diff --
    
    I'd do `checkNotNull(sensorName, "sensorName)`, rather than risk it throwing an NPE in apply (at which point the stacktrace will tell us nothing about where the null was passed in).
    
    (If it were ever possible to have a null sensor name, then I'd let us pass in null to this method).


---
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: Allow sensors to be aggregated us...

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

    https://github.com/apache/incubator-brooklyn/pull/919#issuecomment-144961725
  
    Review comments addressed


---
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: Allow sensors to be aggregated us...

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/919#discussion_r40342438
  
    --- Diff: core/src/main/java/org/apache/brooklyn/enricher/stock/reducer/Reducer.java ---
    @@ -0,0 +1,181 @@
    +/*
    + * 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 org.apache.brooklyn.enricher.stock.reducer;
    +
    +import java.util.Iterator;
    +import java.util.List;
    +import java.util.Map;
    +
    +import org.apache.brooklyn.api.entity.Entity;
    +import org.apache.brooklyn.api.entity.EntityLocal;
    +import org.apache.brooklyn.api.sensor.AttributeSensor;
    +import org.apache.brooklyn.api.sensor.Sensor;
    +import org.apache.brooklyn.api.sensor.SensorEvent;
    +import org.apache.brooklyn.api.sensor.SensorEventListener;
    +import org.apache.brooklyn.config.ConfigKey;
    +import org.apache.brooklyn.core.config.ConfigKeys;
    +import org.apache.brooklyn.core.enricher.AbstractEnricher;
    +import org.apache.brooklyn.util.core.flags.SetFromFlag;
    +import org.apache.brooklyn.util.core.task.Tasks;
    +import org.apache.brooklyn.util.core.task.ValueResolver;
    +import org.slf4j.Logger;
    +import org.slf4j.LoggerFactory;
    +
    +import com.google.api.client.util.Lists;
    +import com.google.common.base.Function;
    +import com.google.common.base.Preconditions;
    +import com.google.common.collect.ImmutableList;
    +import com.google.common.reflect.TypeToken;
    +
    +@SuppressWarnings("serial")
    +public abstract class Reducer<S, T> extends AbstractEnricher implements SensorEventListener<Object> {
    +
    +    private static final Logger LOG = LoggerFactory.getLogger(Reducer.class);
    +
    +    @SetFromFlag("producer")
    +    public static ConfigKey<Entity> PRODUCER = ConfigKeys.newConfigKey(Entity.class, "enricher.producer");
    +    public static ConfigKey<Sensor<?>> TARGET_SENSOR = ConfigKeys.newConfigKey(new TypeToken<Sensor<?>>() {}, "enricher.targetSensor");
    +    public static ConfigKey<List<? extends AttributeSensor<?>>> SOURCE_SENSORS = ConfigKeys.newConfigKey(new TypeToken<List<? extends AttributeSensor<?>>>() {}, "enricher.sourceSensors");
    +    public static ConfigKey<Function<List<?>,?>> REDUCER_FUNCTION = ConfigKeys.newConfigKey(new TypeToken<Function<List<?>, ?>>() {}, "enricher.reducerFunction");
    +    @SetFromFlag("transformation")
    +    public static final ConfigKey<String> REDUCER_FUNCTION_UNTYPED = ConfigKeys.newStringConfigKey("enricher.reducerFunction.untyped",
    +        "A string matching a pre-defined named reducer function, such as join");
    +    public static final ConfigKey<Map<String, Object>> PARAMETERS = ConfigKeys.newConfigKey(new TypeToken<Map<String, Object>>() {}, "enricher.reducerFunction.parameters", 
    +        "A map of parameters to pass into the reducer function");
    +   
    +    protected Entity producer;
    +    protected List<AttributeSensor<S>> subscribedSensors;
    +    protected Sensor<T> targetSensor;
    +    protected Function<List<S>, T> reducerFunction;
    +
    +    @SuppressWarnings({ "unchecked", "rawtypes" })
    +    @Override
    +    public void setEntity(EntityLocal entity) {
    +        super.setEntity(entity);
    +        Preconditions.checkNotNull(getConfig(SOURCE_SENSORS), "source sensors");
    +
    +        this.producer = getConfig(PRODUCER) == null ? entity : getConfig(PRODUCER);
    +        List<AttributeSensor<S>> sensorListTemp = Lists.newArrayList();
    +
    +        for (Object sensorO : getConfig(SOURCE_SENSORS)) {
    +            AttributeSensor<S> sensor = Tasks.resolving(sensorO).as(AttributeSensor.class).timeout(ValueResolver.REAL_QUICK_WAIT).context(producer).get();
    +            if(!sensorListTemp.contains(sensor)) {
    --- End diff --
    
    Sanity check: neither `AttributeSensor` nor any of its children define an `equals()` method -- is it possible for there to be two sensors here which are logically equal but not actually the same (different memory locations)? If yes, then this check won't work.


---
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: Allow sensors to be aggregated us...

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

    https://github.com/apache/incubator-brooklyn/pull/919#issuecomment-146797200
  
    Excellent, thanks @robertgmoss - merging.


---
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: Allow sensors to be aggregated us...

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

    https://github.com/apache/incubator-brooklyn/pull/919#discussion_r41145950
  
    --- Diff: core/src/main/java/org/apache/brooklyn/enricher/stock/Enrichers.java ---
    @@ -171,6 +173,9 @@ public PropagatorBuilder propagatingAllBut(Iterable<? extends Sensor<?>> vals) {
             public JoinerBuilder joining(AttributeSensor<?> source) {
                 return new JoinerBuilder(source);
             }
    +        public <S, T> ReducerBuilder<S, T> reducing(Class<? extends Reducer<S, T>> clazz, List<AttributeSensor<S>> sourceSensors) {
    --- End diff --
    
    Would be nice to have an additional method factory which just uses the generic `Reducer` implementation, working with `Function<List<?>, ?>` params - which I guess would be the main way it's used in java land.


---
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: Allow sensors to be aggregated us...

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

    https://github.com/apache/incubator-brooklyn/pull/919#issuecomment-145535770
  
    All the comments I have are in bike-shedding land, so feel free to ignore. Here are some more:
      * From a user perspective I would prefer to use a single `Reducer` which knows how to load any transformation alias (as opposed to having to look up which implementation does which alias).
      * When working with sensors (especially in yaml land) you never know what the type of the input sensor(s) will be even if the interface is typed in Java. So as a rule of thumb it's nice to `coerce` to the required type instead of forcing the sensor to be of the required type. This would also alleviate the need for all the XXXStringReducer alternatives.
    
    
    Looks good and can be merged as is.


---
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: Allow sensors to be aggregated us...

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

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


---
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: Allow sensors to be aggregated us...

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

    https://github.com/apache/incubator-brooklyn/pull/919#discussion_r40929738
  
    --- Diff: core/src/main/java/org/apache/brooklyn/enricher/stock/Enrichers.java ---
    @@ -676,6 +681,62 @@ public String toString() {
                         .toString();
             }
         }
    +
    +    protected abstract static class AbstractReducerBuilder<S, T, B extends AbstractReducerBuilder<S, T, B>> extends AbstractEnricherBuilder<B> {
    +        protected AttributeSensor<T> publishing;
    +        protected Entity fromEntity;
    +        protected List<AttributeSensor<S>> reducing;
    +        protected Function<List<S>, T> computing;
    +        protected String functionName;
    +        private Map<String, Object> parameters;
    +
    +        public AbstractReducerBuilder(Class<? extends Reducer<S, T>> clazz, List<AttributeSensor<S>> val) {
    --- End diff --
    
    This would be inconsistent with the other uses throughout, and could cause confusion.  I'm inclined to say that this should be done in another PR.  Moreover, this is a protected class and not public.  Perhaps a discussion on the mailing list about whether this should be adopted widely.


---
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: Allow sensors to be aggregated us...

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

    https://github.com/apache/incubator-brooklyn/pull/919#discussion_r41605652
  
    --- Diff: utils/common/src/main/java/org/apache/brooklyn/util/text/StringFunctions.java ---
    @@ -67,6 +70,15 @@ public String apply(@Nullable Object[] input) {
                 }
             };
         }
    +    
    +    /** given e.g. "hello %s %s" returns a function which will insert an Iterable of two strings into that pattern */
    +     public static Function<Iterable<?>, String> formatterForIterable(final String pattern) {
    +        return new Function<Iterable<?>, String>() {
    +            public String apply(@Nullable Iterable<?> input) {
    +                return String.format(pattern, Iterables.toArray(input, Object.class));
    --- End diff --
    
    This will NPE if `input` is null, yet the parameter is marked `@Nullable`. Should we remove the annotation, or explicitly check for null (e.g. to return null if input is null)?


---
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: Allow sensors to be aggregated us...

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/919#discussion_r40339207
  
    --- Diff: core/src/main/java/org/apache/brooklyn/enricher/stock/Transformer.java ---
    @@ -23,6 +23,8 @@
     import org.apache.brooklyn.api.sensor.SensorEvent;
     import org.apache.brooklyn.config.ConfigKey;
     import org.apache.brooklyn.core.config.ConfigKeys;
    +import org.apache.brooklyn.core.entity.Attributes;
    --- End diff --
    
    These imports are never used


---
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: Allow sensors to be aggregated us...

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/919#discussion_r40344015
  
    --- Diff: core/src/main/java/org/apache/brooklyn/enricher/stock/reducer/StringStringReducer.java ---
    @@ -0,0 +1,41 @@
    +/*
    + * 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 org.apache.brooklyn.enricher.stock.reducer;
    +
    +import java.util.List;
    +import java.util.Map;
    +
    +import com.google.common.base.Function;
    +
    +public class StringStringReducer extends GenericStringReducer<String> {
    +    
    +    public StringStringReducer() {}
    +
    +    @Override
    +    protected Function<List<String>, String> createReducerFunction(
    +            String reducerName, Map<String, ?> parameters) {
    +        Function<List<String>, String> function = super.createReducerFunction(reducerName, parameters);
    +        if(function != null) return function;
    +        
    +        if(reducerName.equals("joiner")){
    --- End diff --
    
    Same comment about `Objects.equal()`


---
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: Allow sensors to be aggregated us...

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

    https://github.com/apache/incubator-brooklyn/pull/919#issuecomment-146682142
  
    @aledsage Comments addressed


---
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: Allow sensors to be aggregated us...

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/919#discussion_r40340374
  
    --- Diff: core/src/main/java/org/apache/brooklyn/enricher/stock/reducer/GenericStringReducer.java ---
    @@ -0,0 +1,39 @@
    +/*
    + * 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 org.apache.brooklyn.enricher.stock.reducer;
    +
    +import java.util.List;
    +import java.util.Map;
    +
    +import com.google.common.base.Function;
    +import com.google.common.base.Preconditions;
    +
    +public abstract class GenericStringReducer<T> extends Reducer<T, String>{
    +
    +    @Override
    +    protected Function<List<T>, String> createReducerFunction(
    +            String reducerName, Map<String, ?> parameters) {
    +        if (reducerName.equals("formatString")){
    --- End diff --
    
    Would be good to use `Objects.equal(reducerName, "formatString")` to avoid NPE if `reducerName` is `null`.


---
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: Allow sensors to be aggregated us...

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/919#discussion_r40344471
  
    --- Diff: core/src/main/java/org/apache/brooklyn/enricher/stock/reducer/Reducer.java ---
    @@ -0,0 +1,181 @@
    +/*
    + * 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 org.apache.brooklyn.enricher.stock.reducer;
    +
    +import java.util.Iterator;
    +import java.util.List;
    +import java.util.Map;
    +
    +import org.apache.brooklyn.api.entity.Entity;
    +import org.apache.brooklyn.api.entity.EntityLocal;
    +import org.apache.brooklyn.api.sensor.AttributeSensor;
    +import org.apache.brooklyn.api.sensor.Sensor;
    +import org.apache.brooklyn.api.sensor.SensorEvent;
    +import org.apache.brooklyn.api.sensor.SensorEventListener;
    +import org.apache.brooklyn.config.ConfigKey;
    +import org.apache.brooklyn.core.config.ConfigKeys;
    +import org.apache.brooklyn.core.enricher.AbstractEnricher;
    +import org.apache.brooklyn.util.core.flags.SetFromFlag;
    +import org.apache.brooklyn.util.core.task.Tasks;
    +import org.apache.brooklyn.util.core.task.ValueResolver;
    +import org.slf4j.Logger;
    +import org.slf4j.LoggerFactory;
    +
    +import com.google.api.client.util.Lists;
    +import com.google.common.base.Function;
    +import com.google.common.base.Preconditions;
    +import com.google.common.collect.ImmutableList;
    +import com.google.common.reflect.TypeToken;
    +
    +@SuppressWarnings("serial")
    +public abstract class Reducer<S, T> extends AbstractEnricher implements SensorEventListener<Object> {
    +
    +    private static final Logger LOG = LoggerFactory.getLogger(Reducer.class);
    +
    +    @SetFromFlag("producer")
    +    public static ConfigKey<Entity> PRODUCER = ConfigKeys.newConfigKey(Entity.class, "enricher.producer");
    +    public static ConfigKey<Sensor<?>> TARGET_SENSOR = ConfigKeys.newConfigKey(new TypeToken<Sensor<?>>() {}, "enricher.targetSensor");
    +    public static ConfigKey<List<? extends AttributeSensor<?>>> SOURCE_SENSORS = ConfigKeys.newConfigKey(new TypeToken<List<? extends AttributeSensor<?>>>() {}, "enricher.sourceSensors");
    +    public static ConfigKey<Function<List<?>,?>> REDUCER_FUNCTION = ConfigKeys.newConfigKey(new TypeToken<Function<List<?>, ?>>() {}, "enricher.reducerFunction");
    +    @SetFromFlag("transformation")
    +    public static final ConfigKey<String> REDUCER_FUNCTION_UNTYPED = ConfigKeys.newStringConfigKey("enricher.reducerFunction.untyped",
    +        "A string matching a pre-defined named reducer function, such as join");
    --- End diff --
    
    Should be "joiner" as the example


---
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: Allow sensors to be aggregated us...

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

    https://github.com/apache/incubator-brooklyn/pull/919#discussion_r41605667
  
    --- Diff: utils/common/src/main/java/org/apache/brooklyn/util/text/StringFunctions.java ---
    @@ -154,4 +166,8 @@ public String apply(String input) {
             };
         }
     
    +
    --- End diff --
    
    Pedantic: remove blank lines.


---
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: Allow sensors to be aggregated us...

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

    https://github.com/apache/incubator-brooklyn/pull/919#discussion_r41167017
  
    --- Diff: core/src/main/java/org/apache/brooklyn/enricher/stock/reducer/Reducer.java ---
    @@ -0,0 +1,187 @@
    +/*
    + * 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 org.apache.brooklyn.enricher.stock.reducer;
    +
    +import java.util.Iterator;
    +import java.util.List;
    +import java.util.Map;
    +
    +import org.apache.brooklyn.api.entity.Entity;
    +import org.apache.brooklyn.api.entity.EntityLocal;
    +import org.apache.brooklyn.api.sensor.AttributeSensor;
    +import org.apache.brooklyn.api.sensor.Sensor;
    +import org.apache.brooklyn.api.sensor.SensorEvent;
    +import org.apache.brooklyn.api.sensor.SensorEventListener;
    +import org.apache.brooklyn.config.ConfigKey;
    +import org.apache.brooklyn.core.config.ConfigKeys;
    +import org.apache.brooklyn.core.enricher.AbstractEnricher;
    +import org.apache.brooklyn.util.core.flags.SetFromFlag;
    +import org.apache.brooklyn.util.core.sensor.SensorPredicates;
    +import org.apache.brooklyn.util.core.task.Tasks;
    +import org.apache.brooklyn.util.core.task.ValueResolver;
    +import org.slf4j.Logger;
    +import org.slf4j.LoggerFactory;
    +
    +import com.google.api.client.util.Lists;
    +import com.google.common.base.Function;
    +import com.google.common.base.Optional;
    +import com.google.common.base.Preconditions;
    +import com.google.common.collect.ImmutableList;
    +import com.google.common.collect.Iterables;
    +import com.google.common.reflect.TypeToken;
    +
    +@SuppressWarnings("serial")
    +public abstract class Reducer<S, T> extends AbstractEnricher implements SensorEventListener<Object> {
    +
    +    private static final Logger LOG = LoggerFactory.getLogger(Reducer.class);
    +
    +    @SetFromFlag("producer")
    +    public static ConfigKey<Entity> PRODUCER = ConfigKeys.newConfigKey(Entity.class, "enricher.producer");
    +    public static ConfigKey<Sensor<?>> TARGET_SENSOR = ConfigKeys.newConfigKey(new TypeToken<Sensor<?>>() {}, "enricher.targetSensor");
    +    public static ConfigKey<List<? extends AttributeSensor<?>>> SOURCE_SENSORS = ConfigKeys.newConfigKey(new TypeToken<List<? extends AttributeSensor<?>>>() {}, "enricher.sourceSensors");
    +    public static ConfigKey<Function<List<?>,?>> REDUCER_FUNCTION = ConfigKeys.newConfigKey(new TypeToken<Function<List<?>, ?>>() {}, "enricher.reducerFunction");
    +    @SetFromFlag("transformation")
    +    public static final ConfigKey<String> REDUCER_FUNCTION_TRANSFORMATION = ConfigKeys.newStringConfigKey("enricher.reducerFunction.transformation",
    +        "A string matching a pre-defined named reducer function, such as joiner");
    +    public static final ConfigKey<Map<String, Object>> PARAMETERS = ConfigKeys.newConfigKey(new TypeToken<Map<String, Object>>() {}, "enricher.reducerFunction.parameters", 
    +        "A map of parameters to pass into the reducer function");
    +   
    +    protected Entity producer;
    +    protected List<AttributeSensor<S>> subscribedSensors;
    +    protected Sensor<T> targetSensor;
    +    protected Function<List<S>, T> reducerFunction;
    +
    +    @SuppressWarnings({ "unchecked", "rawtypes" })
    +    @Override
    +    public void setEntity(EntityLocal entity) {
    +        super.setEntity(entity);
    +        Preconditions.checkNotNull(getConfig(SOURCE_SENSORS), "source sensors");
    +
    +        this.producer = getConfig(PRODUCER) == null ? entity : getConfig(PRODUCER);
    +        List<AttributeSensor<S>> sensorListTemp = Lists.newArrayList();
    +
    +        for (Object sensorO : getConfig(SOURCE_SENSORS)) {
    +            AttributeSensor<S> sensor = Tasks.resolving(sensorO).as(AttributeSensor.class).timeout(ValueResolver.REAL_QUICK_WAIT).context(producer).get();
    +            Optional<? extends Sensor<?>> foundSensor = Iterables.tryFind(sensorListTemp, 
    +                    SensorPredicates.sensorNameEqualTo(sensor.getName()));
    +            
    +            if(!foundSensor.isPresent()) {
    +                sensorListTemp.add(sensor);
    +            }
    +        }
    +        
    +        String reducerName = config().get(REDUCER_FUNCTION_TRANSFORMATION);
    +        Function<List<S>, T> reducerFunction = (Function) config().get(REDUCER_FUNCTION);
    +        if(reducerFunction == null){
    +            Map<String, ?> parameters = config().get(PARAMETERS);
    +            reducerFunction = createReducerFunction(reducerName, parameters);
    +        }
    +
    +        this.reducerFunction = reducerFunction;
    +        Preconditions.checkState(sensorListTemp.size() > 0, "Nothing to reduce");
    +
    +        for (Sensor<S> sensor : sensorListTemp) {
    +            subscribe(producer, sensor, this);
    +        }
    +
    +        subscribedSensors = ImmutableList.copyOf(sensorListTemp);
    +    }
    +
    +    protected abstract Function<List<S>, T> createReducerFunction(String reducerName, Map<String, ?> parameters);
    +    
    +    @SuppressWarnings("unchecked")
    +    @Override
    +    public void onEvent(SensorEvent<Object> event) {
    +        Sensor<T> destinationSensor = (Sensor<T>) getConfig(TARGET_SENSOR);
    +
    +        List<S> values = Lists.newArrayList();
    +
    +        for (AttributeSensor<S> sourceSensor : subscribedSensors) {
    +            S resolvedSensorValue = entity.sensors().get(sourceSensor);
    +            if (resolvedSensorValue == null) {
    +                // only apply function if all values are resolved
    +                return;
    +            }
    +
    +            values.add(resolvedSensorValue);
    +        }
    +
    +        Object result = reducerFunction.apply(values);
    +
    +        if (LOG.isTraceEnabled()) LOG.trace("enricher {} got {}, propagating via {} as {}",
    +                new Object[] {this, event, entity, reducerFunction, destinationSensor});
    +
    +        emit((Sensor<T>)destinationSensor, result);
    +    }
    +   
    +    public static class JoinerReducerFunction<A> implements Function<List<A>, String> {
    --- End diff --
    
    Why not use `StringFunctions.joiner(separator)` (which delegates to `Strings.join` for its `apply` method)?


---
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: Allow sensors to be aggregated us...

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

    https://github.com/apache/incubator-brooklyn/pull/919#discussion_r41168345
  
    --- Diff: core/src/main/java/org/apache/brooklyn/util/core/sensor/SensorPredicates.java ---
    @@ -0,0 +1,49 @@
    +/*
    + * 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 org.apache.brooklyn.util.core.sensor;
    +
    +import org.apache.brooklyn.api.sensor.Sensor;
    +
    +import com.google.common.base.Predicate;
    +
    +public class SensorPredicates {
    +
    +    private SensorPredicates() {
    +        // not instantiable
    +    }
    +    
    +    public static Predicate<Sensor<?>> sensorNameEqualTo(String sensorName) {
    --- End diff --
    
    I'd personally go for `nameEqualTo` (it's implicit that it's a sensor, based on the class name). That would be more in-keeping with naming in our other `*Predicates` classes.


---
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: Allow sensors to be aggregated us...

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

    https://github.com/apache/incubator-brooklyn/pull/919#discussion_r41168639
  
    --- Diff: core/src/main/java/org/apache/brooklyn/util/core/sensor/SensorPredicates.java ---
    @@ -0,0 +1,49 @@
    +/*
    + * 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 org.apache.brooklyn.util.core.sensor;
    +
    +import org.apache.brooklyn.api.sensor.Sensor;
    +
    +import com.google.common.base.Predicate;
    +
    +public class SensorPredicates {
    +
    +    private SensorPredicates() {
    +        // not instantiable
    +    }
    +    
    +    public static Predicate<Sensor<?>> sensorNameEqualTo(String sensorName) {
    +        return new SensorNameEquals(sensorName);
    +    }
    +
    +    private static class SensorNameEquals implements Predicate<Sensor<?>> {
    +        
    +        private String sensor;
    --- End diff --
    
    use `final` wherever possible.


---
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: Allow sensors to be aggregated us...

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

    https://github.com/apache/incubator-brooklyn/pull/919#issuecomment-146509185
  
    @robertgmoss looks really useful.  as soon as you can respond to the copious but good comments from @aledsage and @neykov let's merge!


---
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: Allow sensors to be aggregated us...

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/919#discussion_r40338238
  
    --- Diff: core/src/main/java/org/apache/brooklyn/enricher/stock/Enrichers.java ---
    @@ -676,6 +681,62 @@ public String toString() {
                         .toString();
             }
         }
    +
    +    protected abstract static class AbstractReducerBuilder<S, T, B extends AbstractReducerBuilder<S, T, B>> extends AbstractEnricherBuilder<B> {
    +        protected AttributeSensor<T> publishing;
    +        protected Entity fromEntity;
    +        protected List<AttributeSensor<S>> reducing;
    +        protected Function<List<S>, T> computing;
    +        protected String functionName;
    +        private Map<String, Object> parameters;
    +
    +        public AbstractReducerBuilder(Class<? extends Reducer<S, T>> clazz, List<AttributeSensor<S>> val) {
    --- End diff --
    
    Add `@Nonnull` to this and the following args with `null` checks?


---
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: Allow sensors to be aggregated us...

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

    https://github.com/apache/incubator-brooklyn/pull/919#discussion_r41167769
  
    --- Diff: core/src/main/java/org/apache/brooklyn/enricher/stock/reducer/StringStringReducer.java ---
    @@ -0,0 +1,42 @@
    +/*
    + * 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 org.apache.brooklyn.enricher.stock.reducer;
    +
    +import java.util.List;
    +import java.util.Map;
    +import java.util.Objects;
    +
    +import com.google.common.base.Function;
    +
    +public class StringStringReducer extends GenericStringReducer<String> {
    --- End diff --
    
    Agree with Svet's comment - the `StringStringReducer` is a bit worrying. It makes me think we're only handling a sub-set of the possible use-cases, and opening ourselves to having many variants longer term. Is there anything smart we can do with generics instead, and/or coercion?


---
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: Allow sensors to be aggregated us...

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

    https://github.com/apache/incubator-brooklyn/pull/919#discussion_r41167202
  
    --- Diff: core/src/main/java/org/apache/brooklyn/enricher/stock/reducer/Reducer.java ---
    @@ -0,0 +1,187 @@
    +/*
    + * 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 org.apache.brooklyn.enricher.stock.reducer;
    +
    +import java.util.Iterator;
    +import java.util.List;
    +import java.util.Map;
    +
    +import org.apache.brooklyn.api.entity.Entity;
    +import org.apache.brooklyn.api.entity.EntityLocal;
    +import org.apache.brooklyn.api.sensor.AttributeSensor;
    +import org.apache.brooklyn.api.sensor.Sensor;
    +import org.apache.brooklyn.api.sensor.SensorEvent;
    +import org.apache.brooklyn.api.sensor.SensorEventListener;
    +import org.apache.brooklyn.config.ConfigKey;
    +import org.apache.brooklyn.core.config.ConfigKeys;
    +import org.apache.brooklyn.core.enricher.AbstractEnricher;
    +import org.apache.brooklyn.util.core.flags.SetFromFlag;
    +import org.apache.brooklyn.util.core.sensor.SensorPredicates;
    +import org.apache.brooklyn.util.core.task.Tasks;
    +import org.apache.brooklyn.util.core.task.ValueResolver;
    +import org.slf4j.Logger;
    +import org.slf4j.LoggerFactory;
    +
    +import com.google.api.client.util.Lists;
    +import com.google.common.base.Function;
    +import com.google.common.base.Optional;
    +import com.google.common.base.Preconditions;
    +import com.google.common.collect.ImmutableList;
    +import com.google.common.collect.Iterables;
    +import com.google.common.reflect.TypeToken;
    +
    +@SuppressWarnings("serial")
    +public abstract class Reducer<S, T> extends AbstractEnricher implements SensorEventListener<Object> {
    +
    +    private static final Logger LOG = LoggerFactory.getLogger(Reducer.class);
    +
    +    @SetFromFlag("producer")
    +    public static ConfigKey<Entity> PRODUCER = ConfigKeys.newConfigKey(Entity.class, "enricher.producer");
    +    public static ConfigKey<Sensor<?>> TARGET_SENSOR = ConfigKeys.newConfigKey(new TypeToken<Sensor<?>>() {}, "enricher.targetSensor");
    +    public static ConfigKey<List<? extends AttributeSensor<?>>> SOURCE_SENSORS = ConfigKeys.newConfigKey(new TypeToken<List<? extends AttributeSensor<?>>>() {}, "enricher.sourceSensors");
    +    public static ConfigKey<Function<List<?>,?>> REDUCER_FUNCTION = ConfigKeys.newConfigKey(new TypeToken<Function<List<?>, ?>>() {}, "enricher.reducerFunction");
    +    @SetFromFlag("transformation")
    +    public static final ConfigKey<String> REDUCER_FUNCTION_TRANSFORMATION = ConfigKeys.newStringConfigKey("enricher.reducerFunction.transformation",
    +        "A string matching a pre-defined named reducer function, such as joiner");
    +    public static final ConfigKey<Map<String, Object>> PARAMETERS = ConfigKeys.newConfigKey(new TypeToken<Map<String, Object>>() {}, "enricher.reducerFunction.parameters", 
    +        "A map of parameters to pass into the reducer function");
    +   
    +    protected Entity producer;
    +    protected List<AttributeSensor<S>> subscribedSensors;
    +    protected Sensor<T> targetSensor;
    +    protected Function<List<S>, T> reducerFunction;
    +
    +    @SuppressWarnings({ "unchecked", "rawtypes" })
    +    @Override
    +    public void setEntity(EntityLocal entity) {
    +        super.setEntity(entity);
    +        Preconditions.checkNotNull(getConfig(SOURCE_SENSORS), "source sensors");
    +
    +        this.producer = getConfig(PRODUCER) == null ? entity : getConfig(PRODUCER);
    +        List<AttributeSensor<S>> sensorListTemp = Lists.newArrayList();
    +
    +        for (Object sensorO : getConfig(SOURCE_SENSORS)) {
    +            AttributeSensor<S> sensor = Tasks.resolving(sensorO).as(AttributeSensor.class).timeout(ValueResolver.REAL_QUICK_WAIT).context(producer).get();
    +            Optional<? extends Sensor<?>> foundSensor = Iterables.tryFind(sensorListTemp, 
    +                    SensorPredicates.sensorNameEqualTo(sensor.getName()));
    +            
    +            if(!foundSensor.isPresent()) {
    +                sensorListTemp.add(sensor);
    +            }
    +        }
    +        
    +        String reducerName = config().get(REDUCER_FUNCTION_TRANSFORMATION);
    +        Function<List<S>, T> reducerFunction = (Function) config().get(REDUCER_FUNCTION);
    +        if(reducerFunction == null){
    +            Map<String, ?> parameters = config().get(PARAMETERS);
    +            reducerFunction = createReducerFunction(reducerName, parameters);
    +        }
    +
    +        this.reducerFunction = reducerFunction;
    +        Preconditions.checkState(sensorListTemp.size() > 0, "Nothing to reduce");
    +
    +        for (Sensor<S> sensor : sensorListTemp) {
    +            subscribe(producer, sensor, this);
    +        }
    +
    +        subscribedSensors = ImmutableList.copyOf(sensorListTemp);
    +    }
    +
    +    protected abstract Function<List<S>, T> createReducerFunction(String reducerName, Map<String, ?> parameters);
    +    
    +    @SuppressWarnings("unchecked")
    +    @Override
    +    public void onEvent(SensorEvent<Object> event) {
    +        Sensor<T> destinationSensor = (Sensor<T>) getConfig(TARGET_SENSOR);
    +
    +        List<S> values = Lists.newArrayList();
    +
    +        for (AttributeSensor<S> sourceSensor : subscribedSensors) {
    +            S resolvedSensorValue = entity.sensors().get(sourceSensor);
    +            if (resolvedSensorValue == null) {
    +                // only apply function if all values are resolved
    +                return;
    +            }
    +
    +            values.add(resolvedSensorValue);
    +        }
    +
    +        Object result = reducerFunction.apply(values);
    +
    +        if (LOG.isTraceEnabled()) LOG.trace("enricher {} got {}, propagating via {} as {}",
    +                new Object[] {this, event, entity, reducerFunction, destinationSensor});
    +
    +        emit((Sensor<T>)destinationSensor, result);
    +    }
    +   
    +    public static class JoinerReducerFunction<A> implements Function<List<A>, String> {
    +        
    +        private Object separator;
    +
    +        public JoinerReducerFunction(Object separator) {
    +            this.separator = (separator == null) ? ", " : separator;
    +        }
    +
    +        @Override
    +        public String apply(List<A> input) {
    +            
    +            StringBuilder sb = new StringBuilder();
    +            Iterator<A> it = input.iterator();
    +            while(it.hasNext()) {
    +                sb.append(it.next().toString());
    +                if(it.hasNext()){
    +                    sb.append(separator);
    +                }
    +            }
    +            return sb.toString();
    +        }
    +        
    +    }
    +
    +    public static class JoinerFunction extends JoinerReducerFunction<String>{
    +        
    +        public JoinerFunction(Object separator) {
    +            super(separator);
    +        }
    +    }
    +
    +    public static class ToStringReducerFunction<A> implements Function<List<A>, String> {
    --- End diff --
    
    See guava's `Functions#toStringFunction()` (which we delegate to in Brooklyn's `StringFunctions.toStringFunction`).


---
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: Allow sensors to be aggregated us...

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

    https://github.com/apache/incubator-brooklyn/pull/919#discussion_r41605511
  
    --- Diff: core/src/test/java/org/apache/brooklyn/enricher/stock/reducer/ReducerTest.java ---
    @@ -0,0 +1,240 @@
    +/*
    + * 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 org.apache.brooklyn.enricher.stock.reducer;
    +
    +import java.util.List;
    +
    +import javax.annotation.Nullable;
    +
    +import org.apache.brooklyn.api.entity.EntitySpec;
    +import org.apache.brooklyn.api.sensor.AttributeSensor;
    +import org.apache.brooklyn.api.sensor.EnricherSpec;
    +import org.apache.brooklyn.core.sensor.Sensors;
    +import org.apache.brooklyn.core.test.BrooklynAppUnitTestSupport;
    +import org.apache.brooklyn.core.test.entity.TestEntity;
    +import org.apache.brooklyn.enricher.stock.Enrichers;
    +import org.apache.brooklyn.test.Asserts;
    +import org.apache.brooklyn.test.EntityTestUtils;
    +import org.apache.brooklyn.util.collections.MutableMap;
    +import org.apache.brooklyn.util.exceptions.Exceptions;
    +import org.testng.Assert;
    +import org.testng.annotations.BeforeMethod;
    +import org.testng.annotations.Test;
    +
    +import com.google.common.base.Function;
    +import com.google.common.collect.ImmutableList;
    +import com.google.common.collect.ImmutableMap;
    +
    +public class ReducerTest extends BrooklynAppUnitTestSupport {
    +
    +    public static final AttributeSensor<String> STR1 = Sensors.newStringSensor("test.str1");
    +    public static final AttributeSensor<String> STR2 = Sensors.newStringSensor("test.str2");
    +    public static final AttributeSensor<String> STR3 = Sensors.newStringSensor("test.str3");
    +    public static final AttributeSensor<Integer> INT1 = Sensors.newIntegerSensor("test.int1");
    +
    +    private TestEntity entity;
    +
    +    @BeforeMethod(alwaysRun=true)
    +    @Override
    +    public void setUp() throws Exception {
    +        super.setUp();
    +        entity = app.createAndManageChild(EntitySpec.create(TestEntity.class));
    +    }
    +
    +    @Test
    +    public void testBasicReducer(){
    +        entity.enrichers().add(EnricherSpec.create(Reducer.class).configure(
    +                MutableMap.of(
    +                Reducer.SOURCE_SENSORS, ImmutableList.of(STR1, STR2),
    +                Reducer.PRODUCER, entity,
    +                Reducer.TARGET_SENSOR, STR3,
    +                Reducer.REDUCER_FUNCTION, new Concatenator())
    +            )
    +        );
    +
    +        EntityTestUtils.assertAttributeEquals(entity, STR3, null);
    +        
    +        entity.sensors().set(STR1, "foo");
    +        EntityTestUtils.assertAttributeEqualsContinually(entity, STR3, null);
    +
    +        entity.sensors().set(STR2, "bar");
    +        EntityTestUtils.assertAttributeEqualsEventually(entity, STR3, "foobar");
    +    }
    +
    +    @Test
    +    public void testReducingBuilderWithConcatenator() {
    +        entity.enrichers().add(Enrichers.builder()
    +                .reducing(Reducer.class, ImmutableList.<AttributeSensor<?>>of(STR1, STR2))
    +                .from(entity)
    +                .computing(new Concatenator())
    +                .publishing(STR3)
    +                .build()
    +        );
    +
    +        EntityTestUtils.assertAttributeEquals(entity, STR3, null);
    +        
    +        entity.sensors().set(STR1, "foo");
    +        EntityTestUtils.assertAttributeEqualsContinually(entity, STR3, null);
    +
    +        entity.sensors().set(STR2, "bar");
    +        EntityTestUtils.assertAttributeEqualsEventually(entity, STR3, "foobar");
    +    }
    +    
    +    @Test
    +    public void testReducingBuilderWithLengthCalculator() {
    +        entity.enrichers().add(Enrichers.builder()
    +                .reducing(Reducer.class, ImmutableList.<AttributeSensor<?>>of(STR1, STR2))
    +                .from(entity)
    +                .computing(new LengthCalculator())
    +                .publishing(INT1)
    +                .build()
    +        );
    +
    +        EntityTestUtils.assertAttributeEquals(entity, INT1, null);
    +        
    +        entity.sensors().set(STR1, "foo");
    +        EntityTestUtils.assertAttributeEqualsEventually(entity, INT1, 3);
    +
    +        entity.sensors().set(STR2, "bar");
    +        EntityTestUtils.assertAttributeEqualsEventually(entity, INT1, 6);
    +    }
    +    
    +    @Test
    +    public void testReducingBuilderWithJoinerFunction() {
    +        entity.enrichers().add(Enrichers.builder()
    +                .reducing(Reducer.class, ImmutableList.<AttributeSensor<?>>of(STR1, STR2))
    +                .from(entity)
    +                .computing("joiner", ImmutableMap.<String, Object>of("separator", "-"))
    +                .publishing(STR3)
    +                .build()
    +        );
    +
    +        EntityTestUtils.assertAttributeEquals(entity, STR3, null);
    +        
    +        entity.sensors().set(STR1, "foo");
    +        EntityTestUtils.assertAttributeEqualsEventually(entity, STR3, "foo-null");
    +
    +        entity.sensors().set(STR2, "bar");
    +        EntityTestUtils.assertAttributeEqualsEventually(entity, STR3, "foo-bar");
    +    }
    +    
    +    @Test
    +    public void testReducingBuilderWithJoinerFunctionWithDefaultParameter() {
    +        entity.enrichers().add(Enrichers.builder()
    +            .reducing(Reducer.class, ImmutableList.<AttributeSensor<?>>of(STR1, STR2))
    +            .from(entity)
    +            .computing("joiner")
    +            .publishing(STR3)
    +            .build()
    +        );
    +        EntityTestUtils.assertAttributeEquals(entity, STR3, null);
    +        
    +        entity.sensors().set(STR1, "foo");
    +        EntityTestUtils.assertAttributeEqualsEventually(entity, STR3, "foo, null");
    +
    +        entity.sensors().set(STR2, "bar");
    +        EntityTestUtils.assertAttributeEqualsEventually(entity, STR3, "foo, bar");
    +    }
    +    
    +    @Test
    +    public void testReducingBuilderWithJoinerFunctionAndUnusedParameter() {
    +        
    +        entity.enrichers().add(Enrichers.builder()
    +            .reducing(Reducer.class, ImmutableList.<AttributeSensor<?>>of(STR1, STR2))
    +            .from(entity)
    +            .computing("joiner", ImmutableMap.<String, Object>of("non.existent.parameter", "-"))
    +            .publishing(STR3)
    +            .build()
    +        );
    +        EntityTestUtils.assertAttributeEquals(entity, STR3, null);
    +        
    +        entity.sensors().set(STR1, "foo");
    +        EntityTestUtils.assertAttributeEqualsEventually(entity, STR3, "foo, null");
    +
    +        entity.sensors().set(STR2, "bar");
    +        EntityTestUtils.assertAttributeEqualsEventually(entity, STR3, "foo, bar");
    +    }
    +    
    +    @Test
    +    public void testReducingBuilderWithFormatStringFunction() {
    +        entity.enrichers().add(Enrichers.builder()
    +            .reducing(Reducer.class, ImmutableList.<AttributeSensor<?>>of(STR1, STR2))
    +            .from(entity)
    +            .computing("formatString", ImmutableMap.<String, Object>of("format", "hello, %s and %s"))
    +            .publishing(STR3)
    +            .build()
    +        );
    +        
    +        EntityTestUtils.assertAttributeEquals(entity, STR3, null);
    +        
    +        entity.sensors().set(STR1, "foo");
    +        EntityTestUtils.assertAttributeEqualsEventually(entity, STR3, "hello, foo and null");
    +
    +        entity.sensors().set(STR2, "bar");
    +        EntityTestUtils.assertAttributeEqualsEventually(entity, STR3, "hello, foo and bar");
    +    }
    +    
    +    @Test
    +    public void testReducingBuilderWithNamedNonExistentFunction() {
    +        try { 
    +            entity.enrichers().add(Enrichers.builder()
    +                .reducing(Reducer.class, ImmutableList.<AttributeSensor<?>>of(STR1, STR2))
    +                .from(entity)
    +                .computing("unknown function name", ImmutableMap.<String, Object>of("separator", "-"))
    +                .publishing(STR3)
    +                .build()
    +            );
    +            Asserts.fail("Expected exception when adding reducing enricher with unknown named function");
    +        } catch (Exception e) {
    +            Throwable t = Exceptions.getFirstThrowableOfType(e, IllegalStateException.class);
    --- End diff --
    
    I much prefer:
    
        if (Exceptions.getFirstThrowableOfType(e, IllegalStateException.class) == null) {
            throw e;
        }
    
    Otherwise we lose the actual exception. This is normally ok, but it's a real pain if a test fails non-deterministically in the asfbot with no information about what went wrong.


---
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: Allow sensors to be aggregated us...

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

    https://github.com/apache/incubator-brooklyn/pull/919#discussion_r41144182
  
    --- Diff: core/src/test/java/org/apache/brooklyn/enricher/stock/reducer/ReducerTest.java ---
    @@ -0,0 +1,255 @@
    +/*
    + * 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 org.apache.brooklyn.enricher.stock.reducer;
    +
    +import java.util.List;
    +import java.util.Map;
    +
    +import javax.annotation.Nullable;
    +
    +import org.apache.brooklyn.api.entity.EntitySpec;
    +import org.apache.brooklyn.api.sensor.AttributeSensor;
    +import org.apache.brooklyn.api.sensor.EnricherSpec;
    +import org.apache.brooklyn.core.sensor.Sensors;
    +import org.apache.brooklyn.core.test.BrooklynAppUnitTestSupport;
    +import org.apache.brooklyn.core.test.entity.TestEntity;
    +import org.apache.brooklyn.enricher.stock.Enrichers;
    +import org.apache.brooklyn.enricher.stock.reducer.Reducer;
    +import org.apache.brooklyn.enricher.stock.reducer.StringStringReducer;
    +import org.apache.brooklyn.test.Asserts;
    +import org.apache.brooklyn.test.EntityTestUtils;
    +import org.apache.brooklyn.util.collections.MutableMap;
    +import org.apache.brooklyn.util.exceptions.Exceptions;
    +import org.testng.Assert;
    +import org.testng.annotations.BeforeMethod;
    +import org.testng.annotations.Test;
    +
    +import com.google.common.base.Function;
    +import com.google.common.collect.ImmutableList;
    +import com.google.common.collect.ImmutableMap;
    +
    +public class ReducerTest extends BrooklynAppUnitTestSupport {
    +
    +    public static final AttributeSensor<String> STR1 = Sensors.newStringSensor("test.str1");
    +    public static final AttributeSensor<String> STR2 = Sensors.newStringSensor("test.str2");
    +    public static final AttributeSensor<String> STR3 = Sensors.newStringSensor("test.str3");
    +    public static final AttributeSensor<Integer> INT1 = Sensors.newIntegerSensor("test.int1");
    +
    +    private TestEntity entity;
    +
    +    @BeforeMethod(alwaysRun=true)
    +    @Override
    +    public void setUp() throws Exception {
    +        super.setUp();
    +        entity = app.createAndManageChild(EntitySpec.create(TestEntity.class));
    +    }
    +
    +    @Test
    +    public void testBasicReducer(){
    +        entity.addEnricher(EnricherSpec.create(StringStringReducer.class).configure(
    +                MutableMap.of(
    +                Reducer.SOURCE_SENSORS, ImmutableList.of(STR1, STR2),
    +                Reducer.PRODUCER, entity,
    +                Reducer.TARGET_SENSOR, STR3,
    +                Reducer.REDUCER_FUNCTION, new Concatenator())
    +            )
    +        );
    +
    +        EntityTestUtils.assertAttributeEquals(entity, STR3, null);
    +        
    +        entity.sensors().set(STR1, "foo");
    +        EntityTestUtils.assertAttributeEqualsContinually(entity, STR3, null);
    +
    +        entity.sensors().set(STR2, "bar");
    +        EntityTestUtils.assertAttributeEqualsEventually(entity, STR3, "foobar");
    +    }
    +
    +    @Test
    +    public void testReducingBuilderWithConcatenator() {
    +        entity.addEnricher(Enrichers.builder()
    +                .reducing(StringStringReducer.class, ImmutableList.of(STR1, STR2))
    +                .from(entity)
    +                .computing(new Concatenator())
    +                .publishing(STR3)
    +                .build()
    +        );
    +
    +        EntityTestUtils.assertAttributeEquals(entity, STR3, null);
    +        
    +        entity.sensors().set(STR1, "foo");
    +        EntityTestUtils.assertAttributeEqualsContinually(entity, STR3, null);
    +
    +        entity.sensors().set(STR2, "bar");
    +        EntityTestUtils.assertAttributeEqualsEventually(entity, STR3, "foobar");
    +    }
    +    
    +    @Test
    +    public void testReducingBuilderWithLengthCalculator() {
    +        entity.addEnricher(Enrichers.builder()
    +                .reducing(StringIntegerReducer.class, ImmutableList.of(STR1, STR2))
    +                .from(entity)
    +                .computing(new LengthCalculator())
    +                .publishing(INT1)
    +                .build()
    +        );
    +
    +        EntityTestUtils.assertAttributeEquals(entity, INT1, null);
    +        
    +        entity.sensors().set(STR1, "foo");
    +        EntityTestUtils.assertAttributeEqualsContinually(entity, INT1, null);
    +
    +        entity.sensors().set(STR2, "bar");
    +        EntityTestUtils.assertAttributeEqualsEventually(entity, INT1, 6);
    +    }
    +    
    +    @Test
    +    public void testReducingBuilderWithJoinerFunction() {
    +        entity.addEnricher(Enrichers.builder()
    +                .reducing(StringStringReducer.class, ImmutableList.of(STR1, STR2))
    +                .from(entity)
    +                .computing("joiner", ImmutableMap.<String, Object>of("separator", "-"))
    +                .publishing(STR3)
    +                .build()
    +        );
    +
    +        EntityTestUtils.assertAttributeEquals(entity, STR3, null);
    +        
    +        entity.sensors().set(STR1, "foo");
    +        EntityTestUtils.assertAttributeEqualsContinually(entity, STR3, null);
    +
    +        entity.sensors().set(STR2, "bar");
    +        EntityTestUtils.assertAttributeEqualsEventually(entity, STR3, "foo-bar");
    +    }
    +    
    +    @Test
    +    public void testReducingBuilderWithJoinerFunctionWithDefaultParameter() {
    +        entity.addEnricher(Enrichers.builder()
    +            .reducing(StringStringReducer.class, ImmutableList.of(STR1, STR2))
    +            .from(entity)
    +            .computing("joiner")
    +            .publishing(STR3)
    +            .build()
    +        );
    +        EntityTestUtils.assertAttributeEquals(entity, STR3, null);
    +        
    +        entity.sensors().set(STR1, "foo");
    +        EntityTestUtils.assertAttributeEqualsContinually(entity, STR3, null);
    +
    +        entity.sensors().set(STR2, "bar");
    +        EntityTestUtils.assertAttributeEqualsEventually(entity, STR3, "foo, bar");
    +    }
    +    
    +    @Test
    +    public void testReducingBuilderWithJoinerFunctionAndUnusedParameter() {
    +        
    +        entity.addEnricher(Enrichers.builder()
    +            .reducing(StringStringReducer.class, ImmutableList.of(STR1, STR2))
    +            .from(entity)
    +            .computing("joiner", ImmutableMap.<String, Object>of("non.existent.parameter", "-"))
    +            .publishing(STR3)
    +            .build()
    +        );
    +        EntityTestUtils.assertAttributeEquals(entity, STR3, null);
    +        
    +        entity.sensors().set(STR1, "foo");
    +        EntityTestUtils.assertAttributeEqualsContinually(entity, STR3, null);
    +
    +        entity.sensors().set(STR2, "bar");
    +        EntityTestUtils.assertAttributeEqualsEventually(entity, STR3, "foo, bar");
    +    }
    +    
    +    @Test
    +    public void testReducingBuilderWithFormatStringFunction() {
    +        
    +        entity.addEnricher(Enrichers.builder()
    +            .reducing(StringStringReducer.class, ImmutableList.of(STR1, STR2))
    +            .from(entity)
    +            .computing("formatString", ImmutableMap.<String, Object>of("format", "hello, %s and %s"))
    +            .publishing(STR3)
    +            .build()
    +        );
    +        EntityTestUtils.assertAttributeEquals(entity, STR3, null);
    +        
    +        entity.sensors().set(STR1, "foo");
    +        EntityTestUtils.assertAttributeEqualsContinually(entity, STR3, null);
    +
    +        entity.sensors().set(STR2, "bar");
    +        EntityTestUtils.assertAttributeEqualsEventually(entity, STR3, "hello, foo and bar");
    +    }
    +    
    +    @Test
    +    public void testReducingBuilderWithNamedNonExistentFunction() {
    +        try { 
    +            entity.addEnricher(Enrichers.builder()
    +                .reducing(StringStringReducer.class, ImmutableList.of(STR1, STR2))
    +                .from(entity)
    +                .computing("unknown function name", ImmutableMap.<String, Object>of("separator", "-"))
    +                .publishing(STR3)
    +                .build()
    +            );
    +            Asserts.fail("Expected exception when adding reducing enricher with unknown named function");
    +        } catch (Exception e) {
    +            Throwable t = Exceptions.getFirstThrowableOfType(e, IllegalStateException.class);
    +            Assert.assertNotNull(t);
    +        }
    +    }
    +    
    +    private static class Concatenator implements Function<List<String>, String> {
    +        @Nullable
    +        @Override
    +        public String apply(List<String> values) {
    +            StringBuilder result = new StringBuilder();
    +            for (String value : values) {
    +                if (value == null) {
    +                    return null;
    +                } else {
    +                    result.append(value);
    +                }
    +            }
    +            return result.toString();
    +        }
    +    }
    +    
    +    public static class StringIntegerReducer extends Reducer<String, Integer> {
    +        
    +        public StringIntegerReducer() {}
    +
    +        @Override
    +        protected Function<List<String>, Integer> createReducerFunction(
    --- End diff --
    
    Have this as the default implementation in `Reducer`?


---
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: Allow sensors to be aggregated us...

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/919#discussion_r40344616
  
    --- Diff: core/src/main/java/org/apache/brooklyn/enricher/stock/reducer/Reducer.java ---
    @@ -0,0 +1,181 @@
    +/*
    + * 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 org.apache.brooklyn.enricher.stock.reducer;
    +
    +import java.util.Iterator;
    +import java.util.List;
    +import java.util.Map;
    +
    +import org.apache.brooklyn.api.entity.Entity;
    +import org.apache.brooklyn.api.entity.EntityLocal;
    +import org.apache.brooklyn.api.sensor.AttributeSensor;
    +import org.apache.brooklyn.api.sensor.Sensor;
    +import org.apache.brooklyn.api.sensor.SensorEvent;
    +import org.apache.brooklyn.api.sensor.SensorEventListener;
    +import org.apache.brooklyn.config.ConfigKey;
    +import org.apache.brooklyn.core.config.ConfigKeys;
    +import org.apache.brooklyn.core.enricher.AbstractEnricher;
    +import org.apache.brooklyn.util.core.flags.SetFromFlag;
    +import org.apache.brooklyn.util.core.task.Tasks;
    +import org.apache.brooklyn.util.core.task.ValueResolver;
    +import org.slf4j.Logger;
    +import org.slf4j.LoggerFactory;
    +
    +import com.google.api.client.util.Lists;
    +import com.google.common.base.Function;
    +import com.google.common.base.Preconditions;
    +import com.google.common.collect.ImmutableList;
    +import com.google.common.reflect.TypeToken;
    +
    +@SuppressWarnings("serial")
    +public abstract class Reducer<S, T> extends AbstractEnricher implements SensorEventListener<Object> {
    +
    +    private static final Logger LOG = LoggerFactory.getLogger(Reducer.class);
    +
    +    @SetFromFlag("producer")
    +    public static ConfigKey<Entity> PRODUCER = ConfigKeys.newConfigKey(Entity.class, "enricher.producer");
    +    public static ConfigKey<Sensor<?>> TARGET_SENSOR = ConfigKeys.newConfigKey(new TypeToken<Sensor<?>>() {}, "enricher.targetSensor");
    +    public static ConfigKey<List<? extends AttributeSensor<?>>> SOURCE_SENSORS = ConfigKeys.newConfigKey(new TypeToken<List<? extends AttributeSensor<?>>>() {}, "enricher.sourceSensors");
    +    public static ConfigKey<Function<List<?>,?>> REDUCER_FUNCTION = ConfigKeys.newConfigKey(new TypeToken<Function<List<?>, ?>>() {}, "enricher.reducerFunction");
    +    @SetFromFlag("transformation")
    +    public static final ConfigKey<String> REDUCER_FUNCTION_UNTYPED = ConfigKeys.newStringConfigKey("enricher.reducerFunction.untyped",
    --- End diff --
    
    I understand why it's called "untyped" in the context of the code, but is there possibly a more user-friendly name for this?


---
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: Allow sensors to be aggregated us...

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

    https://github.com/apache/incubator-brooklyn/pull/919#discussion_r41166663
  
    --- Diff: core/src/main/java/org/apache/brooklyn/enricher/stock/reducer/StringStringReducer.java ---
    @@ -0,0 +1,42 @@
    +/*
    + * 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 org.apache.brooklyn.enricher.stock.reducer;
    +
    +import java.util.List;
    +import java.util.Map;
    +import java.util.Objects;
    +
    +import com.google.common.base.Function;
    +
    +public class StringStringReducer extends GenericStringReducer<String> {
    +    
    +    public StringStringReducer() {}
    +
    +    @Override
    +    protected Function<List<String>, String> createReducerFunction(
    +            String reducerName, Map<String, ?> parameters) {
    +        Function<List<String>, String> function = super.createReducerFunction(reducerName, parameters);
    +        if(function != null) return function;
    +        
    +        if(Objects.equals(reducerName, "joiner")){
    --- End diff --
    
    This feels like a strange place to define the names of functions that we'll accept.
    
    I presume these conveniences are for yaml (as in Java one would just use `StringFunctions.joiner()` directly)?
    
    Should we be adding support for different functions to https://github.com/nakomis/incubator-brooklyn/blob/master/usage/camp/src/main/java/org/apache/brooklyn/camp/brooklyn/spi/dsl/methods/BrooklynDslCommon.java ? As is done in https://github.com/apache/incubator-brooklyn/pull/910/files#diff-d108c16ec590974e317590c54f71e9da


---
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: Allow sensors to be aggregated us...

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

    https://github.com/apache/incubator-brooklyn/pull/919#issuecomment-146790289
  
    Thanks @robertgmoss - looks really good. Only some extremely minor comments. Happy to either merge now or you can take a look at those and then I'll merge.


---
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: Allow sensors to be aggregated us...

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

    https://github.com/apache/incubator-brooklyn/pull/919#discussion_r41165610
  
    --- Diff: core/src/main/java/org/apache/brooklyn/enricher/stock/reducer/Reducer.java ---
    @@ -0,0 +1,187 @@
    +/*
    + * 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 org.apache.brooklyn.enricher.stock.reducer;
    +
    +import java.util.Iterator;
    +import java.util.List;
    +import java.util.Map;
    +
    +import org.apache.brooklyn.api.entity.Entity;
    +import org.apache.brooklyn.api.entity.EntityLocal;
    +import org.apache.brooklyn.api.sensor.AttributeSensor;
    +import org.apache.brooklyn.api.sensor.Sensor;
    +import org.apache.brooklyn.api.sensor.SensorEvent;
    +import org.apache.brooklyn.api.sensor.SensorEventListener;
    +import org.apache.brooklyn.config.ConfigKey;
    +import org.apache.brooklyn.core.config.ConfigKeys;
    +import org.apache.brooklyn.core.enricher.AbstractEnricher;
    +import org.apache.brooklyn.util.core.flags.SetFromFlag;
    +import org.apache.brooklyn.util.core.sensor.SensorPredicates;
    +import org.apache.brooklyn.util.core.task.Tasks;
    +import org.apache.brooklyn.util.core.task.ValueResolver;
    +import org.slf4j.Logger;
    +import org.slf4j.LoggerFactory;
    +
    +import com.google.api.client.util.Lists;
    +import com.google.common.base.Function;
    +import com.google.common.base.Optional;
    +import com.google.common.base.Preconditions;
    +import com.google.common.collect.ImmutableList;
    +import com.google.common.collect.Iterables;
    +import com.google.common.reflect.TypeToken;
    +
    +@SuppressWarnings("serial")
    +public abstract class Reducer<S, T> extends AbstractEnricher implements SensorEventListener<Object> {
    +
    +    private static final Logger LOG = LoggerFactory.getLogger(Reducer.class);
    +
    +    @SetFromFlag("producer")
    +    public static ConfigKey<Entity> PRODUCER = ConfigKeys.newConfigKey(Entity.class, "enricher.producer");
    +    public static ConfigKey<Sensor<?>> TARGET_SENSOR = ConfigKeys.newConfigKey(new TypeToken<Sensor<?>>() {}, "enricher.targetSensor");
    +    public static ConfigKey<List<? extends AttributeSensor<?>>> SOURCE_SENSORS = ConfigKeys.newConfigKey(new TypeToken<List<? extends AttributeSensor<?>>>() {}, "enricher.sourceSensors");
    +    public static ConfigKey<Function<List<?>,?>> REDUCER_FUNCTION = ConfigKeys.newConfigKey(new TypeToken<Function<List<?>, ?>>() {}, "enricher.reducerFunction");
    +    @SetFromFlag("transformation")
    +    public static final ConfigKey<String> REDUCER_FUNCTION_TRANSFORMATION = ConfigKeys.newStringConfigKey("enricher.reducerFunction.transformation",
    +        "A string matching a pre-defined named reducer function, such as joiner");
    +    public static final ConfigKey<Map<String, Object>> PARAMETERS = ConfigKeys.newConfigKey(new TypeToken<Map<String, Object>>() {}, "enricher.reducerFunction.parameters", 
    +        "A map of parameters to pass into the reducer function");
    +   
    +    protected Entity producer;
    +    protected List<AttributeSensor<S>> subscribedSensors;
    +    protected Sensor<T> targetSensor;
    +    protected Function<List<S>, T> reducerFunction;
    +
    +    @SuppressWarnings({ "unchecked", "rawtypes" })
    +    @Override
    +    public void setEntity(EntityLocal entity) {
    +        super.setEntity(entity);
    +        Preconditions.checkNotNull(getConfig(SOURCE_SENSORS), "source sensors");
    +
    +        this.producer = getConfig(PRODUCER) == null ? entity : getConfig(PRODUCER);
    +        List<AttributeSensor<S>> sensorListTemp = Lists.newArrayList();
    +
    +        for (Object sensorO : getConfig(SOURCE_SENSORS)) {
    +            AttributeSensor<S> sensor = Tasks.resolving(sensorO).as(AttributeSensor.class).timeout(ValueResolver.REAL_QUICK_WAIT).context(producer).get();
    +            Optional<? extends Sensor<?>> foundSensor = Iterables.tryFind(sensorListTemp, 
    +                    SensorPredicates.sensorNameEqualTo(sensor.getName()));
    +            
    +            if(!foundSensor.isPresent()) {
    +                sensorListTemp.add(sensor);
    +            }
    +        }
    +        
    +        String reducerName = config().get(REDUCER_FUNCTION_TRANSFORMATION);
    +        Function<List<S>, T> reducerFunction = (Function) config().get(REDUCER_FUNCTION);
    +        if(reducerFunction == null){
    +            Map<String, ?> parameters = config().get(PARAMETERS);
    +            reducerFunction = createReducerFunction(reducerName, parameters);
    +        }
    +
    +        this.reducerFunction = reducerFunction;
    +        Preconditions.checkState(sensorListTemp.size() > 0, "Nothing to reduce");
    +
    +        for (Sensor<S> sensor : sensorListTemp) {
    +            subscribe(producer, sensor, this);
    +        }
    +
    +        subscribedSensors = ImmutableList.copyOf(sensorListTemp);
    +    }
    +
    +    protected abstract Function<List<S>, T> createReducerFunction(String reducerName, Map<String, ?> parameters);
    +    
    +    @SuppressWarnings("unchecked")
    +    @Override
    +    public void onEvent(SensorEvent<Object> event) {
    +        Sensor<T> destinationSensor = (Sensor<T>) getConfig(TARGET_SENSOR);
    +
    +        List<S> values = Lists.newArrayList();
    +
    +        for (AttributeSensor<S> sourceSensor : subscribedSensors) {
    +            S resolvedSensorValue = entity.sensors().get(sourceSensor);
    +            if (resolvedSensorValue == null) {
    +                // only apply function if all values are resolved
    --- End diff --
    
    Is this always the behaviour we want - to not call the function if any of the values are null? My gut feel is to leave that up to the function (it can filter nulls if it wants).
    
    Doing it this way could lead to strange behaviour - e.g. sensor X and Y get set to "a" and "b", then X gets set to `null`. The function will not be notified about the change of X.
    
    I don't have any particular use-cases in mind where we'd want to know about the null - it's just a gut feel that leaving it up to the function gives more flexibility.


---
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: Allow sensors to be aggregated us...

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

    https://github.com/apache/incubator-brooklyn/pull/919#issuecomment-142991526
  
    LGTM -- tests pass and only minor comments


---
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: Allow sensors to be aggregated us...

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

    https://github.com/apache/incubator-brooklyn/pull/919#discussion_r41167369
  
    --- Diff: core/src/main/java/org/apache/brooklyn/enricher/stock/reducer/Reducer.java ---
    @@ -0,0 +1,187 @@
    +/*
    + * 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 org.apache.brooklyn.enricher.stock.reducer;
    +
    +import java.util.Iterator;
    +import java.util.List;
    +import java.util.Map;
    +
    +import org.apache.brooklyn.api.entity.Entity;
    +import org.apache.brooklyn.api.entity.EntityLocal;
    +import org.apache.brooklyn.api.sensor.AttributeSensor;
    +import org.apache.brooklyn.api.sensor.Sensor;
    +import org.apache.brooklyn.api.sensor.SensorEvent;
    +import org.apache.brooklyn.api.sensor.SensorEventListener;
    +import org.apache.brooklyn.config.ConfigKey;
    +import org.apache.brooklyn.core.config.ConfigKeys;
    +import org.apache.brooklyn.core.enricher.AbstractEnricher;
    +import org.apache.brooklyn.util.core.flags.SetFromFlag;
    +import org.apache.brooklyn.util.core.sensor.SensorPredicates;
    +import org.apache.brooklyn.util.core.task.Tasks;
    +import org.apache.brooklyn.util.core.task.ValueResolver;
    +import org.slf4j.Logger;
    +import org.slf4j.LoggerFactory;
    +
    +import com.google.api.client.util.Lists;
    +import com.google.common.base.Function;
    +import com.google.common.base.Optional;
    +import com.google.common.base.Preconditions;
    +import com.google.common.collect.ImmutableList;
    +import com.google.common.collect.Iterables;
    +import com.google.common.reflect.TypeToken;
    +
    +@SuppressWarnings("serial")
    +public abstract class Reducer<S, T> extends AbstractEnricher implements SensorEventListener<Object> {
    +
    +    private static final Logger LOG = LoggerFactory.getLogger(Reducer.class);
    +
    +    @SetFromFlag("producer")
    +    public static ConfigKey<Entity> PRODUCER = ConfigKeys.newConfigKey(Entity.class, "enricher.producer");
    +    public static ConfigKey<Sensor<?>> TARGET_SENSOR = ConfigKeys.newConfigKey(new TypeToken<Sensor<?>>() {}, "enricher.targetSensor");
    +    public static ConfigKey<List<? extends AttributeSensor<?>>> SOURCE_SENSORS = ConfigKeys.newConfigKey(new TypeToken<List<? extends AttributeSensor<?>>>() {}, "enricher.sourceSensors");
    +    public static ConfigKey<Function<List<?>,?>> REDUCER_FUNCTION = ConfigKeys.newConfigKey(new TypeToken<Function<List<?>, ?>>() {}, "enricher.reducerFunction");
    +    @SetFromFlag("transformation")
    +    public static final ConfigKey<String> REDUCER_FUNCTION_TRANSFORMATION = ConfigKeys.newStringConfigKey("enricher.reducerFunction.transformation",
    +        "A string matching a pre-defined named reducer function, such as joiner");
    +    public static final ConfigKey<Map<String, Object>> PARAMETERS = ConfigKeys.newConfigKey(new TypeToken<Map<String, Object>>() {}, "enricher.reducerFunction.parameters", 
    +        "A map of parameters to pass into the reducer function");
    +   
    +    protected Entity producer;
    +    protected List<AttributeSensor<S>> subscribedSensors;
    +    protected Sensor<T> targetSensor;
    +    protected Function<List<S>, T> reducerFunction;
    +
    +    @SuppressWarnings({ "unchecked", "rawtypes" })
    +    @Override
    +    public void setEntity(EntityLocal entity) {
    +        super.setEntity(entity);
    +        Preconditions.checkNotNull(getConfig(SOURCE_SENSORS), "source sensors");
    +
    +        this.producer = getConfig(PRODUCER) == null ? entity : getConfig(PRODUCER);
    +        List<AttributeSensor<S>> sensorListTemp = Lists.newArrayList();
    +
    +        for (Object sensorO : getConfig(SOURCE_SENSORS)) {
    +            AttributeSensor<S> sensor = Tasks.resolving(sensorO).as(AttributeSensor.class).timeout(ValueResolver.REAL_QUICK_WAIT).context(producer).get();
    +            Optional<? extends Sensor<?>> foundSensor = Iterables.tryFind(sensorListTemp, 
    +                    SensorPredicates.sensorNameEqualTo(sensor.getName()));
    +            
    +            if(!foundSensor.isPresent()) {
    +                sensorListTemp.add(sensor);
    +            }
    +        }
    +        
    +        String reducerName = config().get(REDUCER_FUNCTION_TRANSFORMATION);
    +        Function<List<S>, T> reducerFunction = (Function) config().get(REDUCER_FUNCTION);
    +        if(reducerFunction == null){
    +            Map<String, ?> parameters = config().get(PARAMETERS);
    +            reducerFunction = createReducerFunction(reducerName, parameters);
    +        }
    +
    +        this.reducerFunction = reducerFunction;
    +        Preconditions.checkState(sensorListTemp.size() > 0, "Nothing to reduce");
    +
    +        for (Sensor<S> sensor : sensorListTemp) {
    +            subscribe(producer, sensor, this);
    +        }
    +
    +        subscribedSensors = ImmutableList.copyOf(sensorListTemp);
    +    }
    +
    +    protected abstract Function<List<S>, T> createReducerFunction(String reducerName, Map<String, ?> parameters);
    +    
    +    @SuppressWarnings("unchecked")
    +    @Override
    +    public void onEvent(SensorEvent<Object> event) {
    +        Sensor<T> destinationSensor = (Sensor<T>) getConfig(TARGET_SENSOR);
    +
    +        List<S> values = Lists.newArrayList();
    +
    +        for (AttributeSensor<S> sourceSensor : subscribedSensors) {
    +            S resolvedSensorValue = entity.sensors().get(sourceSensor);
    +            if (resolvedSensorValue == null) {
    +                // only apply function if all values are resolved
    +                return;
    +            }
    +
    +            values.add(resolvedSensorValue);
    +        }
    +
    +        Object result = reducerFunction.apply(values);
    +
    +        if (LOG.isTraceEnabled()) LOG.trace("enricher {} got {}, propagating via {} as {}",
    +                new Object[] {this, event, entity, reducerFunction, destinationSensor});
    +
    +        emit((Sensor<T>)destinationSensor, result);
    +    }
    +   
    +    public static class JoinerReducerFunction<A> implements Function<List<A>, String> {
    +        
    +        private Object separator;
    +
    +        public JoinerReducerFunction(Object separator) {
    +            this.separator = (separator == null) ? ", " : separator;
    +        }
    +
    +        @Override
    +        public String apply(List<A> input) {
    +            
    +            StringBuilder sb = new StringBuilder();
    +            Iterator<A> it = input.iterator();
    +            while(it.hasNext()) {
    +                sb.append(it.next().toString());
    +                if(it.hasNext()){
    +                    sb.append(separator);
    +                }
    +            }
    +            return sb.toString();
    +        }
    +        
    +    }
    +
    +    public static class JoinerFunction extends JoinerReducerFunction<String>{
    +        
    +        public JoinerFunction(Object separator) {
    +            super(separator);
    +        }
    +    }
    +
    +    public static class ToStringReducerFunction<A> implements Function<List<A>, String> {
    +
    +        @Override
    +        public String apply(List<A> input) {
    +            return input.toString();
    +        }
    +        
    +    }
    +    
    +    public static class FormatStringReducerFunction<T> implements Function<List<T>, String> {
    --- End diff --
    
    See `StringFunctions.formatterForArray` (might need a new variant for `Iterable<T>`).


---
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: Allow sensors to be aggregated us...

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/919#discussion_r40341440
  
    --- Diff: core/src/main/java/org/apache/brooklyn/enricher/stock/reducer/Reducer.java ---
    @@ -0,0 +1,181 @@
    +/*
    + * 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 org.apache.brooklyn.enricher.stock.reducer;
    +
    +import java.util.Iterator;
    +import java.util.List;
    +import java.util.Map;
    +
    +import org.apache.brooklyn.api.entity.Entity;
    +import org.apache.brooklyn.api.entity.EntityLocal;
    +import org.apache.brooklyn.api.sensor.AttributeSensor;
    +import org.apache.brooklyn.api.sensor.Sensor;
    +import org.apache.brooklyn.api.sensor.SensorEvent;
    +import org.apache.brooklyn.api.sensor.SensorEventListener;
    +import org.apache.brooklyn.config.ConfigKey;
    +import org.apache.brooklyn.core.config.ConfigKeys;
    +import org.apache.brooklyn.core.enricher.AbstractEnricher;
    +import org.apache.brooklyn.util.core.flags.SetFromFlag;
    +import org.apache.brooklyn.util.core.task.Tasks;
    +import org.apache.brooklyn.util.core.task.ValueResolver;
    +import org.slf4j.Logger;
    +import org.slf4j.LoggerFactory;
    +
    +import com.google.api.client.util.Lists;
    +import com.google.common.base.Function;
    +import com.google.common.base.Preconditions;
    +import com.google.common.collect.ImmutableList;
    +import com.google.common.reflect.TypeToken;
    +
    +@SuppressWarnings("serial")
    +public abstract class Reducer<S, T> extends AbstractEnricher implements SensorEventListener<Object> {
    +
    +    private static final Logger LOG = LoggerFactory.getLogger(Reducer.class);
    +
    +    @SetFromFlag("producer")
    +    public static ConfigKey<Entity> PRODUCER = ConfigKeys.newConfigKey(Entity.class, "enricher.producer");
    +    public static ConfigKey<Sensor<?>> TARGET_SENSOR = ConfigKeys.newConfigKey(new TypeToken<Sensor<?>>() {}, "enricher.targetSensor");
    +    public static ConfigKey<List<? extends AttributeSensor<?>>> SOURCE_SENSORS = ConfigKeys.newConfigKey(new TypeToken<List<? extends AttributeSensor<?>>>() {}, "enricher.sourceSensors");
    +    public static ConfigKey<Function<List<?>,?>> REDUCER_FUNCTION = ConfigKeys.newConfigKey(new TypeToken<Function<List<?>, ?>>() {}, "enricher.reducerFunction");
    +    @SetFromFlag("transformation")
    +    public static final ConfigKey<String> REDUCER_FUNCTION_UNTYPED = ConfigKeys.newStringConfigKey("enricher.reducerFunction.untyped",
    +        "A string matching a pre-defined named reducer function, such as join");
    +    public static final ConfigKey<Map<String, Object>> PARAMETERS = ConfigKeys.newConfigKey(new TypeToken<Map<String, Object>>() {}, "enricher.reducerFunction.parameters", 
    +        "A map of parameters to pass into the reducer function");
    +   
    +    protected Entity producer;
    +    protected List<AttributeSensor<S>> subscribedSensors;
    +    protected Sensor<T> targetSensor;
    +    protected Function<List<S>, T> reducerFunction;
    +
    +    @SuppressWarnings({ "unchecked", "rawtypes" })
    +    @Override
    +    public void setEntity(EntityLocal entity) {
    +        super.setEntity(entity);
    +        Preconditions.checkNotNull(getConfig(SOURCE_SENSORS), "source sensors");
    --- End diff --
    
    Same comment about error message


---
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: Allow sensors to be aggregated us...

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

    https://github.com/apache/incubator-brooklyn/pull/919#discussion_r41168854
  
    --- Diff: core/src/test/java/org/apache/brooklyn/enricher/stock/reducer/ReducerTest.java ---
    @@ -0,0 +1,255 @@
    +/*
    + * 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 org.apache.brooklyn.enricher.stock.reducer;
    +
    +import java.util.List;
    +import java.util.Map;
    +
    +import javax.annotation.Nullable;
    +
    +import org.apache.brooklyn.api.entity.EntitySpec;
    +import org.apache.brooklyn.api.sensor.AttributeSensor;
    +import org.apache.brooklyn.api.sensor.EnricherSpec;
    +import org.apache.brooklyn.core.sensor.Sensors;
    +import org.apache.brooklyn.core.test.BrooklynAppUnitTestSupport;
    +import org.apache.brooklyn.core.test.entity.TestEntity;
    +import org.apache.brooklyn.enricher.stock.Enrichers;
    +import org.apache.brooklyn.enricher.stock.reducer.Reducer;
    +import org.apache.brooklyn.enricher.stock.reducer.StringStringReducer;
    +import org.apache.brooklyn.test.Asserts;
    +import org.apache.brooklyn.test.EntityTestUtils;
    +import org.apache.brooklyn.util.collections.MutableMap;
    +import org.apache.brooklyn.util.exceptions.Exceptions;
    +import org.testng.Assert;
    +import org.testng.annotations.BeforeMethod;
    +import org.testng.annotations.Test;
    +
    +import com.google.common.base.Function;
    +import com.google.common.collect.ImmutableList;
    +import com.google.common.collect.ImmutableMap;
    +
    +public class ReducerTest extends BrooklynAppUnitTestSupport {
    +
    +    public static final AttributeSensor<String> STR1 = Sensors.newStringSensor("test.str1");
    +    public static final AttributeSensor<String> STR2 = Sensors.newStringSensor("test.str2");
    +    public static final AttributeSensor<String> STR3 = Sensors.newStringSensor("test.str3");
    +    public static final AttributeSensor<Integer> INT1 = Sensors.newIntegerSensor("test.int1");
    +
    +    private TestEntity entity;
    +
    +    @BeforeMethod(alwaysRun=true)
    +    @Override
    +    public void setUp() throws Exception {
    +        super.setUp();
    +        entity = app.createAndManageChild(EntitySpec.create(TestEntity.class));
    +    }
    +
    +    @Test
    +    public void testBasicReducer(){
    +        entity.addEnricher(EnricherSpec.create(StringStringReducer.class).configure(
    +                MutableMap.of(
    +                Reducer.SOURCE_SENSORS, ImmutableList.of(STR1, STR2),
    +                Reducer.PRODUCER, entity,
    +                Reducer.TARGET_SENSOR, STR3,
    +                Reducer.REDUCER_FUNCTION, new Concatenator())
    +            )
    +        );
    +
    +        EntityTestUtils.assertAttributeEquals(entity, STR3, null);
    +        
    +        entity.sensors().set(STR1, "foo");
    +        EntityTestUtils.assertAttributeEqualsContinually(entity, STR3, null);
    +
    +        entity.sensors().set(STR2, "bar");
    +        EntityTestUtils.assertAttributeEqualsEventually(entity, STR3, "foobar");
    +    }
    +
    +    @Test
    +    public void testReducingBuilderWithConcatenator() {
    +        entity.addEnricher(Enrichers.builder()
    +                .reducing(StringStringReducer.class, ImmutableList.of(STR1, STR2))
    +                .from(entity)
    +                .computing(new Concatenator())
    +                .publishing(STR3)
    +                .build()
    +        );
    +
    +        EntityTestUtils.assertAttributeEquals(entity, STR3, null);
    +        
    +        entity.sensors().set(STR1, "foo");
    +        EntityTestUtils.assertAttributeEqualsContinually(entity, STR3, null);
    +
    +        entity.sensors().set(STR2, "bar");
    +        EntityTestUtils.assertAttributeEqualsEventually(entity, STR3, "foobar");
    +    }
    +    
    +    @Test
    +    public void testReducingBuilderWithLengthCalculator() {
    +        entity.addEnricher(Enrichers.builder()
    +                .reducing(StringIntegerReducer.class, ImmutableList.of(STR1, STR2))
    +                .from(entity)
    +                .computing(new LengthCalculator())
    +                .publishing(INT1)
    +                .build()
    +        );
    +
    +        EntityTestUtils.assertAttributeEquals(entity, INT1, null);
    +        
    +        entity.sensors().set(STR1, "foo");
    +        EntityTestUtils.assertAttributeEqualsContinually(entity, INT1, null);
    +
    +        entity.sensors().set(STR2, "bar");
    +        EntityTestUtils.assertAttributeEqualsEventually(entity, INT1, 6);
    +    }
    +    
    +    @Test
    +    public void testReducingBuilderWithJoinerFunction() {
    +        entity.addEnricher(Enrichers.builder()
    +                .reducing(StringStringReducer.class, ImmutableList.of(STR1, STR2))
    +                .from(entity)
    +                .computing("joiner", ImmutableMap.<String, Object>of("separator", "-"))
    +                .publishing(STR3)
    +                .build()
    +        );
    +
    +        EntityTestUtils.assertAttributeEquals(entity, STR3, null);
    +        
    +        entity.sensors().set(STR1, "foo");
    +        EntityTestUtils.assertAttributeEqualsContinually(entity, STR3, null);
    +
    +        entity.sensors().set(STR2, "bar");
    +        EntityTestUtils.assertAttributeEqualsEventually(entity, STR3, "foo-bar");
    +    }
    +    
    +    @Test
    +    public void testReducingBuilderWithJoinerFunctionWithDefaultParameter() {
    +        entity.addEnricher(Enrichers.builder()
    +            .reducing(StringStringReducer.class, ImmutableList.of(STR1, STR2))
    +            .from(entity)
    +            .computing("joiner")
    +            .publishing(STR3)
    +            .build()
    +        );
    +        EntityTestUtils.assertAttributeEquals(entity, STR3, null);
    +        
    +        entity.sensors().set(STR1, "foo");
    +        EntityTestUtils.assertAttributeEqualsContinually(entity, STR3, null);
    +
    +        entity.sensors().set(STR2, "bar");
    +        EntityTestUtils.assertAttributeEqualsEventually(entity, STR3, "foo, bar");
    +    }
    +    
    +    @Test
    +    public void testReducingBuilderWithJoinerFunctionAndUnusedParameter() {
    +        
    +        entity.addEnricher(Enrichers.builder()
    +            .reducing(StringStringReducer.class, ImmutableList.of(STR1, STR2))
    +            .from(entity)
    +            .computing("joiner", ImmutableMap.<String, Object>of("non.existent.parameter", "-"))
    +            .publishing(STR3)
    +            .build()
    +        );
    +        EntityTestUtils.assertAttributeEquals(entity, STR3, null);
    +        
    +        entity.sensors().set(STR1, "foo");
    +        EntityTestUtils.assertAttributeEqualsContinually(entity, STR3, null);
    +
    +        entity.sensors().set(STR2, "bar");
    +        EntityTestUtils.assertAttributeEqualsEventually(entity, STR3, "foo, bar");
    +    }
    +    
    +    @Test
    +    public void testReducingBuilderWithFormatStringFunction() {
    +        
    +        entity.addEnricher(Enrichers.builder()
    +            .reducing(StringStringReducer.class, ImmutableList.of(STR1, STR2))
    +            .from(entity)
    +            .computing("formatString", ImmutableMap.<String, Object>of("format", "hello, %s and %s"))
    +            .publishing(STR3)
    +            .build()
    +        );
    +        EntityTestUtils.assertAttributeEquals(entity, STR3, null);
    +        
    +        entity.sensors().set(STR1, "foo");
    +        EntityTestUtils.assertAttributeEqualsContinually(entity, STR3, null);
    +
    +        entity.sensors().set(STR2, "bar");
    +        EntityTestUtils.assertAttributeEqualsEventually(entity, STR3, "hello, foo and bar");
    +    }
    +    
    +    @Test
    +    public void testReducingBuilderWithNamedNonExistentFunction() {
    +        try { 
    +            entity.addEnricher(Enrichers.builder()
    +                .reducing(StringStringReducer.class, ImmutableList.of(STR1, STR2))
    +                .from(entity)
    +                .computing("unknown function name", ImmutableMap.<String, Object>of("separator", "-"))
    +                .publishing(STR3)
    +                .build()
    +            );
    +            Asserts.fail("Expected exception when adding reducing enricher with unknown named function");
    +        } catch (Exception e) {
    +            Throwable t = Exceptions.getFirstThrowableOfType(e, IllegalStateException.class);
    +            Assert.assertNotNull(t);
    +        }
    +    }
    +    
    +    private static class Concatenator implements Function<List<String>, String> {
    +        @Nullable
    +        @Override
    +        public String apply(List<String> values) {
    +            StringBuilder result = new StringBuilder();
    +            for (String value : values) {
    +                if (value == null) {
    +                    return null;
    +                } else {
    +                    result.append(value);
    +                }
    +            }
    +            return result.toString();
    +        }
    +    }
    +    
    +    public static class StringIntegerReducer extends Reducer<String, Integer> {
    --- End diff --
    
    It's worrying that you're defining this in the test - that presumably means it's impossible to do it in yaml, because this class doesn't exist and there is no other way to do it other than writing the code yourself?


---
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.
---