text:
package org.apache.drill.exec;

import org.apache.drill.exec.physical.impl.common.HashTable;
import org.apache.drill.exec.rpc.user.InboundImpersonationManager;
import org.apache.drill.exec.server.options.OptionValidator;
import org.apache.drill.exec.server.options.TypeValidators.BooleanValidator;
import org.apache.drill.exec.server.options.TypeValidators.DoubleValidator;
import org.apache.drill.exec.server.options.TypeValidators.EnumeratedStringValidator;
import org.apache.drill.exec.server.options.TypeValidators.LongValidator;
import org.apache.drill.exec.server.options.TypeValidators.MaxWidthValidator;
import org.apache.drill.exec.server.options.TypeValidators.PositiveLongValidator;
import org.apache.drill.exec.server.options.TypeValidators.PowerOfTwoLongValidator;
import org.apache.drill.exec.server.options.TypeValidators.RangeDoubleValidator;
import org.apache.drill.exec.server.options.TypeValidators.RangeLongValidator;
import org.apache.drill.exec.server.options.TypeValidators.StringValidator;
import org.apache.drill.exec.server.options.TypeValidators.AdminUsersValidator;
import org.apache.drill.exec.server.options.TypeValidators.AdminUserGroupsValidator;
import org.apache.drill.exec.testing.ExecutionControls;

public final class ExecConstants {
  private ExecConstants() {
    // Don't allow instantiation
  }

  public static final String ZK_RETRY_TIMES = "drill.exec.zk.retry.count";
  public static final String ZK_RETRY_DELAY = "drill.exec.zk.retry.delay";
  public static final String ZK_CONNECTION = "drill.exec.zk.connect";
  public static final String ZK_TIMEOUT = "drill.exec.zk.timeout";
  public static final String ZK_ROOT = "drill.exec.zk.root";
  public static final String ZK_REFRESH = "drill.exec.zk.refresh";
  public static final String BIT_RETRY_TIMES = "drill.exec.rpc.bit.server.retry.count";
  public static final String BIT_RETRY_DELAY = "drill.exec.rpc.bit.server.retry.delay";
  public static final String BIT_TIMEOUT = "drill.exec.bit.timeout" ;
  public static final String SERVICE_NAME = "drill.exec.cluster-id";
  public static final String INITIAL_BIT_PORT = "drill.exec.rpc.bit.server.port";
  public static final String INITIAL_DATA_PORT = "drill.exec.rpc.bit.server.dataport";
  public static final String BIT_RPC_TIMEOUT = "drill.exec.rpc.bit.timeout";
  public static final String INITIAL_USER_PORT = "drill.exec.rpc.user.server.port";
  public static final String USER_RPC_TIMEOUT = "drill.exec.rpc.user.timeout";
  public static final String METRICS_CONTEXT_NAME = "drill.exec.metrics.context";
  public static final String USE_IP_ADDRESS = "drill.exec.rpc.use.ip";
  public static final String CLIENT_RPC_THREADS = "drill.exec.rpc.user.client.threads";
  public static final String BIT_SERVER_RPC_THREADS = "drill.exec.rpc.bit.server.threads";
  public static final String USER_SERVER_RPC_THREADS = "drill.exec.rpc.user.server.threads";
  public static final String FRAG_RUNNER_RPC_TIMEOUT = "drill.exec.rpc.fragrunner.timeout";
  public static final PositiveLongValidator FRAG_RUNNER_RPC_TIMEOUT_VALIDATOR = new PositiveLongValidator(FRAG_RUNNER_RPC_TIMEOUT, Long.MAX_VALUE);
  public static final String TRACE_DUMP_DIRECTORY = "drill.exec.trace.directory";
  public static final String TRACE_DUMP_FILESYSTEM = "drill.exec.trace.filesystem";
  public static final String TEMP_DIRECTORIES = "drill.exec.tmp.directories";
  public static final String TEMP_FILESYSTEM = "drill.exec.tmp.filesystem";
  public static final String INCOMING_BUFFER_IMPL = "drill.exec.buffer.impl";
  /** incoming buffer size (number of batches) */
  public static final String INCOMING_BUFFER_SIZE = "drill.exec.buffer.size";
  public static final String SPOOLING_BUFFER_DELETE = "drill.exec.buffer.spooling.delete";
  public static final String SPOOLING_BUFFER_MEMORY = "drill.exec.buffer.spooling.size";
  public static final String BATCH_PURGE_THRESHOLD = "drill.exec.sort.purge.threshold";

  // Spill boot-time Options common to all spilling operators
  // (Each individual operator may override the common options)

  public static final String SPILL_FILESYSTEM = "drill.exec.spill.fs";
  public static final String SPILL_DIRS = "drill.exec.spill.directories";

  public static final String OUTPUT_BATCH_SIZE = "drill.exec.memory.operator.output_batch_size";
  // Output Batch Size in Bytes. We have a small lower bound so we can test with unit tests without the
  // need to produce very large batches that take up lot of memory.
  public static final LongValidator OUTPUT_BATCH_SIZE_VALIDATOR = new RangeLongValidator(OUTPUT_BATCH_SIZE, 128, 512 * 1024 * 1024);

  // External Sort Boot configuration

  public static final String EXTERNAL_SORT_TARGET_SPILL_BATCH_SIZE = "drill.exec.sort.external.spill.batch.size";
  public static final String EXTERNAL_SORT_SPILL_GROUP_SIZE = "drill.exec.sort.external.spill.group.size";
  public static final String EXTERNAL_SORT_SPILL_THRESHOLD = "drill.exec.sort.external.spill.threshold";
  public static final String EXTERNAL_SORT_SPILL_DIRS = "drill.exec.sort.external.spill.directories";
  public static final String EXTERNAL_SORT_SPILL_FILESYSTEM = "drill.exec.sort.external.spill.fs";
  public static final String EXTERNAL_SORT_SPILL_FILE_SIZE = "drill.exec.sort.external.spill.file_size";
  public static final String EXTERNAL_SORT_MSORT_MAX_BATCHSIZE = "drill.exec.sort.external.msort.batch.maxsize";
  public static final String EXTERNAL_SORT_DISABLE_MANAGED = "drill.exec.sort.external.disable_managed";
  public static final String EXTERNAL_SORT_MERGE_LIMIT = "drill.exec.sort.external.merge_limit";
  public static final String EXTERNAL_SORT_SPILL_BATCH_SIZE = "drill.exec.sort.external.spill.spill_batch_size";
  public static final String EXTERNAL_SORT_MERGE_BATCH_SIZE = "drill.exec.sort.external.spill.merge_batch_size";
  public static final String EXTERNAL_SORT_MAX_MEMORY = "drill.exec.sort.external.mem_limit";
  public static final String EXTERNAL_SORT_BATCH_LIMIT = "drill.exec.sort.external.batch_limit";

  // External Sort Runtime options

  public static final BooleanValidator EXTERNAL_SORT_DISABLE_MANAGED_OPTION = new BooleanValidator("exec.sort.disable_managed");

  // Hash Aggregate Options
  public static final String HASHAGG_NUM_PARTITIONS_KEY = "exec.hashagg.num_partitions";
  public static final LongValidator HASHAGG_NUM_PARTITIONS_VALIDATOR = new RangeLongValidator(HASHAGG_NUM_PARTITIONS_KEY, 1, 128); // 1 means - no spilling
  public static final String HASHAGG_MAX_MEMORY_KEY = "exec.hashagg.mem_limit";
  public static final LongValidator HASHAGG_MAX_MEMORY_VALIDATOR = new RangeLongValidator(HASHAGG_MAX_MEMORY_KEY, 0, Integer.MAX_VALUE);
  // min batches is used for tuning (each partition needs so many batches when planning the number of partitions,
  // or reserve this number when calculating whether the remaining available memory is too small and requires a spill.)
  // Low value may OOM (e.g., when incoming rows become wider), higher values use fewer partitions but are safer
  public static final String HASHAGG_MIN_BATCHES_PER_PARTITION_KEY = "exec.hashagg.min_batches_per_partition";
  public static final LongValidator HASHAGG_MIN_BATCHES_PER_PARTITION_VALIDATOR = new RangeLongValidator(HASHAGG_MIN_BATCHES_PER_PARTITION_KEY, 1, 5);
  // Can be turned off mainly for testing. Memory prediction is used to decide on when to spill to disk; with this option off,
  // spill would be triggered only by another mechanism -- "catch OOMs and then spill".
  public static final String HASHAGG_USE_MEMORY_PREDICTION_KEY = "exec.hashagg.use_memory_prediction";
  public static final BooleanValidator HASHAGG_USE_MEMORY_PREDICTION_VALIDATOR = new BooleanValidator(HASHAGG_USE_MEMORY_PREDICTION_KEY);

  public static final String HASHAGG_SPILL_DIRS = "drill.exec.hashagg.spill.directories";
  public static final String HASHAGG_SPILL_FILESYSTEM = "drill.exec.hashagg.spill.fs";
  public static final String HASHAGG_FALLBACK_ENABLED_KEY = "drill.exec.hashagg.fallback.enabled";
  public static final BooleanValidator HASHAGG_FALLBACK_ENABLED_VALIDATOR = new BooleanValidator(HASHAGG_FALLBACK_ENABLED_KEY);

  public static final String SSL_PROVIDER = "drill.exec.ssl.provider"; // valid values are "JDK", "OPENSSL" // default JDK
  public static final String SSL_PROTOCOL = "drill.exec.ssl.protocol"; // valid values are SSL, SSLV2, SSLV3, TLS, TLSV1, TLSv1.1, TLSv1.2(default)
  public static final String SSL_KEYSTORE_TYPE = "drill.exec.ssl.keyStoreType";
  public static final String SSL_KEYSTORE_PATH = "drill.exec.ssl.keyStorePath";     // path to keystore. default : $JRE_HOME/lib/security/keystore.jks
  public static final String SSL_KEYSTORE_PASSWORD = "drill.exec.ssl.keyStorePassword"; // default: changeit
  public static final String SSL_KEY_PASSWORD = "drill.exec.ssl.keyPassword"; //
  public static final String SSL_TRUSTSTORE_TYPE = "drill.exec.ssl.trustStoreType"; // valid values are jks(default), jceks, pkcs12
  public static final String SSL_TRUSTSTORE_PATH = "drill.exec.ssl.trustStorePath"; // path to keystore. default : $JRE_HOME/lib/security/cacerts.jks
  public static final String SSL_TRUSTSTORE_PASSWORD = "drill.exec.ssl.trustStorePassword"; // default: changeit
  public static final String SSL_USE_HADOOP_CONF = "drill.exec.ssl.useHadoopConfig"; // Initialize ssl params from hadoop if not provided by drill. default: true
  public static final String SSL_HANDSHAKE_TIMEOUT = "drill.exec.security.user.encryption.ssl.handshakeTimeout"; // Default 10 seconds

