<commit_before>/*
 * Copyright 2016 StreamSets Inc.
 *
 * Licensed under 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 com.streamsets.pipeline.lib.util;

import com.google.common.base.Optional;
import com.streamsets.pipeline.lib.data.DataFactory;
import io.confluent.kafka.schemaregistry.client.CachedSchemaRegistryClient;
import io.confluent.kafka.schemaregistry.client.SchemaMetadata;
import io.confluent.kafka.schemaregistry.client.SchemaRegistryClient;
import io.confluent.kafka.schemaregistry.client.rest.exceptions.RestClientException;
import org.apache.avro.Schema;

import java.io.IOException;
import java.io.OutputStream;
import java.nio.ByteBuffer;
import java.util.List;

import static org.apache.commons.lang.StringUtils.isEmpty;

/**
 *
 */
public class AvroSchemaHelper {
  public static final byte MAGIC_BYTE = 0x0;
  public static final byte MAGIC_BYTE_SIZE = 1;
  public static final int ID_SIZE = 4;

  private static final String KEY_PREFIX = "avro.";

  public static final String SCHEMA_SOURCE_KEY = KEY_PREFIX + "avroSchemaSource";

  public static final String SCHEMA_REPO_URLS_KEY = KEY_PREFIX + "schemaRegistryUrls";

  public static final String SUBJECT_KEY = KEY_PREFIX + "subject";
  public static final String SUBJECT_DEFAULT = "";

  public static final String SCHEMA_ID_KEY = KEY_PREFIX + "schemaId";
  public static final int SCHEMA_ID_DEFAULT = 0;

  public static final String SCHEMA_KEY = KEY_PREFIX + "schema";
  public static final String SCHEMA_DEFAULT = "";

  public static final String INCLUDE_SCHEMA_KEY = KEY_PREFIX + "includeSchema";
  public static final boolean INCLUDE_SCHEMA_DEFAULT = true;

  public static final String DEFAULT_VALUES_KEY = KEY_PREFIX + "defaultValues";

  public static final String COMPRESSION_CODEC_KEY = KEY_PREFIX + "compressionCodec";
  public static final String COMPRESSION_CODEC_DEFAULT = "null";

  private final SchemaRegistryClient registryClient;

  /**
   * AvroSchemaHelper constructor. DataFactory settings should be passed in for parsing.
   * @param settings DataFactory settings.
   */
  public AvroSchemaHelper(DataFactory.Settings settings) {
      final List<String> schemaRepoUrls = settings.getConfig(SCHEMA_REPO_URLS_KEY);

      if (!schemaRepoUrls.isEmpty()) {
        registryClient = new CachedSchemaRegistryClient(schemaRepoUrls, 1000);
      } else {
        registryClient = null;
      }
  }

  /**
   * Method to allow the caller to find out if this helper was configured with a schema registry or not.
   * @return true if a valid schema registry client is available.
   */
  public boolean hasRegistryClient() {
    return registryClient != null;
  }

  /**
   * Parses and returns an Avro schema loaded from the schema registry using the provided schema ID
   * if available, or the latest version of a schema for the specified subject.
   * @param subject optional schema subject (if schema ID is provided)
   * @param schemaId optional schema ID (if subject is provided)
   * @return parsed avro schema
   * @throws SchemaRegistryException if there is an error with the registry client
   */
  public Schema loadFromRegistry(String subject, int schemaId) throws SchemaRegistryException {
    try {
      if (isEmpty(subject)) {
        return loadFromRegistry(schemaId);
      } else {
        return loadFromRegistry(subject);
      }
    } catch (SchemaRegistryException e) {
      throw new SchemaRegistryException(e);
    }
  }

  /**
   * Parses an avro schema from a string instead of the schema registry.
   * @param schema JSON string representing an Avro schema
   * @return parsed avro schema
   */
  public Schema loadFromString(String schema) {
    return new Schema.Parser().setValidate(true).setValidateDefaults(true).parse(schema);
  }

  /**
   * Registers a parsed schema with the schema registry under the specified subject.
   * @param schema parsed avro schema
   * @param subject subject to register the schema under
   * @return schemaId if registration was successful
   * @throws SchemaRegistryException if there is an error with the registry client
   */
  public int registerSchema(Schema schema, String subject) throws SchemaRegistryException {
    try {
      return registryClient.register(subject, schema);
    } catch (IOException | RestClientException e) {
      throw new SchemaRegistryException(e);
    }
  }

