<commit_before>/*
 * Copyright © 2015 <NAME>, 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.data2.registry;

import co.cask.cdap.api.dataset.DatasetProperties;
import co.cask.cdap.common.conf.Constants;
import co.cask.cdap.data2.datafabric.dataset.DatasetsUtil;
import co.cask.cdap.data2.dataset2.DatasetFramework;
import co.cask.cdap.data2.dataset2.tx.Transactional;
import co.cask.cdap.proto.Id;
import co.cask.tephra.TransactionExecutor;
import co.cask.tephra.TransactionExecutorFactory;
import com.google.common.base.Supplier;
import com.google.common.base.Throwables;
import com.google.common.collect.Iterators;
import com.google.inject.Inject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Collections;
import java.util.Iterator;
import java.util.Set;

/**
 * Store program/adapter -> dataset/stream usage information.
 *
 * TODO: Reduce duplication between this and {@link UsageDataset}.
 */
public class UsageRegistry {

  private static final Logger LOG = LoggerFactory.getLogger(UsageRegistry.class);

  private static final Id.DatasetInstance USAGE_INSTANCE_ID =
    Id.DatasetInstance.from(Constants.SYSTEM_NAMESPACE_ID, "usage.registry");

  private final Transactional<UsageDatasetIterable, UsageDataset> txnl;

  @Inject
  public UsageRegistry(TransactionExecutorFactory txExecutorFactory, final DatasetFramework datasetFramework) {
    txnl = Transactional.of(txExecutorFactory, new Supplier<UsageDatasetIterable>() {
      @Override
      public UsageDatasetIterable get() {
        try {
          UsageDataset usageDataset = DatasetsUtil.getOrCreateDataset(datasetFramework,
                                                                      USAGE_INSTANCE_ID,
                                                                      UsageDataset.class.getSimpleName(),
                                                                      DatasetProperties.EMPTY, null, null);
          return new UsageDatasetIterable(usageDataset);
        } catch (Exception e) {
          LOG.error("Failed to access usage table", e);
          throw Throwables.propagate(e);
        }
      }
    });
  }

  /**
   * Registers usage of a stream by multiple ids.
   *
   * @param users the users of the stream
   * @param streamId the stream
   */
  public void registerAll(final Iterable<? extends Id> users, final Id.Stream streamId) {
    txnl.executeUnchecked(new TransactionExecutor.Function<UsageDatasetIterable, Void>() {
      @Override
      public Void apply(UsageDatasetIterable input) throws Exception {
        for (Id user : users) {
          // TODO: CDAP-2251: remove redundancy
          if (user instanceof Id.Program) {
            register((Id.Program) user, streamId);
          } else if (user instanceof Id.Adapter) {
            register((Id.Adapter) user, streamId);
          }<commit_msg>(CDAP-2548) Make UsageDataset backward compatible for the type change.<commit_after>/*
 * Copyright © 2015 <NAME>, 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.data2.registry;

import co.cask.cdap.api.dataset.DatasetProperties;
import co.cask.cdap.api.dataset.table.Table;
import co.cask.cdap.common.conf.Constants;
import co.cask.cdap.data2.datafabric.dataset.DatasetsUtil;
import co.cask.cdap.data2.dataset2.DatasetFramework;
import co.cask.cdap.data2.dataset2.tx.Transactional;
import co.cask.cdap.proto.Id;
import co.cask.tephra.TransactionExecutor;
import co.cask.tephra.TransactionExecutorFactory;
import com.google.common.base.Supplier;
import com.google.common.base.Throwables;
import com.google.common.collect.Iterators;
import com.google.inject.Inject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Collections;
import java.util.Iterator;
import java.util.Set;

/**
 * Store program/adapter -> dataset/stream usage information.
 *
 * TODO: Reduce duplication between this and {@link UsageDataset}.
 */
public class UsageRegistry {

  private static final Logger LOG = LoggerFactory.getLogger(UsageRegistry.class);

  private static final Id.DatasetInstance USAGE_INSTANCE_ID =
    Id.DatasetInstance.from(Constants.SYSTEM_NAMESPACE_ID, "usage.registry");

  private final Transactional<UsageDatasetIterable, UsageDataset> txnl;

  @Inject
  public UsageRegistry(TransactionExecutorFactory txExecutorFactory, final DatasetFramework datasetFramework) {
    txnl = Transactional.of(txExecutorFactory, new Supplier<UsageDatasetIterable>() {
      @Override
      public UsageDatasetIterable get() {
        try {
          Object usageDataset = DatasetsUtil.getOrCreateDataset(datasetFramework, USAGE_INSTANCE_ID,
                                                                UsageDataset.class.getSimpleName(),
                                                                DatasetProperties.EMPTY, null, null);
          // Backward compatible check for version <= 3.0.0
          if (usageDataset instanceof UsageDataset) {
            return new UsageDatasetIterable((UsageDataset) usageDataset);
          }
          return new UsageDatasetIterable(new UsageDataset((Table) usageDataset));
        } catch (Exception e) {
          LOG.error("Failed to access usage table", e);
          throw Throwables.propagate(e);
        }
      }
    });
  }

  /**
   * Registers usage of a stream by multiple ids.
   *
   * @param users the users of the stream
   * @param streamId the stream
   */
  public void registerAll(final Iterable<? extends Id> users, final Id.Stream streamId) {
    txnl.executeUnchecked(new TransactionExecutor.Function<UsageDatasetIterable, Void>() {
      @Override
      public Void apply(UsageDatasetIterable input) throws Exception {
        for (Id user : users) {
          // TODO: CDAP-2251: remove redundancy
          if (user instanceof Id.Program) {
            register((Id.Program) user, streamId);
          } else if (user instanceof Id.Adapter) {
            register((Id.Adapter) user, streamId);
          }
{'fraction_non_alphanumeric': 0.08914839077185988, 'fraction_numerical': 0.006693249786385645, 'mean_word_length': 3.0338885697874787, 'pattern_counts': {'":': 0, '<': 14, '<?xml version=': 0, '>': 15, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 13, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '7323634', 'n_tokens_mistral': 1895, 'n_tokens_neox': 1889, 'n_words': 534}