  public static final String TEXT_LINE_READER_BATCH_SIZE = "drill.exec.storage.file.text.batch.size";
  public static final String TEXT_LINE_READER_BUFFER_SIZE = "drill.exec.storage.file.text.buffer.size";
  public static final String HAZELCAST_SUBNETS = "drill.exec.cache.hazel.subnets";
  public static final String HTTP_ENABLE = "drill.exec.http.enabled";
  public static final String HTTP_MAX_PROFILES = "drill.exec.http.max_profiles";
  public static final String HTTP_PORT = "drill.exec.http.port";
  public static final String HTTP_PORT_HUNT = "drill.exec.http.porthunt";
  public static final String HTTP_JETTY_SERVER_ACCEPTORS = "drill.exec.http.jetty.server.acceptors";
  public static final String HTTP_JETTY_SERVER_SELECTORS = "drill.exec.http.jetty.server.selectors";
  public static final String HTTP_ENABLE_SSL = "drill.exec.http.ssl_enabled";
  public static final String HTTP_CORS_ENABLED = "drill.exec.http.cors.enabled";
  public static final String HTTP_CORS_ALLOWED_ORIGINS = "drill.exec.http.cors.allowedOrigins";
  public static final String HTTP_CORS_ALLOWED_METHODS = "drill.exec.http.cors.allowedMethods";
  public static final String HTTP_CORS_ALLOWED_HEADERS = "drill.exec.http.cors.allowedHeaders";
  public static final String HTTP_CORS_CREDENTIALS = "drill.exec.http.cors.credentials";
  public static final String HTTP_SESSION_MEMORY_RESERVATION = "drill.exec.http.session.memory.reservation";
  public static final String HTTP_SESSION_MEMORY_MAXIMUM = "drill.exec.http.session.memory.maximum";
  public static final String HTTP_SESSION_MAX_IDLE_SECS = "drill.exec.http.session_max_idle_secs";
  public static final String HTTP_KEYSTORE_PATH = SSL_KEYSTORE_PATH;
  public static final String HTTP_KEYSTORE_PASSWORD = SSL_KEYSTORE_PASSWORD;
  public static final String HTTP_TRUSTSTORE_PATH = SSL_TRUSTSTORE_PATH;
  public static final String HTTP_TRUSTSTORE_PASSWORD = SSL_TRUSTSTORE_PASSWORD;
  public static final String HTTP_AUTHENTICATION_MECHANISMS = "drill.exec.http.auth.mechanisms";
  public static final String HTTP_SPNEGO_PRINCIPAL = "drill.exec.http.auth.spnego.principal";
  public static final String HTTP_SPNEGO_KEYTAB = "drill.exec.http.auth.spnego.keytab";
  public static final String SYS_STORE_PROVIDER_CLASS = "drill.exec.sys.store.provider.class";
  public static final String SYS_STORE_PROVIDER_LOCAL_PATH = "drill.exec.sys.store.provider.local.path";
  public static final String SYS_STORE_PROVIDER_LOCAL_ENABLE_WRITE = "drill.exec.sys.store.provider.local.write";
  public static final String PROFILES_STORE_INMEMORY = "drill.exec.profiles.store.inmemory";
  public static final String PROFILES_STORE_CAPACITY = "drill.exec.profiles.store.capacity";
  public static final String IMPERSONATION_ENABLED = "drill.exec.impersonation.enabled";
  public static final String IMPERSONATION_MAX_CHAINED_USER_HOPS = "drill.exec.impersonation.max_chained_user_hops";
  public static final String AUTHENTICATION_MECHANISMS = "drill.exec.security.auth.mechanisms";
  public static final String USER_AUTHENTICATION_ENABLED = "drill.exec.security.user.auth.enabled";
  public static final String USER_AUTHENTICATOR_IMPL = "drill.exec.security.user.auth.impl";
  public static final String PAM_AUTHENTICATOR_PROFILES = "drill.exec.security.user.auth.pam_profiles";
  public static final String BIT_AUTHENTICATION_ENABLED = "drill.exec.security.bit.auth.enabled";
  public static final String BIT_AUTHENTICATION_MECHANISM = "drill.exec.security.bit.auth.mechanism";
  public static final String USE_LOGIN_PRINCIPAL = "drill.exec.security.bit.auth.use_login_principal";
  public static final String USER_ENCRYPTION_SASL_ENABLED = "drill.exec.security.user.encryption.sasl.enabled";
  public static final String USER_ENCRYPTION_SASL_MAX_WRAPPED_SIZE = "drill.exec.security.user.encryption.sasl.max_wrapped_size";
  private static final String SERVICE_LOGIN_PREFIX = "drill.exec.security.auth";
  public static final String SERVICE_PRINCIPAL = SERVICE_LOGIN_PREFIX + ".principal";
  public static final String SERVICE_KEYTAB_LOCATION = SERVICE_LOGIN_PREFIX + ".keytab";
  public static final String KERBEROS_NAME_MAPPING = SERVICE_LOGIN_PREFIX + ".auth_to_local";

  public static final String USER_SSL_ENABLED = "drill.exec.security.user.encryption.ssl.enabled";
  public static final String BIT_ENCRYPTION_SASL_ENABLED = "drill.exec.security.bit.encryption.sasl.enabled";
  public static final String BIT_ENCRYPTION_SASL_MAX_WRAPPED_SIZE = "drill.exec.security.bit.encryption.sasl.max_wrapped_size";

  /** Size of JDBC batch queue (in batches) above which throttling begins. */
  public static final String JDBC_BATCH_QUEUE_THROTTLING_THRESHOLD =
      "drill.jdbc.batch_queue_throttling_threshold";
  // Thread pool size for scan threads. Used by the Parquet scan.
  public static final String SCAN_THREADPOOL_SIZE = "drill.exec.scan.threadpool_size";
  // The size of the thread pool used by a scan to decode the data. Used by Parquet
  public static final String SCAN_DECODE_THREADPOOL_SIZE = "drill.exec.scan.decode_threadpool_size";

  /**
   * Currently if a query is cancelled, but one of the fragments reports the status as FAILED instead of CANCELLED or
   * FINISHED we report the query result as CANCELLED by swallowing the failures occurred in fragments. This BOOT
   * setting allows the user to see the query status as failure. Useful for developers/testers.
   */
  public static final String RETURN_ERROR_FOR_FAILURE_IN_CANCELLED_FRAGMENTS = "drill.exec.debug.return_error_for_failure_in_cancelled_fragments";

  public static final String CLIENT_SUPPORT_COMPLEX_TYPES = "drill.client.supports-complex-types";

  /**
   * Configuration properties connected with dynamic UDFs support
   */
  public static final String UDF_RETRY_ATTEMPTS = "drill.exec.udf.retry-attempts";
  public static final String UDF_DIRECTORY_LOCAL = "drill.exec.udf.directory.local";
  public static final String UDF_DIRECTORY_FS = "drill.exec.udf.directory.fs";
  public static final String UDF_DIRECTORY_ROOT = "drill.exec.udf.directory.root";
  public static final String UDF_DIRECTORY_STAGING = "drill.exec.udf.directory.staging";
  public static final String UDF_DIRECTORY_REGISTRY = "drill.exec.udf.directory.registry";
  public static final String UDF_DIRECTORY_TMP = "drill.exec.udf.directory.tmp";
  public static final String UDF_DISABLE_DYNAMIC = "drill.exec.udf.disable_dynamic";

  /**
   * Local temporary directory is used as base for temporary storage of Dynamic UDF jars.
   */
  public static final String DRILL_TMP_DIR = "drill.tmp-dir";

  /**
   * Temporary tables can be created ONLY in default temporary workspace.
   */
  public static final String DEFAULT_TEMPORARY_WORKSPACE = "drill.exec.default_temporary_workspace";

  public static final String OUTPUT_FORMAT_OPTION = "store.format";
  public static final OptionValidator OUTPUT_FORMAT_VALIDATOR = new StringValidator(OUTPUT_FORMAT_OPTION);
  public static final String PARQUET_BLOCK_SIZE = "store.parquet.block-size";
  public static final String PARQUET_WRITER_USE_SINGLE_FS_BLOCK = "store.parquet.writer.use_single_fs_block";
  public static final OptionValidator PARQUET_WRITER_USE_SINGLE_FS_BLOCK_VALIDATOR = new BooleanValidator(
    PARQUET_WRITER_USE_SINGLE_FS_BLOCK);
  public static final OptionValidator PARQUET_BLOCK_SIZE_VALIDATOR = new PositiveLongValidator(PARQUET_BLOCK_SIZE, Integer.MAX_VALUE);
  public static final String PARQUET_PAGE_SIZE = "store.parquet.page-size";
  public static final OptionValidator PARQUET_PAGE_SIZE_VALIDATOR = new PositiveLongValidator(PARQUET_PAGE_SIZE, Integer.MAX_VALUE);
  public static final String PARQUET_DICT_PAGE_SIZE = "store.parquet.dictionary.page-size";
  public static final OptionValidator PARQUET_DICT_PAGE_SIZE_VALIDATOR = new PositiveLongValidator(PARQUET_DICT_PAGE_SIZE, Integer.MAX_VALUE);
  public static final String PARQUET_WRITER_COMPRESSION_TYPE = "store.parquet.compression";
  public static final OptionValidator PARQUET_WRITER_COMPRESSION_TYPE_VALIDATOR = new EnumeratedStringValidator(
      PARQUET_WRITER_COMPRESSION_TYPE, "snappy", "gzip", "none");
  public static final String PARQUET_WRITER_ENABLE_DICTIONARY_ENCODING = "store.parquet.enable_dictionary_encoding";
  public static final OptionValidator PARQUET_WRITER_ENABLE_DICTIONARY_ENCODING_VALIDATOR = new BooleanValidator(
      PARQUET_WRITER_ENABLE_DICTIONARY_ENCODING);

  public static final String PARQUET_WRITER_USE_PRIMITIVE_TYPES_FOR_DECIMALS
      = "store.parquet.writer.use_primitive_types_for_decimals";
  public static final OptionValidator PARQUET_WRITER_USE_PRIMITIVE_TYPES_FOR_DECIMALS_VALIDATOR = new BooleanValidator(
    PARQUET_WRITER_USE_PRIMITIVE_TYPES_FOR_DECIMALS);

  public static final String PARQUET_WRITER_LOGICAL_TYPE_FOR_DECIMALS
      = "store.parquet.writer.logical_type_for_decimals";
  public static final OptionValidator PARQUET_WRITER_LOGICAL_TYPE_FOR_DECIMALS_VALIDATOR
      = new EnumeratedStringValidator(PARQUET_WRITER_LOGICAL_TYPE_FOR_DECIMALS, "fixed_len_byte_array", "binary");

  public static final String PARQUET_VECTOR_FILL_THRESHOLD = "store.parquet.vector_fill_threshold";
  public static final OptionValidator PARQUET_VECTOR_FILL_THRESHOLD_VALIDATOR = new PositiveLongValidator(PARQUET_VECTOR_FILL_THRESHOLD, 99l);
  public static final String PARQUET_VECTOR_FILL_CHECK_THRESHOLD = "store.parquet.vector_fill_check_threshold";
  public static final OptionValidator PARQUET_VECTOR_FILL_CHECK_THRESHOLD_VALIDATOR = new PositiveLongValidator(PARQUET_VECTOR_FILL_CHECK_THRESHOLD, 100l);
  public static final String PARQUET_NEW_RECORD_READER = "store.parquet.use_new_reader";
  public static final OptionValidator PARQUET_RECORD_READER_IMPLEMENTATION_VALIDATOR = new BooleanValidator(PARQUET_NEW_RECORD_READER);
  public static final String PARQUET_READER_INT96_AS_TIMESTAMP = "store.parquet.reader.int96_as_timestamp";
  public static final OptionValidator PARQUET_READER_INT96_AS_TIMESTAMP_VALIDATOR = new BooleanValidator(PARQUET_READER_INT96_AS_TIMESTAMP);

  public static final String PARQUET_PAGEREADER_ASYNC = "store.parquet.reader.pagereader.async";
  public static final OptionValidator PARQUET_PAGEREADER_ASYNC_VALIDATOR = new BooleanValidator(PARQUET_PAGEREADER_ASYNC);

  // Number of pages the Async Parquet page reader will read before blocking
  public static final String PARQUET_PAGEREADER_QUEUE_SIZE = "store.parquet.reader.pagereader.queuesize";
  public static final OptionValidator PARQUET_PAGEREADER_QUEUE_SIZE_VALIDATOR = new  PositiveLongValidator(PARQUET_PAGEREADER_QUEUE_SIZE, Integer.MAX_VALUE);

  public static final String PARQUET_PAGEREADER_ENFORCETOTALSIZE = "store.parquet.reader.pagereader.enforceTotalSize";
  public static final OptionValidator PARQUET_PAGEREADER_ENFORCETOTALSIZE_VALIDATOR = new BooleanValidator(PARQUET_PAGEREADER_ENFORCETOTALSIZE);

  public static final String PARQUET_COLUMNREADER_ASYNC = "store.parquet.reader.columnreader.async";
  public static final OptionValidator PARQUET_COLUMNREADER_ASYNC_VALIDATOR = new BooleanValidator(PARQUET_COLUMNREADER_ASYNC);

  // Use a buffering reader for Parquet page reader
  public static final String PARQUET_PAGEREADER_USE_BUFFERED_READ = "store.parquet.reader.pagereader.bufferedread";
  public static final OptionValidator PARQUET_PAGEREADER_USE_BUFFERED_READ_VALIDATOR = new  BooleanValidator(PARQUET_PAGEREADER_USE_BUFFERED_READ);

  // Size in MiB of the buffer the Parquet page reader will use to read from disk. Default is 1 MiB
  public static final String PARQUET_PAGEREADER_BUFFER_SIZE = "store.parquet.reader.pagereader.buffersize";
  public static final OptionValidator PARQUET_PAGEREADER_BUFFER_SIZE_VALIDATOR = new  LongValidator(PARQUET_PAGEREADER_BUFFER_SIZE);

  // try to use fadvise if available
  public static final String PARQUET_PAGEREADER_USE_FADVISE = "store.parquet.reader.pagereader.usefadvise";
  public static final OptionValidator PARQUET_PAGEREADER_USE_FADVISE_VALIDATOR = new  BooleanValidator(PARQUET_PAGEREADER_USE_FADVISE);

  public static final OptionValidator COMPILE_SCALAR_REPLACEMENT = new BooleanValidator("exec.compile.scalar_replacement");

  public static final String JSON_ALL_TEXT_MODE = "store.json.all_text_mode";
  public static final BooleanValidator JSON_READER_ALL_TEXT_MODE_VALIDATOR = new BooleanValidator(JSON_ALL_TEXT_MODE);
  public static final BooleanValidator JSON_EXTENDED_TYPES = new BooleanValidator("store.json.extended_types");
  public static final BooleanValidator JSON_WRITER_UGLIFY = new BooleanValidator("store.json.writer.uglify");
  public static final BooleanValidator JSON_WRITER_SKIPNULLFIELDS = new BooleanValidator("store.json.writer.skip_null_fields");
  public static final String JSON_READER_SKIP_INVALID_RECORDS_FLAG = "store.json.reader.skip_invalid_records";
  public static final BooleanValidator JSON_SKIP_MALFORMED_RECORDS_VALIDATOR = new BooleanValidator(JSON_READER_SKIP_INVALID_RECORDS_FLAG);
  public static final String JSON_READER_PRINT_INVALID_RECORDS_LINE_NOS_FLAG = "store.json.reader.print_skipped_invalid_record_number";
  public static final BooleanValidator JSON_READER_PRINT_INVALID_RECORDS_LINE_NOS_FLAG_VALIDATOR = new BooleanValidator(JSON_READER_PRINT_INVALID_RECORDS_LINE_NOS_FLAG);
  public static final DoubleValidator TEXT_ESTIMATED_ROW_SIZE = new RangeDoubleValidator("store.text.estimated_row_size_bytes", 1, Long.MAX_VALUE);

  /**
   * Json writer option for writing `NaN` and `Infinity` tokens as numbers (not enclosed with double quotes)
   */
  public static final String JSON_WRITER_NAN_INF_NUMBERS = "store.json.writer.allow_nan_inf";
  public static final BooleanValidator JSON_WRITER_NAN_INF_NUMBERS_VALIDATOR = new BooleanValidator(JSON_WRITER_NAN_INF_NUMBERS);
  /**
   * Json reader option that enables parser to read `NaN` and `Infinity` tokens as numbers
   */
  public static final String JSON_READER_NAN_INF_NUMBERS = "store.json.reader.allow_nan_inf";
  public static final BooleanValidator JSON_READER_NAN_INF_NUMBERS_VALIDATOR = new BooleanValidator(JSON_READER_NAN_INF_NUMBERS);
  /**
   * The column label (for directory levels) in results when querying files in a directory
   * E.g.  labels: dir0   dir1<pre>
   *    structure: foo
   *                |-    bar  -  a.parquet
   *                |-    baz  -  b.parquet</pre>
   */
  public static final String FILESYSTEM_PARTITION_COLUMN_LABEL = "drill.exec.storage.file.partition.column.label";
  public static final StringValidator FILESYSTEM_PARTITION_COLUMN_LABEL_VALIDATOR = new StringValidator(FILESYSTEM_PARTITION_COLUMN_LABEL);

  /**
   * Implicit file columns
   */
  public static final String IMPLICIT_FILENAME_COLUMN_LABEL = "drill.exec.storage.implicit.filename.column.label";
  public static final OptionValidator IMPLICIT_FILENAME_COLUMN_LABEL_VALIDATOR = new StringValidator(IMPLICIT_FILENAME_COLUMN_LABEL);
  public static final String IMPLICIT_SUFFIX_COLUMN_LABEL = "drill.exec.storage.implicit.suffix.column.label";
  public static final OptionValidator IMPLICIT_SUFFIX_COLUMN_LABEL_VALIDATOR = new StringValidator(IMPLICIT_SUFFIX_COLUMN_LABEL);
  public static final String IMPLICIT_FQN_COLUMN_LABEL = "drill.exec.storage.implicit.fqn.column.label";
  public static final OptionValidator IMPLICIT_FQN_COLUMN_LABEL_VALIDATOR = new StringValidator(IMPLICIT_FQN_COLUMN_LABEL);
  public static final String IMPLICIT_FILEPATH_COLUMN_LABEL = "drill.exec.storage.implicit.filepath.column.label";
  public static final OptionValidator IMPLICIT_FILEPATH_COLUMN_LABEL_VALIDATOR = new StringValidator(IMPLICIT_FILEPATH_COLUMN_LABEL);

  public static final String JSON_READ_NUMBERS_AS_DOUBLE = "store.json.read_numbers_as_double";
  public static final BooleanValidator JSON_READ_NUMBERS_AS_DOUBLE_VALIDATOR = new BooleanValidator(JSON_READ_NUMBERS_AS_DOUBLE);

  public static final String MONGO_ALL_TEXT_MODE = "store.mongo.all_text_mode";
  public static final OptionValidator MONGO_READER_ALL_TEXT_MODE_VALIDATOR = new BooleanValidator(MONGO_ALL_TEXT_MODE);
  public static final String MONGO_READER_READ_NUMBERS_AS_DOUBLE = "store.mongo.read_numbers_as_double";
  public static final OptionValidator MONGO_READER_READ_NUMBERS_AS_DOUBLE_VALIDATOR = new BooleanValidator(MONGO_READER_READ_NUMBERS_AS_DOUBLE);
  public static final String MONGO_BSON_RECORD_READER = "store.mongo.bson.record.reader";
  public static final OptionValidator MONGO_BSON_RECORD_READER_VALIDATOR = new BooleanValidator(MONGO_BSON_RECORD_READER);

  public static final String ENABLE_UNION_TYPE_KEY = "exec.enable_union_type";
  public static final BooleanValidator ENABLE_UNION_TYPE = new BooleanValidator(ENABLE_UNION_TYPE_KEY);

  // Kafka plugin related options.
  public static final String KAFKA_ALL_TEXT_MODE = "store.kafka.all_text_mode";
  public static final OptionValidator KAFKA_READER_ALL_TEXT_MODE_VALIDATOR = new BooleanValidator(KAFKA_ALL_TEXT_MODE);
  public static final String KAFKA_READER_READ_NUMBERS_AS_DOUBLE = "store.kafka.read_numbers_as_double";
  public static final OptionValidator KAFKA_READER_READ_NUMBERS_AS_DOUBLE_VALIDATOR = new BooleanValidator(
      KAFKA_READER_READ_NUMBERS_AS_DOUBLE);
  public static final String KAFKA_RECORD_READER = "store.kafka.record.reader";
  public static final OptionValidator KAFKA_RECORD_READER_VALIDATOR = new StringValidator(KAFKA_RECORD_READER);
  public static final String KAFKA_POLL_TIMEOUT = "store.kafka.poll.timeout";
  public static final PositiveLongValidator KAFKA_POLL_TIMEOUT_VALIDATOR = new PositiveLongValidator(KAFKA_POLL_TIMEOUT,
      Long.MAX_VALUE);

  // TODO: We need to add a feature that enables storage plugins to add their own options. Currently we have to declare
  // in core which is not right. Move this option and above two mongo plugin related options once we have the feature.
  public static final String HIVE_OPTIMIZE_SCAN_WITH_NATIVE_READERS = "store.hive.optimize_scan_with_native_readers";
  public static final OptionValidator HIVE_OPTIMIZE_SCAN_WITH_NATIVE_READERS_VALIDATOR =
      new BooleanValidator(HIVE_OPTIMIZE_SCAN_WITH_NATIVE_READERS);

  public static final String SLICE_TARGET = "planner.slice_target";
  public static final long SLICE_TARGET_DEFAULT = 100000l;
  public static final PositiveLongValidator SLICE_TARGET_OPTION = new PositiveLongValidator(SLICE_TARGET, Long.MAX_VALUE);

  public static final String CAST_TO_NULLABLE_NUMERIC = "drill.exec.functions.cast_empty_string_to_null";
  public static final BooleanValidator CAST_TO_NULLABLE_NUMERIC_OPTION = new BooleanValidator(CAST_TO_NULLABLE_NUMERIC);

  /**
   * HashTable runtime settings
   */
  public static final String MIN_HASH_TABLE_SIZE_KEY = "exec.min_hash_table_size";
  public static final PositiveLongValidator MIN_HASH_TABLE_SIZE = new PositiveLongValidator(MIN_HASH_TABLE_SIZE_KEY, HashTable.MAXIMUM_CAPACITY);
  public static final String MAX_HASH_TABLE_SIZE_KEY = "exec.max_hash_table_size";
  public static final PositiveLongValidator MAX_HASH_TABLE_SIZE = new PositiveLongValidator(MAX_HASH_TABLE_SIZE_KEY, HashTable.MAXIMUM_CAPACITY);

  /**
   * Limits the maximum level of parallelization to this factor time the number of Drillbits
   */
  public static final String CPU_LOAD_AVERAGE_KEY = "planner.cpu_load_average";
  public static final DoubleValidator CPU_LOAD_AVERAGE = new DoubleValidator(CPU_LOAD_AVERAGE_KEY);
  public static final String MAX_WIDTH_PER_NODE_KEY = "planner.width.max_per_node";
  public static final MaxWidthValidator MAX_WIDTH_PER_NODE = new MaxWidthValidator(MAX_WIDTH_PER_NODE_KEY);

  /**
   * The maximum level or parallelization any stage of the query can do. Note that while this
   * might be the number of active Drillbits, realistically, this could be well beyond that
   * number of we want to do things like speed results return.
   */
  public static final String MAX_WIDTH_GLOBAL_KEY = "planner.width.max_per_query";
  public static final OptionValidator MAX_WIDTH_GLOBAL = new PositiveLongValidator(MAX_WIDTH_GLOBAL_KEY, Integer.MAX_VALUE);

  /**
   * Factor by which a node with endpoint affinity will be favored while creating assignment
   */
  public static final String AFFINITY_FACTOR_KEY = "planner.affinity_factor";
  public static final OptionValidator AFFINITY_FACTOR = new DoubleValidator(AFFINITY_FACTOR_KEY);

  public static final String EARLY_LIMIT0_OPT_KEY = "planner.enable_limit0_optimization";
  public static final BooleanValidator EARLY_LIMIT0_OPT = new BooleanValidator(EARLY_LIMIT0_OPT_KEY);

  public static final String ENABLE_MEMORY_ESTIMATION_KEY = "planner.memory.enable_memory_estimation";
  public static final OptionValidator ENABLE_MEMORY_ESTIMATION = new BooleanValidator(ENABLE_MEMORY_ESTIMATION_KEY);

  /**
   * Maximum query memory per node (in MB). Re-plan with cheaper operators if
   * memory estimation exceeds this limit.
   * <p/>
   * DEFAULT: 2048 MB
   */
  public static final String MAX_QUERY_MEMORY_PER_NODE_KEY = "planner.memory.max_query_memory_per_node";
  public static final LongValidator MAX_QUERY_MEMORY_PER_NODE = new RangeLongValidator(MAX_QUERY_MEMORY_PER_NODE_KEY, 1024 * 1024, Long.MAX_VALUE);

  /**
   * Alternative way to compute per-query-per-node memory as a percent
   * of the total available system memory.
   * <p>
   * Suggestion for computation.
   * <ul>
   * <li>Assume an allowance for non-managed operators. Default assumption:
   * 50%</li>
   * <li>Assume a desired number of concurrent queries. Default assumption:
   * 10.</li>
   * <li>The value of this parameter is<br>
   * (1 - non-managed allowance) / concurrency</li>
   * </ul>
   * Doing the math produces the default 5% number. The actual number
   * given is no less than the <tt>max_query_memory_per_node</tt>
   * amount.
   * <p>
   * This number is used only when throttling is disabled. Setting the
   * number to 0 effectively disables this technique as it will always
   * produce values lower than <tt>max_query_memory_per_node</tt>.
   * <p>
   * DEFAULT: 5%
   */

  public static String PERCENT_MEMORY_PER_QUERY_KEY = "planner.memory.percent_per_query";
  public static DoubleValidator PERCENT_MEMORY_PER_QUERY = new RangeDoubleValidator(
      PERCENT_MEMORY_PER_QUERY_KEY, 0, 1.0);

  /**
   * Minimum memory allocated to each buffered operator instance.
   * <p/>
   * DEFAULT: 40 MB
   */
  public static final String MIN_MEMORY_PER_BUFFERED_OP_KEY = "planner.memory.min_memory_per_buffered_op";
  public static final LongValidator MIN_MEMORY_PER_BUFFERED_OP = new RangeLongValidator(MIN_MEMORY_PER_BUFFERED_OP_KEY, 1024 * 1024, Long.MAX_VALUE);

  /**
   * Extra query memory per node for non-blocking operators.
   * NOTE: This option is currently used only for memory estimation.
   * <p/>
   * DEFAULT: 64 MB
   * MAXIMUM: 2048 MB
   */
  public static final String NON_BLOCKING_OPERATORS_MEMORY_KEY = "planner.memory.non_blocking_operators_memory";
  public static final OptionValidator NON_BLOCKING_OPERATORS_MEMORY = new PowerOfTwoLongValidator(
    NON_BLOCKING_OPERATORS_MEMORY_KEY, 1 << 11);

  public static final String HASH_JOIN_TABLE_FACTOR_KEY = "planner.memory.hash_join_table_factor";
  public static final OptionValidator HASH_JOIN_TABLE_FACTOR = new DoubleValidator(HASH_JOIN_TABLE_FACTOR_KEY);

  public static final String HASH_AGG_TABLE_FACTOR_KEY = "planner.memory.hash_agg_table_factor";
  public static final OptionValidator HASH_AGG_TABLE_FACTOR = new DoubleValidator(HASH_AGG_TABLE_FACTOR_KEY);

  public static final String AVERAGE_FIELD_WIDTH_KEY = "planner.memory.average_field_width";
  public static final OptionValidator AVERAGE_FIELD_WIDTH = new PositiveLongValidator(AVERAGE_FIELD_WIDTH_KEY, Long.MAX_VALUE);

  // Mux Exchange options.
  public static final String ORDERED_MUX_EXCHANGE = "planner.enable_ordered_mux_exchange";

  // Resource management boot-time options.

  public static final String MAX_MEMORY_PER_NODE = "drill.exec.rm.memory_per_node";
  public static final String MAX_CPUS_PER_NODE = "drill.exec.rm.cpus_per_node";

  // Resource management system run-time options.

  // Enables queues. When running embedded, enables an in-process queue. When
  // running distributed, enables the Zookeeper-based distributed queue.

  public static final BooleanValidator ENABLE_QUEUE = new BooleanValidator("exec.queue.enable");
  public static final LongValidator LARGE_QUEUE_SIZE = new PositiveLongValidator("exec.queue.large", 10_000);
  public static final LongValidator SMALL_QUEUE_SIZE = new PositiveLongValidator("exec.queue.small", 100_000);
  public static final LongValidator QUEUE_THRESHOLD_SIZE = new PositiveLongValidator("exec.queue.threshold", Long.MAX_VALUE);
  public static final LongValidator QUEUE_TIMEOUT = new PositiveLongValidator("exec.queue.timeout_millis", Long.MAX_VALUE);

  // Ratio of memory for small queries vs. large queries.
  // Each small query gets 1 unit, each large query gets QUEUE_MEMORY_RATIO units.
  // A lower limit of 1 enforces the intuition that a large query should never get
  // *less* memory than a small one.

  public static final DoubleValidator QUEUE_MEMORY_RATIO = new RangeDoubleValidator("exec.queue.memory_ratio", 1.0, 1000);

  public static final DoubleValidator QUEUE_MEMORY_RESERVE = new RangeDoubleValidator("exec.queue.memory_reserve_ratio", 0, 1.0);

  public static final String ENABLE_VERBOSE_ERRORS_KEY = "exec.errors.verbose";
  public static final OptionValidator ENABLE_VERBOSE_ERRORS = new BooleanValidator(ENABLE_VERBOSE_ERRORS_KEY);

  public static final String ENABLE_NEW_TEXT_READER_KEY = "exec.storage.enable_new_text_reader";
  public static final OptionValidator ENABLE_NEW_TEXT_READER = new BooleanValidator(ENABLE_NEW_TEXT_READER_KEY);

  public static final String BOOTSTRAP_STORAGE_PLUGINS_FILE = "bootstrap-storage-plugins.json";

  public static final String DRILL_SYS_FILE_SUFFIX = ".sys.drill";

  public static final String ENABLE_WINDOW_FUNCTIONS = "window.enable";
  public static final OptionValidator ENABLE_WINDOW_FUNCTIONS_VALIDATOR = new BooleanValidator(ENABLE_WINDOW_FUNCTIONS);

  public static final String DRILLBIT_CONTROL_INJECTIONS = "drill.exec.testing.controls";
  public static final OptionValidator DRILLBIT_CONTROLS_VALIDATOR = new ExecutionControls.ControlsOptionValidator(DRILLBIT_CONTROL_INJECTIONS, 1);

  public static final String NEW_VIEW_DEFAULT_PERMS_KEY = "new_view_default_permissions";
  public static final OptionValidator NEW_VIEW_DEFAULT_PERMS_VALIDATOR = new StringValidator(NEW_VIEW_DEFAULT_PERMS_KEY);

  public static final String CTAS_PARTITIONING_HASH_DISTRIBUTE = "store.partition.hash_distribute";
  public static final BooleanValidator CTAS_PARTITIONING_HASH_DISTRIBUTE_VALIDATOR = new BooleanValidator(CTAS_PARTITIONING_HASH_DISTRIBUTE);

  public static final String ENABLE_BULK_LOAD_TABLE_LIST_KEY = "exec.enable_bulk_load_table_list";
  public static final BooleanValidator ENABLE_BULK_LOAD_TABLE_LIST = new BooleanValidator(ENABLE_BULK_LOAD_TABLE_LIST_KEY);

  /**
   * When getting Hive Table information with exec.enable_bulk_load_table_list set to true,
   * use the exec.bulk_load_table_list.bulk_size to determine how many tables to fetch from HiveMetaStore
   * at a time. (The number of tables can get to be quite large.)
   */
  public static final String BULK_LOAD_TABLE_LIST_BULK_SIZE_KEY = "exec.bulk_load_table_list.bulk_size";
  public static final PositiveLongValidator BULK_LOAD_TABLE_LIST_BULK_SIZE = new PositiveLongValidator(BULK_LOAD_TABLE_LIST_BULK_SIZE_KEY, Integer.MAX_VALUE);

  /**
   * Option whose value is a comma separated list of admin usernames. Admin users are users who have special privileges
   * such as changing system options.
   */
  public static final String ADMIN_USERS_KEY = "security.admin.users";
  public static final AdminUsersValidator ADMIN_USERS_VALIDATOR = new AdminUsersValidator(ADMIN_USERS_KEY);

  /**
   * Option whose value is a comma separated list of admin usergroups.
   */
  public static final String ADMIN_USER_GROUPS_KEY = "security.admin.user_groups";
  public static final AdminUserGroupsValidator ADMIN_USER_GROUPS_VALIDATOR =
          new AdminUserGroupsValidator(ADMIN_USER_GROUPS_KEY);
  /**
   * Option whose value is a string representing list of inbound impersonation policies.
   *
   * Impersonation policy format:
   * [
   *   {
   *    proxy_principals : { users : ["..."], groups : ["..."] },
   *    target_principals : { users : ["..."], groups : ["..."] }
   *   },
   *   ...
   * ]
   */
  public static final String IMPERSONATION_POLICIES_KEY = "exec.impersonation.inbound_policies";
  public static final StringValidator IMPERSONATION_POLICY_VALIDATOR =
      new InboundImpersonationManager.InboundImpersonationPolicyValidator(IMPERSONATION_POLICIES_KEY);

  /**
   * Web settings
   */
  public static final String WEB_LOGS_MAX_LINES = "web.logs.max_lines";
  public static final OptionValidator WEB_LOGS_MAX_LINES_VALIDATOR = new PositiveLongValidator(WEB_LOGS_MAX_LINES, Integer.MAX_VALUE);

  public static final String CODE_GEN_EXP_IN_METHOD_SIZE = "exec.java.compiler.exp_in_method_size";
  public static final LongValidator CODE_GEN_EXP_IN_METHOD_SIZE_VALIDATOR = new LongValidator(CODE_GEN_EXP_IN_METHOD_SIZE);

  public static final String CREATE_PREPARE_STATEMENT_TIMEOUT_MILLIS = "prepare.statement.create_timeout_ms";
  public static final OptionValidator CREATE_PREPARE_STATEMENT_TIMEOUT_MILLIS_VALIDATOR =
      new PositiveLongValidator(CREATE_PREPARE_STATEMENT_TIMEOUT_MILLIS, Integer.MAX_VALUE);

  public static final String DYNAMIC_UDF_SUPPORT_ENABLED = "exec.udf.enable_dynamic_support";
  public static final BooleanValidator DYNAMIC_UDF_SUPPORT_ENABLED_VALIDATOR = new BooleanValidator(DYNAMIC_UDF_SUPPORT_ENABLED);

  /**
   * Option to save query profiles. If false, no query profile will be saved
   * for any query.
   */
  public static final String ENABLE_QUERY_PROFILE_OPTION = "exec.query_profile.save";
  public static final BooleanValidator ENABLE_QUERY_PROFILE_VALIDATOR = new BooleanValidator(ENABLE_QUERY_PROFILE_OPTION);

  /**
   * Profiles are normally written after the last client message to reduce latency.
   * When running tests, however, we want the profile written <i>before</i> the
   * return so that the client can immediately read the profile for test
   * verification.
   */
  public static final String QUERY_PROFILE_DEBUG_OPTION = "exec.query_profile.debug_mode";
  public static final BooleanValidator QUERY_PROFILE_DEBUG_VALIDATOR = new BooleanValidator(QUERY_PROFILE_DEBUG_OPTION);

  public static final String USE_DYNAMIC_UDFS_KEY = "exec.udf.use_dynamic";
  public static final BooleanValidator USE_DYNAMIC_UDFS = new BooleanValidator(USE_DYNAMIC_UDFS_KEY);

  public static final String QUERY_TRANSIENT_STATE_UPDATE_KEY = "exec.query.progress.update";
  public static final BooleanValidator QUERY_TRANSIENT_STATE_UPDATE = new BooleanValidator(QUERY_TRANSIENT_STATE_UPDATE_KEY);

  public static final String PERSISTENT_TABLE_UMASK = "exec.persistent_table.umask";
  public static final StringValidator PERSISTENT_TABLE_UMASK_VALIDATOR = new StringValidator(PERSISTENT_TABLE_UMASK);

  /**
   * Enables batch iterator (operator) validation. Validation is normally enabled
   * only when assertions are enabled. This option enables iterator validation even
   * if assertions are not enabled. That is, it allows iterator validation even on
   * a "production" Drill instance.
   */
  public static final String ENABLE_ITERATOR_VALIDATION_OPTION = "debug.validate_iterators";
  public static final BooleanValidator ENABLE_ITERATOR_VALIDATOR = new BooleanValidator(ENABLE_ITERATOR_VALIDATION_OPTION);

  /**
   * Boot-time config option to enable validation. Primarily used for tests.
   * If true, overrrides the above. (That is validation is done if assertions are on,
   * if the above session option is set to true, or if this config option is set to true.
   */
  public static final String ENABLE_ITERATOR_VALIDATION = "drill.exec.debug.validate_iterators";

  /**
   * When iterator validation is enabled, additionally validates the vectors in
   * each batch passed to each iterator.
   */
  public static final String ENABLE_VECTOR_VALIDATION_OPTION = "debug.validate_vectors";
  public static final BooleanValidator ENABLE_VECTOR_VALIDATOR = new BooleanValidator(ENABLE_VECTOR_VALIDATION_OPTION);

  /**
   * Boot-time config option to enable vector validation. Primarily used for
   * tests. Add the following to the command line to enable:<br>
   * <tt>-ea -Ddrill.exec.debug.validate_vectors=true</tt>
   */
  public static final String ENABLE_VECTOR_VALIDATION = "drill.exec.debug.validate_vectors";

  public static final String OPTION_DEFAULTS_ROOT = "drill.exec.options.";

  public static String bootDefaultFor(String name) {
    return OPTION_DEFAULTS_ROOT + name;
}
  /**
   * Boot-time config option provided to modify duration of the grace period.
   * Grace period is the amount of time where the drillbit accepts work after
   * the shutdown request is triggered. The primary use of grace period is to
   * avoid the race conditions caused by zookeeper delay in updating the state
   * information of the drillbit that is shutting down. So, it is advisable
   * to have a grace period that is atleast twice the amount of zookeeper
   * refresh time.
   */
  public static final String GRACE_PERIOD = "drill.exec.grace_period_ms";

  public static final String DRILL_PORT_HUNT = "drill.exec.port_hunt";

  public static final String ALLOW_LOOPBACK_ADDRESS_BINDING = "drill.exec.allow_loopback_address_binding";

}


text:
	<meta charset="UTF-8"/>
	<meta itemprop='identifier' content='184827'/>
	<meta itemprop='datePublished' content='2014-08-18'/>
	<meta itemprop='datePublished-pubid' content='105'/>

EDITAL DE PREGÂO PRESENCIAL PARA REGISTRO DE PREÇO

COMISSÃO PERMANENTE DE LICITAÇÃO

TOMADA DE PREÇOS Nº 001/2014

Ata de abertura do envelope "B" – PROPOSTA TÉCNICA referente à TOMADA DE PREÇOS Nº 01/2014, atendendo aos termos do processo n° 03/001.310/2014, que tem por objeto a P

restação dos Serviços de Engenharia de Elaboração de Plano de Mobilidade Urbana Sustentável da Cidade do Rio de Janeiro, conforme especificado no Termo de Referência

, parte integrante desta Tomada de Preços. Às 11:05 horas, do dia 15 de agosto de 2014, na sede da Secretaria Municipal de Transportes, situada na Rua Dona Mariana, 48 - 7º andar / Auditório - Botafogo, reuniu-se a Comissão Permanente de Licitação, composta pelos membros:

Ivan Fontes Escobar

, Presidente, matr. 12/152.692-0, Priscila

Fernandes Pereira

, Vice-Presidente, matr. 11/219.057-7 e Luiz Gustavo de Oliveira Barreto, Assessor Técnico, Matr. 11/156.685-0. Aberta a sessão, compareceu ao certame o representante da empresa Concremat Engenharia e Tecnologia S/A. Foi realizada abertura dos envelopes "B" das empresas 1) Consórcio PlanMobRJ – Logit Engenharia Consultiva Ltda e Oficina – Engenheiros Consultores Associados Ltda e 2) Concremat Engenharia e Tecnologia S/A sendo rubricadas todas as folhas pela comissão e pelo representante legal supramencionado.

A sessão fica suspensa aguardando o julgamento do envelope "B" pelos Assessores Técnicos designados através da Resolução "P" nº 213 de 25/06/2014, publicado no Diário Oficial de 26/06/2014 às fls. 15, A

pós esse julgamento a comissão publicará o resultado no Diário Oficial do Município do Rio de Janeiro

.

Registre-se que:

Foi convocado o assessor técnico Sr. Luiz Gustavo de Oliveira Barreto em virtude do não comparecimento do Membro da Comissão Permanente de Licitação;

Foi constatado pela Comissão que nas cópias apresentadas pelo Consórcio PlanMobRJ – Logit Engenharia Consultiva Ltda e Oficina – Engenheiros Consultores Associados Ltda e 2) Concremat Engenharia e Tecnologia S/A ficaram faltando as seguintes folhas: 117, 233, 287, 310 e 314.

Nada mais havendo a tratar, lavrou-se a presente Ata que segue assinada pelos Membros da Comissão.

redpajama_set_name: RedPajamaGithub


text:
Package.describe({
    name: '255kb:md-snackbars',
    version: '1.3.1',
    summary: 'Snackbars and Toasts based on Google\'s Material Design',
    git: 'https://github.com/255kb/md-snackbars',
    documentation: 'README.md'
});

Package.onUse(function(api) {
    api.versionsFrom('1.0');
    api.use(['jquery'], 'client');
    api.addFiles(['dist/md-snackbars.js', 'dist/md-snackbars.css'], 'client');
    api.export(['MDSnackbars']);
});


text:
<?php

namespace Sonata\CatalogBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * Orders
 */
class Orders
{
    /**
     * @var integer
     */
    private $id;

    /**
     * @var boolean
     */
    private $status;

    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set status
     *
     * @param boolean $status
     * @return Orders
     */
    public function setStatus($status)
    {
        $this->status = $status;

        return $this;
    }

    /**
     * Get status
     *
     * @return boolean
     */
    public function getStatus()
    {
        return $this->status;
    }

   /**
     * @var \Sonata\CatalogBundle\Entity\Customers
     */
    private $customers;

    /**
     * Set customers
     *
     * @param \Sonata\CatalogBundle\Entity\Customers $customers
     * @return Orders
     */
    public function setCustomers(\Sonata\CatalogBundle\Entity\Customers $customers = null)
    {
        $this->customers = $customers;

        return $this;
    }

    /**
     * Get customers
     *
     * @return \Sonata\CatalogBundle\Entity\Customers
     */
    public function getCustomers()
    {
        return $this->customers;
    }
    /**
     * @var \Doctrine\Common\Collections\Collection
     */
    private $orderitems;

    /**
     * Constructor
     */
    public function __construct()
    {
        $this->orderitems = new \Doctrine\Common\Collections\ArrayCollection();
    }

    /**
     * Add orderitems
     *
     * @param \Sonata\CatalogBundle\Entity\OrderItems $orderitems
     * @return Orders
     */
    public function addOrderitem(\Sonata\CatalogBundle\Entity\OrderItems $orderitems)
    {
        $orderitems->setOrders($this);
        $this->orderitems[] = $orderitems;

        return $this;
    }

    /**
     * Remove orderitems
     *
     * @param \Sonata\CatalogBundle\Entity\OrderItems $orderitems
     */
    public function removeOrderitem(\Sonata\CatalogBundle\Entity\OrderItems $orderitems)
    {
        $this->orderitems->removeElement($orderitems);
    }

    /**
     * Get orderitems
     *
     * @return \Doctrine\Common\Collections\Collection
     */
    public function getOrderitems()
    {
        return $this->orderitems;
    }
    /**
     * @var \Date
     */
    private $orderedAt;

    /**
     * Set orderedAt
     *
     * @param \Date $orderedAt
     * @return Orders
     */
    public function setOrderedAt($orderedAt)
    {
        $this->orderedAt = $orderedAt;

        return $this;
    }

    /**
     * Get orderedAt
     *
     * @return \Date
     */
    public function getOrderedAt()
    {
        return $this->orderedAt;
    }

}


text:
@interface LocationService ()

@property (strong, nonatomic) CLLocationManager *manager;

@end

@implementation LocationService

- (instancetype)init
{
    self = [super init];
    if (self) {
        self.manager = [[CLLocationManager alloc] init];
        self.manager.delegate = self;
    }
    return self;
}

#pragma mark - CLLocationManagerDelegate

- (void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status{

    switch (status) {
        case kCLAuthorizationStatusNotDetermined:

            [self.manager requestWhenInUseAuthorization];

            break;
        case kCLAuthorizationStatusRestricted:

            if ([self.delegate respondsToSelector:@selector(LSAuthRestricted)]) {
                [self.delegate LSAuthRestricted];
            }
            break;
        case kCLAuthorizationStatusDenied:

            if ([self.delegate respondsToSelector:@selector(LSAuthDenied)]) {
                [self.delegate LSAuthDenied];
            }
            break;
        case kCLAuthorizationStatusAuthorizedWhenInUse:
            NSLog(@"Can use current location");
            break;

        default:
            break;
    }
}

- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations{

    [self.manager stopUpdatingLocation];

    CLLocation *lastLocation = [locations lastObject];

    if (lastLocation != nil) {
        if ([self.delegate respondsToSelector:@selector(LSDidUpdateLocation:)]) {
            [self.delegate LSDidUpdateLocation:lastLocation];
        }
    }
}

- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error{
    if ([self.delegate respondsToSelector:@selector(LSDidFailLocation)]) {
        [self.delegate LSDidFailLocation];
    }
}

//MARK: - Application

- (void)startUpdatingLocation{
    [self.manager startUpdatingLocation];
}

@end


text:
import json
import logging
import os
import re
import shlex
import socket
import subprocess
import sys
import time
import traceback
import errno
import imp
import zapv2
from random import randint
from six.moves.urllib.request import urlopen
from six import binary_type

try:
    import pkg_resources
except ImportError:
    # don't hard fail since it's just used for the version check
    logging.warning('Error importing pkg_resources. Is setuptools installed?')

class ScanNotStartedException(Exception):
    pass

OLD_ZAP_CLIENT_WARNING = '''A newer version of python_owasp_zap_v2.4
 is available. Please run \'pip install -U python_owasp_zap_v2.4\' to update to
 the latest version.'''.replace('\n', '')

zap_conf_lvls = ["PASS", "IGNORE", "INFO", "WARN", "FAIL"]
zap_hooks = None

def load_custom_hooks(hooks_file=None):
    """ Loads a custom python module which modifies zap scripts behaviour
    hooks_file - a python file which defines custom hooks
    """
    global zap_hooks
    hooks_file = hooks_file if hooks_file else os.environ.get('ZAP_HOOKS', '~/.zap_hooks.py')
    hooks_file = os.path.expanduser(hooks_file)

    if not os.path.exists(hooks_file):
        logging.debug('Could not find custom hooks file at %s ' % hooks_file)
        return

    zap_hooks = imp.load_source("zap_hooks", hooks_file)

def hook(hook_name=None, **kwargs):
    """
    Decorator method for calling hook before/after method.
    Always adds a hook that runs before intercepting args and if wrap=True will create
    another hook to intercept the return.
    hook_name - name of hook for interactions, if None will use the name of the method it wrapped
    """
    after_hook = kwargs.get('wrap', False)
    def _decorator(func):
        name = func.__name__
        _hook_name = hook_name if hook_name else name
        def _wrap(*args, **kwargs):
            hook_args = list(args)
            hook_kwargs = dict(kwargs)
            args = trigger_hook(_hook_name, *hook_args, **hook_kwargs)
            args_list = list(args)
            return_data = func(*args_list, **kwargs)

            if after_hook:
                return trigger_hook('%s_wrap' % _hook_name, return_data, **hook_kwargs)
            return return_data
        return _wrap
    return _decorator

def trigger_hook(name, *args, **kwargs):
    """ Trigger execution of custom hook method if found """
    global zap_hooks
    arg_length = len(args)
    args_list = list(args)
    args = args[0] if arg_length == 1 else args

    logging.debug('Trigger hook: %s, args: %s' %  (name, arg_length))

    if not zap_hooks:
        return args
    elif not hasattr(zap_hooks, name):
        return args

    hook_fn = getattr(zap_hooks, name)
    if not callable(hook_fn):
        return args

    response = hook_fn(*args_list, **kwargs)

    # The number of args returned should match arguments passed
    if not response:
        return args
    elif arg_length == 1:
      return args
    elif (isinstance(response, list) or isinstance(response, tuple)) and len(response) != arg_length:
        return args
    return response

@hook()
def load_config(config, config_dict, config_msg, out_of_scope_dict):
    """ Loads the config file specified into:
    config_dict - a dictionary which maps plugin_ids to levels (IGNORE, WARN, FAIL)
    config_msg - a dictionary which maps plugin_ids to optional user specified descriptions
    out_of_scope_dict - a dictionary which maps plugin_ids to out of scope regexes
    """
    for line in config:
        if not line.startswith('#') and len(line) > 1:
            (key, val, optional) = line.rstrip().split('\t', 2)
            if val == 'OUTOFSCOPE':
                for plugin_id in key.split(','):
                    if plugin_id not in out_of_scope_dict:
                        out_of_scope_dict[plugin_id] = []
                    out_of_scope_dict[plugin_id].append(re.compile(optional))
            elif val not in zap_conf_lvls:
                raise ValueError("Level {0} is not a supported level: {1}".format(val, zap_conf_lvls))
            else:
                config_dict[key] = val
                if '\t' in optional:
                    (ignore, usermsg) = optional.rstrip().split('\t')
                    config_msg[key] = usermsg
                else:
                    config_msg[key] = ''
    logging.debug('Loaded config: {0}'.format(config_dict))

def is_in_scope(plugin_id, url, out_of_scope_dict):
    """ Returns True if the url is in scope for the specified plugin_id """
    if '*' in out_of_scope_dict:
        for oos_prog in out_of_scope_dict['*']:
            #print('OOS Compare ' + oos_url + ' vs ' + 'url)
            if oos_prog.match(url):
                #print('OOS Ignoring ' + str(plugin_id) + ' ' + url)
                return False
        #print 'Not in * dict'
    if plugin_id in out_of_scope_dict:
        for oos_prog in out_of_scope_dict[plugin_id]:
            #print('OOS Compare ' + oos_url + ' vs ' + 'url)
            if oos_prog.match(url):
                #print('OOS Ignoring ' + str(plugin_id) + ' ' + url)
                return False
    #print 'Not in ' + plugin_id + ' dict'
    return True

def print_rule(zap, action, alert_list, detailed_output, user_msg, in_progress_issues):
    id = alert_list[0].get('pluginId')
    if id in in_progress_issues:
        print (action + '-IN_PROGRESS: ' + alert_list[0].get('alert') + ' [' + id + '] x ' + str(len(alert_list)) + ' ' + user_msg)
        if in_progress_issues[id]["link"]:
            print ('\tProgress link: ' + in_progress_issues[id]["link"])
    else:
        print (action + '-NEW: ' + alert_list[0].get('alert') + ' [' + id + '] x ' + str(len(alert_list)) + ' ' + user_msg)
    if detailed_output:
        # Show (up to) first 5 urls, along with the response code (which we have to perform another request for)
        for alert in alert_list[0:5]:
            msg = zap.core.message(alert.get('messageId'))
            respHeader = msg['responseHeader']
            code = respHeader[respHeader.index(' ') + 1 : respHeader.index('\r\n')]
            print ('\t' + alert.get('url') + ' (' + code + ')')

def print_rules(zap, alert_dict, level, config_dict, config_msg, min_level, inc_rule, inc_extra, detailed_output, in_progress_issues):
    count = 0
    inprog_count = 0
    for key, alert_list in sorted(alert_dict.items()):
        #if (config_dict.has_key(key) and config_dict[key] == level):
        if inc_rule(config_dict, key, inc_extra):
            user_msg = ''
            if key in config_msg:
                user_msg = config_msg[key]
            if min_level <= zap_conf_lvls.index(level):
                print_rule(zap, level, alert_list, detailed_output, user_msg, in_progress_issues)
            if key in in_progress_issues:
                inprog_count += 1
            else:
                count += 1
    return trigger_hook('print_rules_wrap', count, inprog_count)

def inc_ignore_rules(config_dict, key, inc_extra):
    return (key in config_dict) and config_dict[key] == 'IGNORE'

def inc_info_rules(config_dict, key, inc_extra):
    return ((key in config_dict) and config_dict[key] == 'INFO') or ((key not in config_dict) and inc_extra)

def inc_warn_rules(config_dict, key, inc_extra):
    return ((key in config_dict) and config_dict[key] == 'WARN') or ((key not in config_dict) and inc_extra)

def inc_fail_rules(config_dict, key, inc_extra):
    return (key in config_dict) and config_dict[key] == 'FAIL'

def dump_log_file(cid):
    traceback.print_exc()
    # Unexpected issue - dump the zap.log file
    if running_in_docker():
        zap_log = '/zap/zap.out'
        if os.path.isfile(zap_log):
            with open(zap_log, 'r') as zlog:
                for line in zlog:
                    sys.stderr.write(line)
        else:
            logging.debug('Failed to find zap_log ' + zap_log)
    else:
        logging.debug('Dumping docker logs')
        subprocess.call(["docker", "logs", cid], stdout=sys.stderr)

def cp_to_docker(cid, file, dir):
    logging.debug ('Copy ' + file)
    params = ['docker', 'cp', file, cid + ':' + dir + file]
    logging.debug (subprocess.check_output(params))

def running_in_docker():
    return os.path.exists('/.dockerenv')

def add_zap_options(params, zap_options):
    if zap_options:
        for zap_opt in shlex.split(zap_options):
            params.append(zap_opt)

@hook()
def start_zap(port, extra_zap_params):
    logging.debug('Starting ZAP')
    # All of the default common params
    params = [
        'zap-x.sh', '-daemon',
        '-port', str(port),
        '-host', '0.0.0.0',
        '-config', 'api.disablekey=true',
        '-config', 'api.addrs.addr.name=.*',
        '-config', 'api.addrs.addr.regex=true']

    params.extend(extra_zap_params)

    logging.info('Params: ' + str(params))

    with open('zap.out', "w") as outfile:
        subprocess.Popen(params, stdout=outfile)

def wait_for_zap_start(zap, timeout_in_secs = 600):
    version = None
    if not timeout_in_secs:
        # if ZAP doesn't start in 10 mins then its probably not going to start
        timeout_in_secs = 600

    for x in range(0, timeout_in_secs):
        try:
            version = zap.core.version
            logging.debug('ZAP Version ' + version)
            logging.debug('Took ' + str(x) + ' seconds')
            break
        except IOError:
            time.sleep(1)

    if not version:
        raise IOError(
          errno.EIO,
          'Failed to connect to ZAP after {0} seconds'.format(timeout_in_secs))

@hook(wrap=True)
def start_docker_zap(docker_image, port, extra_zap_params, mount_dir):
    try:
        logging.debug('Pulling ZAP Docker image: ' + docker_image)
        ls_output = subprocess.check_output(['docker', 'pull', docker_image])
    except OSError as err:
        logging.warning('Failed to run docker - is it on your path?')
        raise err

    logging.debug('Starting ZAP')
    params = ['docker', 'run']

    if mount_dir:
        params.extend(['-v', mount_dir + ':/zap/wrk/:rw'])

    params.extend([
            '-u', 'zap',
            '-p', str(port) + ':' + str(port),
            '-d', docker_image,
            'zap-x.sh', '-daemon',
            '-port', str(port),
            '-host', '0.0.0.0',
            '-config', 'api.disablekey=true',
            '-config', 'api.addrs.addr.name=.*',
            '-config', 'api.addrs.addr.regex=true'])

    params.extend(extra_zap_params)

    logging.info('Params: ' + str(params))

    cid = subprocess.check_output(params).rstrip().decode('utf-8')
    logging.debug('Docker CID: ' + cid)
    return cid

def get_free_port():
    while True:
        port = randint(32768, 61000)
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        if not (sock.connect_ex(('127.0.0.1', port)) == 0):
            return port

def ipaddress_for_cid(cid):
    insp_output = subprocess.check_output(['docker', 'inspect', cid]).strip().decode('utf-8')
    #logging.debug('Docker Inspect: ' + insp_output)
    insp_json = json.loads(insp_output)
    return str(insp_json[0]['NetworkSettings']['IPAddress'])

def stop_docker(cid):
    # Close container - ignore failures
    try:
        logging.debug('Stopping Docker container')
        subprocess.check_output(['docker', 'stop', cid])
        logging.debug('Docker container stopped')
    except OSError:
        logging.warning('Docker stop failed')

    # Remove container - ignore failures
    try:
        logging.debug('Removing Docker container')
        subprocess.check_output(['docker', 'rm', cid])
        logging.debug('Docker container removed')
    except OSError:
        logging.warning('Docker rm failed')

@hook()
def zap_access_target(zap, target):
    res = zap.urlopen(target)
    if res.startswith("ZAP Error"):
        raise IOError(errno.EIO, 'ZAP failed to access: {0}'.format(target))

@hook(wrap=True)
def zap_spider(zap, target):
    logging.debug('Spider ' + target)
    spider_scan_id = zap.spider.scan(target)
    time.sleep(5)

    while (int(zap.spider.status(spider_scan_id)) < 100):
        logging.debug('Spider progress %: ' + zap.spider.status(spider_scan_id))
        time.sleep(5)
    logging.debug('Spider complete')

@hook(wrap=True)
def zap_ajax_spider(zap, target, max_time):
    logging.debug('AjaxSpider ' + target)
    if max_time:
        zap.ajaxSpider.set_option_max_duration(str(max_time))
    zap.ajaxSpider.scan(target)
    time.sleep(5)

    while (zap.ajaxSpider.status == 'running'):
        logging.debug('Ajax Spider running, found urls: ' + zap.ajaxSpider.number_of_results)
        time.sleep(5)
    logging.debug('Ajax Spider complete')

@hook(wrap=True)
def zap_active_scan(zap, target, policy):
    logging.debug('Active Scan ' + target + ' with policy ' + policy)
    ascan_scan_id = zap.ascan.scan(target, recurse=True, scanpolicyname=policy)
    try:
        int(ascan_scan_id)
    except ValueError:
        raise ScanNotStartedException('Failed to start the scan, check the log/output for more details.')
    time.sleep(5)

    while(int(zap.ascan.status(ascan_scan_id)) < 100):
        logging.debug('Active Scan progress %: ' + zap.ascan.status(ascan_scan_id))
        time.sleep(5)
    logging.debug('Active Scan complete')
    logging.debug(zap.ascan.scan_progress(ascan_scan_id))

def zap_wait_for_passive_scan(zap, timeout_in_secs = 0):
    rtc = zap.pscan.records_to_scan
    logging.debug('Records to scan...')
    time_taken = 0
    timed_out = False
    while (int(zap.pscan.records_to_scan) > 0):
        logging.debug('Records to passive scan : ' + zap.pscan.records_to_scan)
        time.sleep(2)
        time_taken += 2
        if timeout_in_secs and time_taken > timeout_in_secs:
            timed_out = True
            break
    if timed_out:
      logging.debug('Exceeded passive scan timeout')
    else:
      logging.debug('Passive scanning complete')

@hook(wrap=True)
def zap_get_alerts(zap, baseurl, blacklist, out_of_scope_dict):
    # Retrieve the alerts using paging in case there are lots of them
    st = 0
    pg = 5000
    alert_dict = {}
    alert_count = 0
    alerts = zap.core.alerts(baseurl=baseurl, start=st, count=pg)
    while len(alerts) > 0:
        logging.debug('Reading ' + str(pg) + ' alerts from ' + str(st))
        alert_count += len(alerts)
        for alert in alerts:
            plugin_id = alert.get('pluginId')
            if plugin_id in blacklist:
                continue
            if not is_in_scope(plugin_id, alert.get('url'), out_of_scope_dict):
                continue
            if alert.get('risk') == 'Informational':
                # Ignore all info alerts - some of them may have been downgraded by security annotations
                continue
            if (plugin_id not in alert_dict):
                alert_dict[plugin_id] = []
            alert_dict[plugin_id].append(alert)
        st += pg
        alerts = zap.core.alerts(start=st, count=pg)
    logging.debug('Total number of alerts: ' + str(alert_count))
    return alert_dict

def get_latest_zap_client_version():
    version_info = None

    try:
        version_info = urlopen('https://pypi.python.org/pypi/python-owasp-zap-v2.4/json', timeout=10)
    except Exception as e:
        logging.warning('Error fetching latest ZAP Python API client version: %s' % e)
        return None

    version_json = json.loads(version_info.read().decode('utf-8'))

    if 'info' not in version_json:
        logging.warning('No version found for latest ZAP Python API client.')
        return None
    if 'version' not in version_json['info']:
        logging.warning('No version found for latest ZAP Python API client.')
        return None

    return version_json['info']['version']

def check_zap_client_version():
    # No need to check ZAP Python API client while running in Docker
    if running_in_docker():
        return

    if 'pkg_resources' not in globals():  # import failed
        logging.warning('Could not check ZAP Python API client without pkg_resources.')
        return

    current_version = getattr(zapv2, '__version__', None)
    latest_version = get_latest_zap_client_version()
    parse_version = pkg_resources.parse_version
    if current_version and latest_version and \
       parse_version(current_version) < parse_version(latest_version):
        logging.warning(OLD_ZAP_CLIENT_WARNING)
    elif current_version is None:
        # the latest versions >= 0.0.9 have a __version__
        logging.warning(OLD_ZAP_CLIENT_WARNING)
    # else:
    # we're up to date or ahead / running a development build
    # or latest_version is None and the user already got a warning

def write_report(file_path, report):
    with open(file_path, mode='wb') as f:
        if not isinstance(report, binary_type):
            report = report.encode('utf-8')

        f.write(report)

@hook(wrap=True)
def zap_import_context(zap, context_file):
    res = context_id = zap.context.import_context(context_file)
    if res.startswith("ZAP Error"):
        context_id = None
        logging.error('Failed to load context file ' + context_file + ' : ' + res)
    return context_id


text:
<?php

namespace Zoba\HolidaysManagerBundle\Controller;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Zoba\HolidaysManagerBundle\Entity\ExtraTime;
use Zoba\HolidaysManagerBundle\Form\ExtraTimeType;

/**
 * ExtraTime controller.
 *
 * @Route("/extra_time_admin")
 */
class ExtraTimeController extends Controller
{
    /**
     * Lists all ExtraTime entities.
     *
     * @Route("/", name="extra_time_admin")
     * @Template()
     */
    public function indexAction()
    {
        $em = $this->getDoctrine()->getManager();

        $entities = $em->getRepository('ZobaHolidaysManagerBundle:ExtraTime')->findAll();

        return array(
            'entities' => $entities,
        );
    }

    /**
     * Finds and displays a ExtraTime entity.
     *
     * @Route("/{id}/show", name="extra_time_admin_show")
     * @Template()
     */
    public function showAction($id)
    {
        $em = $this->getDoctrine()->getManager();

        $entity = $em->getRepository('ZobaHolidaysManagerBundle:ExtraTime')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find ExtraTime entity.');
        }

        $deleteForm = $this->createDeleteForm($id);

        return array(
            'entity'      => $entity,
            'delete_form' => $deleteForm->createView(),
        );
    }

    /**
     * Displays a form to create a new ExtraTime entity.
     *
     * @Route("/new", name="extra_time_admin_new")
     * @Template()
     */
    public function newAction()
    {
        $entity = new ExtraTime();
        $form   = $this->createForm(new ExtraTimeType(), $entity);

        return array(
            'entity' => $entity,
            'form'   => $form->createView(),
        );
    }

    /**
     * Creates a new ExtraTime entity.
     *
     * @Route("/create", name="extra_time_admin_create")
     * @Method("POST")
     * @Template("ZobaHolidaysManagerBundle:ExtraTime:new.html.twig")
     */
    public function createAction(Request $request)
    {
        $entity  = new ExtraTime();
        $form = $this->createForm(new ExtraTimeType(), $entity);
        $form->bind($request);

        if ($form->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $em->persist($entity);
            $em->flush();

            return $this->redirect($this->generateUrl('extra_time_admin_show', array('id' => $entity->getId())));
        }

        return array(
            'entity' => $entity,
            'form'   => $form->createView(),
        );
    }

    /**
     * Displays a form to edit an existing ExtraTime entity.
     *
     * @Route("/{id}/edit", name="extra_time_admin_edit")
     * @Template()
     */
    public function editAction($id)
    {
        $em = $this->getDoctrine()->getManager();

        $entity = $em->getRepository('ZobaHolidaysManagerBundle:ExtraTime')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find ExtraTime entity.');
        }

        $editForm = $this->createForm(new ExtraTimeType(), $entity);
        $deleteForm = $this->createDeleteForm($id);

        return array(
            'entity'      => $entity,
            'edit_form'   => $editForm->createView(),
            'delete_form' => $deleteForm->createView(),
        );
    }

    /**
     * Edits an existing ExtraTime entity.
     *
     * @Route("/{id}/update", name="extra_time_admin_update")
     * @Method("POST")
     * @Template("ZobaHolidaysManagerBundle:ExtraTime:edit.html.twig")
     */
    public function updateAction(Request $request, $id)
    {
        $em = $this->getDoctrine()->getManager();

        $entity = $em->getRepository('ZobaHolidaysManagerBundle:ExtraTime')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find ExtraTime entity.');
        }

        $deleteForm = $this->createDeleteForm($id);
        $editForm = $this->createForm(new ExtraTimeType(), $entity);
        $editForm->bind($request);

        if ($editForm->isValid()) {
            $em->persist($entity);
            $em->flush();

            return $this->redirect($this->generateUrl('extra_time_admin_edit', array('id' => $id)));
        }

        return array(
            'entity'      => $entity,
            'edit_form'   => $editForm->createView(),
            'delete_form' => $deleteForm->createView(),
        );
    }

    /**
     * Deletes a ExtraTime entity.
     *
     * @Route("/{id}/delete", name="extra_time_admin_delete")
     * @Method("POST")
     */
    public function deleteAction(Request $request, $id)
    {
        $form = $this->createDeleteForm($id);
        $form->bind($request);

        if ($form->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $entity = $em->getRepository('ZobaHolidaysManagerBundle:ExtraTime')->find($id);

            if (!$entity) {
                throw $this->createNotFoundException('Unable to find ExtraTime entity.');
            }

            $em->remove($entity);
            $em->flush();
        }

        return $this->redirect($this->generateUrl('extra_time_admin'));
    }

    private function createDeleteForm($id)
    {
        return $this->createFormBuilder(array('id' => $id))
            ->add('id', 'hidden')
            ->getForm()
        ;
    }
}


text:
// 默认函数参数相关
!function(BasicAssignmentTag){

this.DefaultArgumentExpression = function(ArgumentExpression){
	/**
	 * 省略参数表达式
	 * @param {Context} context - 语法标签上下文
	 */
	function DefaultArgumentExpression(context){
		ArgumentExpression.call(this, context);
	};
	DefaultArgumentExpression = new Rexjs(DefaultArgumentExpression, ArgumentExpression);

	DefaultArgumentExpression.props({
		assignment: null,
		/**
		 * 提取表达式文本内容
		 * @param {ContentBuilder} contentBuilder - 内容生成器
		 * @param {ContentBuilder} anotherBuilder - 另一个内容生成器,一般用于副内容的生成或记录
		 */
		extractTo: function(contentBuilder, anotherBuilder){
			// 如果需要编译
			if(config.es6Base){
				var context = this.context;

				// 追加参数名至 contentBuilder
				contentBuilder.appendContext(context);

				// 追加参数名至 anotherBuilder
				anotherBuilder.appendContext(context);
				// 判断是否为 undefined
				anotherBuilder.appendString("===void 0&&(");

				// 将赋值表达式提取至临时生成器
				this.assignment.extractTo(anotherBuilder);
				// 再对临时生成器添加分号
				anotherBuilder.appendString(");");
				return;
			}

			// 直接正式提取赋值表达式
			this.assignment.extractTo(contentBuilder);
		}
	});

	return DefaultArgumentExpression;
}(
	this.ArgumentExpression
);

this.ArgumentAssignmentStatement = function(){
	/**
	 * 默认参数赋值语句
	 * @param {Statements} statements - 该语句将要所处的语句块
	 */
	function ArgumentAssignmentStatement(statements){
		ECMAScriptStatement.call(this, statements);
	};
	ArgumentAssignmentStatement = new Rexjs(ArgumentAssignmentStatement, ECMAScriptStatement);

	ArgumentAssignmentStatement.props({
		/**
		 * 捕获处理异常
		 * @param {SyntaxParser} parser - 语法解析器
		 * @param {Context} context - 语法标签上下文
		 */
		catch: function(parser, context){
			// 跳出语句并设置 assignment
			this.out().assignment = this.expression;
		},
		/**
		 * 尝试处理异常
		 * @param {SyntaxParser} parser - 语法解析器
		 * @param {Context} context - 语法标签上下文
		 */
		try: function(parser, context){
			// 如果是逗号
			if(context.content === ","){
				// 跳出语句并设置 assignment
				this.out().assignment = this.expression;
			}
		}
	});

	return ArgumentAssignmentStatement;
}();

this.ArgumentAssignmentTag = function(DefaultArgumentExpression, ArgumentAssignmentStatement, visitor){
	/**
	 * 默认参数赋值标签
	 * @param {Number} _type - 标签类型
	 */
	function ArgumentAssignmentTag(_type){
		BasicAssignmentTag.call(this, _type);
	};
	ArgumentAssignmentTag = new Rexjs(ArgumentAssignmentTag, BasicAssignmentTag);

	ArgumentAssignmentTag.props({
		/**
		 * 标签访问器
		 * @param {SyntaxParser} parser - 语法解析器
		 * @param {Context} context - 标签上下文
		 * @param {Statement} statement - 当前语句
		 * @param {Statements} statements - 当前语句块
		 */
		visitor: function(parser, context, statement, statements){
			var expression = statement.expression;

			// 设置当前表达式
			statement.expression = new DefaultArgumentExpression(expression.context);

			(
				// 初始化参数赋值语句
				statements.statement = statement = new ArgumentAssignmentStatement(statements)
			)
			// 设置 expression
			.expression = expression;

			// 调用父类方法
			visitor.call(this, parser, context, statement, statements);
		}
	});

	return ArgumentAssignmentTag;
}(
	this.DefaultArgumentExpression,
	this.ArgumentAssignmentStatement,
	BasicAssignmentTag.prototype.visitor
);

}.call(
	this,
	this.BasicAssignmentTag
);


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using AdvancedStringBuilder;
using LibSassHost;
using LibSassHost.Helpers;
using LshIndentType = LibSassHost.IndentType;
using LshLineFeedType = LibSassHost.LineFeedType;

using BundleTransformer.Core;
using BundleTransformer.Core.Assets;
using BundleTransformer.Core.FileSystem;
using BundleTransformer.Core.Resources;
using BundleTransformer.Core.Translators;
using BundleTransformer.Core.Utilities;
using CoreStrings = BundleTransformer.Core.Resources.Strings;

using BundleTransformer.SassAndScss.Configuration;
using BundleTransformer.SassAndScss.Internal;
using BtIndentType = BundleTransformer.SassAndScss.IndentType;
using BtLineFeedType = BundleTransformer.SassAndScss.LineFeedType;

namespace BundleTransformer.SassAndScss.Translators
{
	/// <summary>
	/// Translator that responsible for translation of Sass or SCSS code to CSS code
	/// </summary>
	public sealed class SassAndScssTranslator : TranslatorWithNativeMinificationBase
	{
		/// <summary>
		/// Name of output code type
		/// </summary>
		const string OUTPUT_CODE_TYPE = "CSS";

		/// <summary>
		/// Synchronizer of Sass compiler's initialization
		/// </summary>
		private static readonly object _initializationSynchronizer = new object();

		/// <summary>
		/// Flag that indicates if the Sass compiler is initialized
		/// </summary>
		private static bool _initialized;

		/// <summary>
		/// Gets or sets a list of include paths
		/// </summary>
		public IList<string> IncludePaths
		{
			get;
			set;
		}

		/// <summary>
		/// Gets or sets a indent type
		/// </summary>
		public BtIndentType IndentType
		{
			get;
			set;
		}

		/// <summary>
		/// Gets or sets a number of spaces or tabs to be used for indentation
		/// </summary>
		public int IndentWidth
		{
			get;
			set;
		}

		/// <summary>
		/// Gets or sets a line feed type
		/// </summary>
		public BtLineFeedType LineFeedType
		{
			get;
			set;
		}

		/// <summary>
		/// Gets or sets a precision for fractional numbers
		/// </summary>
		public int Precision
		{
			get;
			set;
		}

		/// <summary>
		/// Gets or sets a flag for whether to emit comments in the generated CSS
		/// indicating the corresponding source line
		/// </summary>
		public bool SourceComments
		{
			get;
			set;
		}

		/// <summary>
		/// Constructs an instance of Sass and SCSS translator
		/// </summary>
		public SassAndScssTranslator()
			: this(BundleTransformerContext.Current.Configuration.GetSassAndScssSettings())
		{ }

		/// <summary>
		/// Constructs an instance of Sass and SCSS translator
		/// </summary>
		/// <param name="sassAndScssConfig">Configuration settings of Sass and SCSS translator</param>
		public SassAndScssTranslator(SassAndScssSettings sassAndScssConfig)
		{
			UseNativeMinification = sassAndScssConfig.UseNativeMinification;
			IncludePaths = sassAndScssConfig.IncludePaths
				.Cast<IncludedPathRegistration>()
				.Select(p => p.Path)
				.ToList()
				;
			IndentType = sassAndScssConfig.IndentType;
			IndentWidth = sassAndScssConfig.IndentWidth;
			LineFeedType = sassAndScssConfig.LineFeedType;
			Precision = sassAndScssConfig.Precision;
			SourceComments = sassAndScssConfig.SourceComments;
		}

		/// <summary>
		/// Sets a virtual file system wrapper
		/// </summary>
		/// <param name="virtualFileSystemWrapper">Virtual file system wrapper</param>
		public static void SetVirtualFileSystemWrapper(IVirtualFileSystemWrapper virtualFileSystemWrapper)
		{
			if (virtualFileSystemWrapper == null)
			{
				throw new ArgumentNullException(
					nameof(virtualFileSystemWrapper),
					string.Format(CoreStrings.Common_ArgumentIsNull, nameof(virtualFileSystemWrapper))
				);
			}

			IFileManager virtualFileManager = new VirtualFileManager(virtualFileSystemWrapper);

			lock (_initializationSynchronizer)
			{
				SassCompiler.FileManager = virtualFileManager;
				_initialized = true;
			}
		}

		/// <summary>
		/// Initializes a Sass compiler
		/// </summary>
		private static void Initialize()
		{
			if (!_initialized)
			{
				lock (_initializationSynchronizer)
				{
					if (!_initialized)
					{
						IVirtualFileSystemWrapper virtualFileSystemWrapper =
							BundleTransformerContext.Current.FileSystem.GetVirtualFileSystemWrapper();
						IFileManager virtualFileManager = new VirtualFileManager(virtualFileSystemWrapper);

						SassCompiler.FileManager = virtualFileManager;
						_initialized = true;
					}
				}
			}
		}

		/// <summary>
		/// Translates a code of asset written on Sass or SCSS to CSS code
		/// </summary>
		/// <param name="asset">Asset with code written on Sass or SCSS</param>
		/// <returns>Asset with translated code</returns>
		public override IAsset Translate(IAsset asset)
		{
			if (asset == null)
			{
				throw new ArgumentNullException(
					nameof(asset),
					string.Format(Strings.Common_ArgumentIsNull, nameof(asset))
				);
			}

			Initialize();

			bool enableNativeMinification = NativeMinificationEnabled;
			CompilationOptions options = CreateCompilationOptions(enableNativeMinification);

			InnerTranslate(asset, options, enableNativeMinification);

			return asset;
		}

		/// <summary>
		/// Translates a code of assets written on Sass or SCSS to CSS code
		/// </summary>
		/// <param name="assets">Set of assets with code written on Sass or SCSS</param>
		/// <returns>Set of assets with translated code</returns>
		public override IList<IAsset> Translate(IList<IAsset> assets)
		{
			if (assets == null)
			{
				throw new ArgumentNullException(
					nameof(assets),
					string.Format(Strings.Common_ArgumentIsNull, nameof(assets))
				);
			}

			if (assets.Count == 0)
			{
				return assets;
			}

			var assetsToProcessing = assets.Where(a => a.AssetTypeCode == Constants.AssetTypeCode.Sass
				|| a.AssetTypeCode == Constants.AssetTypeCode.Scss).ToList();
			if (assetsToProcessing.Count == 0)
			{
				return assets;
			}

			Initialize();

			bool enableNativeMinification = NativeMinificationEnabled;
			CompilationOptions options = CreateCompilationOptions(enableNativeMinification);

			foreach (var asset in assetsToProcessing)
			{
				InnerTranslate(asset, options, enableNativeMinification);
			}

			return assets;
		}

		private void InnerTranslate(IAsset asset, CompilationOptions sassOptions, bool enableNativeMinification)
		{
			string assetTypeName = asset.AssetTypeCode == Constants.AssetTypeCode.Sass ? "Sass" : "SCSS";
			string newContent;
			string assetUrl = asset.Url;
			IList<string> dependencies;

			try
			{
				CompilationResult result = SassCompiler.Compile(asset.Content, assetUrl, options: sassOptions);
				newContent = result.CompiledContent;
				dependencies = result.IncludedFilePaths;
			}
			catch (SassCompilationException e)
			{
				string errorDetails = SassErrorHelpers.GenerateErrorDetails(e, true);

				var stringBuilderPool = StringBuilderPool.Shared;
				StringBuilder errorMessageBuilder = stringBuilderPool.Rent();
				errorMessageBuilder.AppendLine(e.Message);
				errorMessageBuilder.AppendLine();
				errorMessageBuilder.Append(errorDetails);

				string errorMessage = errorMessageBuilder.ToString();
				stringBuilderPool.Return(errorMessageBuilder);

				throw new AssetTranslationException(
					string.Format(CoreStrings.Translators_TranslationSyntaxError,
						assetTypeName, OUTPUT_CODE_TYPE, assetUrl, errorMessage));
			}
			catch (Exception e)
			{
				throw new AssetTranslationException(
					string.Format(CoreStrings.Translators_TranslationFailed,
						assetTypeName, OUTPUT_CODE_TYPE, assetUrl, e.Message), e);
			}

			asset.Content = newContent;
			asset.Minified = enableNativeMinification;
			asset.RelativePathsResolved = false;
			asset.VirtualPathDependencies = dependencies;
		}

		/// <summary>
		/// Creates a compilation options
		/// </summary>
		/// <param name="enableNativeMinification">Flag that indicating to use of native minification</param>
		/// <returns>Compilation options</returns>
		private CompilationOptions CreateCompilationOptions(bool enableNativeMinification)
		{
			IList<string> processedIncludePaths = IncludePaths
					.Select(p => SassCompiler.FileManager.ToAbsolutePath(p))
					.ToList()
					;

			var options = new CompilationOptions
			{
				IncludePaths = processedIncludePaths,
				IndentType = Utils.GetEnumFromOtherEnum<BtIndentType, LshIndentType>(IndentType),
				IndentWidth = IndentWidth,
				LineFeedType = Utils.GetEnumFromOtherEnum<BtLineFeedType, LshLineFeedType>(LineFeedType),
				OutputStyle = enableNativeMinification ? OutputStyle.Compressed : OutputStyle.Expanded,
				Precision = Precision,
				SourceComments = SourceComments
			};

			return options;
		}
	}
}


text:
package duy.phuong.handnote.MyView.DrawingView;

import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Point;
import android.graphics.Rect;

import java.util.ArrayList;

/**
 * Created by Phuong on 27/01/2016.
 */
public class MyPath {
    private ArrayList<Point> mListPoint;
    private Rect mRect;
    private boolean mChecked;
    private int mColor;
    private Bitmap mBitmap;
    public Canvas mCanvas;

    public MyPath(ArrayList<Point> ListPoint) {
        this.mListPoint = ListPoint;
        mChecked = false;
    }

    public void createBitmap(int w, int h) {
        mBitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
        mCanvas = new Canvas(mBitmap);
    }

    public Bitmap getBitmap() {
        return mBitmap;
    }

    public int getColor() {
        return mColor;
    }

    public void setColor(int mColor) {
        this.mColor = mColor;
    }

    public boolean isChecked() {
        return mChecked;
    }

    public void setChecked(boolean Checked) {
        this.mChecked = Checked;
    }

    public ArrayList<Point> getListPoint() {
        return mListPoint;
    }

    public Rect getRect() {
        return mRect;
    }

    public void initRect() {
        int left = mListPoint.get(0).x;
        int right = mListPoint.get(0).x;
        int top = mListPoint.get(0).y;
        int bot = mListPoint.get(0).y;

        for (int i = 1; i < mListPoint.size(); i++) {
            Point point = mListPoint.get(i);
            if (point.x < left) {
                left = point.x;
            }
            if (point.x > right) {
                right = point.x;
            }
            if (point.y < top) {
                top = point.y;
            }
            if (point.y > bot) {
                bot = point.y;
            }
        }

        mRect = new Rect(left, top, right, bot);
    }

    public boolean isIntersect(MyPath myPath) {
        if (myPath != null) {
            Bitmap bitmap = myPath.getBitmap();
            if (mBitmap.getWidth() == bitmap.getWidth() && mBitmap.getHeight() == bitmap.getHeight()) {
                int width = bitmap.getWidth(), height = bitmap.getHeight();
                if (mRect != null && myPath.getRect() != null) {
                    int top = (mRect.top < myPath.getRect().top) ? mRect.top : myPath.getRect().top;
                    top = (top < 0) ? 0 : top;
                    int right = (mRect.right > myPath.getRect().right) ? mRect.right : myPath.getRect().right;
                    right = (right > width - 1) ? width - 1 : right;
                    int bot = (mRect.bottom > myPath.getRect().bottom) ? mRect.bottom : myPath.getRect().bottom;
                    bot = (bot > height - 1) ? height - 1 : bot;
                    int left = (mRect.left < myPath.getRect().left) ? mRect.left : myPath.getRect().left;
                    left = (left < 0) ? 0 : left;

                    for (int i = left; i <= right; i++)
                        for (int j = top; j <= bot; j++) {
                            if (mBitmap.getPixel(i, j) == Color.BLACK && bitmap.getPixel(i, j) == Color.BLACK) {
                                return true;
                            }
                        }
                }
            }
        }

        return false;
    }
}


text:
/**
 *     This code was auto-generated by a tool.
 *
 *     Changes to this file may cause incorrect behavior and will be lost if
 *     the code is regenerated.
*/
package com.mozu.test.framework.datafactory;

import java.util.List;
import java.util.HashMap;
import java.util.ArrayList;
import org.apache.http.HttpStatus;
import org.joda.time.DateTime;
import com.mozu.api.ApiException;
import com.mozu.api.ApiContext;
import com.mozu.test.framework.core.TestFailException;
import com.mozu.api.resources.content.DocumentTypeResource;

/** <summary>
 * Use the Document Types resource to view the document types supplied by the Content API.
 * </summary>
 */
public class DocumentTypeFactory
{

	public static com.mozu.api.contracts.content.DocumentTypeCollection getDocumentTypes(ApiContext apiContext, com.mozu.api.DataViewMode dataViewMode, int expectedCode) throws Exception
	{
		return getDocumentTypes(apiContext, dataViewMode,  null,  null,  null, expectedCode);
	}

	public static com.mozu.api.contracts.content.DocumentTypeCollection getDocumentTypes(ApiContext apiContext, com.mozu.api.DataViewMode dataViewMode, Integer pageSize, Integer startIndex, String responseFields, int expectedCode) throws Exception
	{
		com.mozu.api.contracts.content.DocumentTypeCollection returnObj = new com.mozu.api.contracts.content.DocumentTypeCollection();
		DocumentTypeResource resource = new DocumentTypeResource(apiContext, dataViewMode);
		try
		{
			returnObj = resource.getDocumentTypes( pageSize,  startIndex,  responseFields);
		}
		catch (ApiException e)
		{
			if(e.getHttpStatusCode() != expectedCode)
				throw new TestFailException("" + e.getHttpStatusCode(), Thread.currentThread().getStackTrace()[2].getMethodName(), "" + expectedCode, "");
			else
				return null;
		}
		if(expectedCode != 304 && !(expectedCode >= 200 && expectedCode <= 300) && !(expectedCode == HttpStatus.SC_NOT_FOUND && returnObj == null))
			throw new TestFailException("304 or between 200 and 300", Thread.currentThread().getStackTrace()[2].getMethodName(), "" + expectedCode, "");
		return returnObj;
	}

	public static com.mozu.api.contracts.content.DocumentType getDocumentType(ApiContext apiContext, com.mozu.api.DataViewMode dataViewMode, String documentTypeName, int expectedCode) throws Exception
	{
		return getDocumentType(apiContext, dataViewMode,  documentTypeName,  null, expectedCode);
	}

	public static com.mozu.api.contracts.content.DocumentType getDocumentType(ApiContext apiContext, com.mozu.api.DataViewMode dataViewMode, String documentTypeName, String responseFields, int expectedCode) throws Exception
	{
		com.mozu.api.contracts.content.DocumentType returnObj = new com.mozu.api.contracts.content.DocumentType();
		DocumentTypeResource resource = new DocumentTypeResource(apiContext, dataViewMode);
		try
		{
			returnObj = resource.getDocumentType( documentTypeName,  responseFields);
		}
		catch (ApiException e)
		{
			if(e.getHttpStatusCode() != expectedCode)
				throw new TestFailException("" + e.getHttpStatusCode(), Thread.currentThread().getStackTrace()[2].getMethodName(), "" + expectedCode, "");
			else
				return null;
		}
		if(expectedCode != 304 && !(expectedCode >= 200 && expectedCode <= 300) && !(expectedCode == HttpStatus.SC_NOT_FOUND && returnObj == null))
			throw new TestFailException("304 or between 200 and 300", Thread.currentThread().getStackTrace()[2].getMethodName(), "" + expectedCode, "");
		return returnObj;
	}

	public static com.mozu.api.contracts.content.DocumentType createDocumentType(ApiContext apiContext, com.mozu.api.DataViewMode dataViewMode, com.mozu.api.contracts.content.DocumentType documentType, int expectedCode) throws Exception
	{
		return createDocumentType(apiContext, dataViewMode,  documentType,  null, expectedCode);
	}

	public static com.mozu.api.contracts.content.DocumentType createDocumentType(ApiContext apiContext, com.mozu.api.DataViewMode dataViewMode, com.mozu.api.contracts.content.DocumentType documentType, String responseFields, int expectedCode) throws Exception
	{
		com.mozu.api.contracts.content.DocumentType returnObj = new com.mozu.api.contracts.content.DocumentType();
		DocumentTypeResource resource = new DocumentTypeResource(apiContext, dataViewMode);
		try
		{
			returnObj = resource.createDocumentType( documentType,  responseFields);
		}
		catch (ApiException e)
		{
			if(e.getHttpStatusCode() != expectedCode)
				throw new TestFailException("" + e.getHttpStatusCode(), Thread.currentThread().getStackTrace()[2].getMethodName(), "" + expectedCode, "");
			else
				return null;
		}
		if(expectedCode != 304 && !(expectedCode >= 200 && expectedCode <= 300) && !(expectedCode == HttpStatus.SC_NOT_FOUND && returnObj == null))
			throw new TestFailException("304 or between 200 and 300", Thread.currentThread().getStackTrace()[2].getMethodName(), "" + expectedCode, "");
		return returnObj;
	}

	public static com.mozu.api.contracts.content.DocumentType updateDocumentType(ApiContext apiContext, com.mozu.api.contracts.content.DocumentType documentType, String documentTypeName, int expectedCode) throws Exception
	{
		return updateDocumentType(apiContext,  documentType,  documentTypeName,  null, expectedCode);
	}

	public static com.mozu.api.contracts.content.DocumentType updateDocumentType(ApiContext apiContext, com.mozu.api.contracts.content.DocumentType documentType, String documentTypeName, String responseFields, int expectedCode) throws Exception
	{
		com.mozu.api.contracts.content.DocumentType returnObj = new com.mozu.api.contracts.content.DocumentType();
		DocumentTypeResource resource = new DocumentTypeResource(apiContext);
		try
		{
			returnObj = resource.updateDocumentType( documentType,  documentTypeName,  responseFields);
		}
		catch (ApiException e)
		{
			if(e.getHttpStatusCode() != expectedCode)
				throw new TestFailException("" + e.getHttpStatusCode(), Thread.currentThread().getStackTrace()[2].getMethodName(), "" + expectedCode, "");
			else
				return null;
		}
		if(expectedCode != 304 && !(expectedCode >= 200 && expectedCode <= 300) && !(expectedCode == HttpStatus.SC_NOT_FOUND && returnObj == null))
			throw new TestFailException("304 or between 200 and 300", Thread.currentThread().getStackTrace()[2].getMethodName(), "" + expectedCode, "");
		return returnObj;
	}

}