  /**
   * Loads and parses a schema for the specified subject from the schema registry
   * @param subject subject for which to fetch the latest version of a schema.
   * @return parsed avro schema
   * @throws SchemaRegistryException if there is an error with the registry client
   */
  public Schema loadFromRegistry(String subject) throws SchemaRegistryException {
    try {
      SchemaMetadata metadata = registryClient.getLatestSchemaMetadata(subject);
      return registryClient.getByID(metadata.getId());
    } catch (IOException | RestClientException e) {<commit_msg>SDC-4183. Don't use setValidateDefaults method from avro as some stages may use old avro versions which does not contain this API.<commit_after>/*
 * Copyright 2016 StreamSets Inc.
 *
 * Licensed under 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 com.streamsets.pipeline.lib.util;

import com.google.common.base.Optional;
import com.streamsets.pipeline.lib.data.DataFactory;
import io.confluent.kafka.schemaregistry.client.CachedSchemaRegistryClient;
import io.confluent.kafka.schemaregistry.client.SchemaMetadata;
import io.confluent.kafka.schemaregistry.client.SchemaRegistryClient;
import io.confluent.kafka.schemaregistry.client.rest.exceptions.RestClientException;
import org.apache.avro.Schema;

import java.io.IOException;
import java.io.OutputStream;
import java.nio.ByteBuffer;
import java.util.List;

import static org.apache.commons.lang.StringUtils.isEmpty;

/**
 *
 */
public class AvroSchemaHelper {
  public static final byte MAGIC_BYTE = 0x0;
  public static final byte MAGIC_BYTE_SIZE = 1;
  public static final int ID_SIZE = 4;

  private static final String KEY_PREFIX = "avro.";

  public static final String SCHEMA_SOURCE_KEY = KEY_PREFIX + "avroSchemaSource";

  public static final String SCHEMA_REPO_URLS_KEY = KEY_PREFIX + "schemaRegistryUrls";

  public static final String SUBJECT_KEY = KEY_PREFIX + "subject";
  public static final String SUBJECT_DEFAULT = "";

  public static final String SCHEMA_ID_KEY = KEY_PREFIX + "schemaId";
  public static final int SCHEMA_ID_DEFAULT = 0;

  public static final String SCHEMA_KEY = KEY_PREFIX + "schema";
  public static final String SCHEMA_DEFAULT = "";

  public static final String INCLUDE_SCHEMA_KEY = KEY_PREFIX + "includeSchema";
  public static final boolean INCLUDE_SCHEMA_DEFAULT = true;

  public static final String DEFAULT_VALUES_KEY = KEY_PREFIX + "defaultValues";

  public static final String COMPRESSION_CODEC_KEY = KEY_PREFIX + "compressionCodec";
  public static final String COMPRESSION_CODEC_DEFAULT = "null";

  private final SchemaRegistryClient registryClient;

  /**
   * AvroSchemaHelper constructor. DataFactory settings should be passed in for parsing.
   * @param settings DataFactory settings.
   */
  public AvroSchemaHelper(DataFactory.Settings settings) {
      final List<String> schemaRepoUrls = settings.getConfig(SCHEMA_REPO_URLS_KEY);

      if (!schemaRepoUrls.isEmpty()) {
        registryClient = new CachedSchemaRegistryClient(schemaRepoUrls, 1000);
      } else {
        registryClient = null;
      }
  }

  /**
   * Method to allow the caller to find out if this helper was configured with a schema registry or not.
   * @return true if a valid schema registry client is available.
   */
  public boolean hasRegistryClient() {
    return registryClient != null;
  }

  /**
   * Parses and returns an Avro schema loaded from the schema registry using the provided schema ID
   * if available, or the latest version of a schema for the specified subject.
   * @param subject optional schema subject (if schema ID is provided)
   * @param schemaId optional schema ID (if subject is provided)
   * @return parsed avro schema
   * @throws SchemaRegistryException if there is an error with the registry client
   */
  public Schema loadFromRegistry(String subject, int schemaId) throws SchemaRegistryException {
    try {
      if (isEmpty(subject)) {
        return loadFromRegistry(schemaId);
      } else {
        return loadFromRegistry(subject);
      }
    } catch (SchemaRegistryException e) {
      throw new SchemaRegistryException(e);
    }
  }

  /**
   * Parses an avro schema from a string instead of the schema registry.
   * @param schema JSON string representing an Avro schema
   * @return parsed avro schema
   */
  public Schema loadFromString(String schema) {
    return new Schema.Parser()
        .setValidate(true)
        //.setValidateDefaults(true)  -> we cannot use this api because 1.7.3 avro version does
        //not contain this api and MAPR hive jars uses 1.7.3 (even though streamsets use avro 1.7.7) and
        //We load the jar from mapr stage libs automatically -> this api i believe is kind of nice to have.
        .parse(schema);
  }

  /**
   * Registers a parsed schema with the schema registry under the specified subject.
   * @param schema parsed avro schema
   * @param subject subject to register the schema under
   * @return schemaId if registration was successful
   * @throws SchemaRegistryException if there is an error with the registry client
   */
  public int registerSchema(Schema schema, String subject) throws SchemaRegistryException {
    try {
      return registryClient.register(subject, schema);
    } catch (IOException | RestClientException e) {
      throw new SchemaRegistryException(e);
    }
  }

  /**
   * Loads and parses a schema for the specified subject from the schema registry
   * @param subject subject for which to fetch the latest version of a schema.
   * @return parsed avro schema
   * @throws SchemaRegistryException if there is an error with the registry client
   */
  public Schema loadFromRegistry(String subject) throws SchemaRegistryException {
    try {
      SchemaMetadata metadata = registryClient.getLatestSchemaMetadata(subject);
      return registryClient.getByID(metadata.getId());
    } catch (IOException | RestClientException e) {
{'fraction_non_alphanumeric': 0.06903872282608696, 'fraction_numerical': 0.00399116847826087, 'mean_word_length': 3.937945492662474, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 7, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '5834549', 'n_tokens_mistral': 3137, 'n_tokens_neox': 3072, 'n_words': 1186}