All Downloads are FREE. Search and download functionalities are using the official Maven repository.

co.cask.cdap.dq.functions.DiscreteValuesHistogram Maven / Gradle / Ivy

There is a newer version: 3.5.0
Show newest version
/*
 * Copyright © 2015 Cask Data, Inc.
 *
 * Licensed 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 co.cask.cdap.dq.functions;

import co.cask.cdap.api.common.Bytes;
import co.cask.cdap.dq.DataQualityWritable;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.Map;

/**
 * Discrete Values Histogram Aggregation Function
 */
public class DiscreteValuesHistogram
  implements BasicAggregationFunction, CombinableAggregationFunction> {
  private static final Gson GSON = new Gson();
  private static final Type TOKEN_TYPE_MAP_STRING_INTEGER = new TypeToken>() { }.getType();
  private Map histogramMap = new HashMap<>();
  private Map aggregatedHistogramMap = new HashMap<>();

  @Override
  public void combine(byte[] value) {
    Map outputMap = deserialize(value);
    for (Map.Entry entry : outputMap.entrySet()) {
      Integer val = aggregatedHistogramMap.get(entry.getKey());
      aggregatedHistogramMap.put(entry.getKey(), val == null ? entry.getValue() : val + entry.getValue());
    }
  }

  @Override
  public Map deserialize(byte[] valueBytes) {
   return GSON.fromJson(Bytes.toString(valueBytes), TOKEN_TYPE_MAP_STRING_INTEGER);
  }

  @Override
  public Map retrieveAggregation() {
    return aggregatedHistogramMap.isEmpty() ? null : aggregatedHistogramMap;
  }

  @Override
  public void add(DataQualityWritable value) {
    Integer mapVal = histogramMap.get(value.get().toString());
    if (mapVal != null) {
      histogramMap.put(value.get().toString(), mapVal + 1);
    } else {
      histogramMap.put(value.get().toString(), 1);
    }
  }

  @Override
  public byte[] aggregate() {
    return Bytes.toBytes(GSON.toJson(histogramMap));
  }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy