text:
package org.apache.kafka.connect.runtime;

import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerConfig;
import org.apache.kafka.common.MetricName;
import org.apache.kafka.common.config.ConfigValue;
import org.apache.kafka.common.config.provider.ConfigProvider;
import org.apache.kafka.common.metrics.Sensor;
import org.apache.kafka.common.metrics.stats.Frequencies;
import org.apache.kafka.common.metrics.stats.Total;
import org.apache.kafka.common.utils.Time;
import org.apache.kafka.common.utils.Utils;
import org.apache.kafka.connect.connector.Connector;
import org.apache.kafka.connect.connector.ConnectorContext;
import org.apache.kafka.connect.connector.Task;
import org.apache.kafka.connect.connector.policy.ConnectorClientConfigOverridePolicy;
import org.apache.kafka.connect.connector.policy.ConnectorClientConfigRequest;
import org.apache.kafka.connect.errors.ConnectException;
import org.apache.kafka.connect.health.ConnectorType;
import org.apache.kafka.connect.runtime.ConnectMetrics.LiteralSupplier;
import org.apache.kafka.connect.runtime.ConnectMetrics.MetricGroup;
import org.apache.kafka.connect.runtime.distributed.ClusterConfigState;
import org.apache.kafka.connect.runtime.errors.DeadLetterQueueReporter;
import org.apache.kafka.connect.runtime.errors.ErrorHandlingMetrics;
import org.apache.kafka.connect.runtime.errors.ErrorReporter;
import org.apache.kafka.connect.runtime.errors.LogReporter;
import org.apache.kafka.connect.runtime.errors.RetryWithToleranceOperator;
import org.apache.kafka.connect.runtime.isolation.Plugins;
import org.apache.kafka.connect.runtime.isolation.Plugins.ClassLoaderUsage;
import org.apache.kafka.connect.sink.SinkRecord;
import org.apache.kafka.connect.sink.SinkTask;
import org.apache.kafka.connect.source.SourceRecord;
import org.apache.kafka.connect.source.SourceTask;
import org.apache.kafka.connect.storage.Converter;
import org.apache.kafka.connect.storage.HeaderConverter;
import org.apache.kafka.connect.storage.OffsetBackingStore;
import org.apache.kafka.connect.storage.OffsetStorageReader;
import org.apache.kafka.connect.storage.OffsetStorageReaderImpl;
import org.apache.kafka.connect.storage.OffsetStorageWriter;
import org.apache.kafka.connect.util.ConnectorTaskId;
import org.apache.kafka.connect.util.LoggingContext;
import org.apache.kafka.connect.util.SinkUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.stream.Collectors;

/**
 *

 * Worker runs a (dynamic) set of tasks in a set of threads, doing the work of actually moving
 * data to/from Kafka.
 *

 *

 * Since each task has a dedicated thread, this is mainly just a container for them.
 *

 */
public class Worker {
    private static final Logger log = LoggerFactory.getLogger(Worker.class);

    protected Herder herder;
    private final ExecutorService executor;
    private final Time time;
    private final String workerId;
    private final Plugins plugins;
    private final ConnectMetrics metrics;
    private final WorkerMetricsGroup workerMetricsGroup;
    private final WorkerConfig config;
    private final Converter internalKeyConverter;
    private final Converter internalValueConverter;
    private final OffsetBackingStore offsetBackingStore;

    private final ConcurrentMap<String, WorkerConnector> connectors = new ConcurrentHashMap<>();
    private final ConcurrentMap<ConnectorTaskId, WorkerTask> tasks = new ConcurrentHashMap<>();
    private SourceTaskOffsetCommitter sourceTaskOffsetCommitter;
    private WorkerConfigTransformer workerConfigTransformer;
    private ConnectorClientConfigOverridePolicy connectorClientConfigOverridePolicy;

    public Worker(
        String workerId,
        Time time,
        Plugins plugins,
        WorkerConfig config,
        OffsetBackingStore offsetBackingStore,
        ConnectorClientConfigOverridePolicy connectorClientConfigOverridePolicy) {
        this(workerId, time, plugins, config, offsetBackingStore, Executors.newCachedThreadPool(), connectorClientConfigOverridePolicy);
    }

    @SuppressWarnings("deprecation")
    Worker(
            String workerId,
            Time time,
            Plugins plugins,
            WorkerConfig config,
            OffsetBackingStore offsetBackingStore,
            ExecutorService executorService,
            ConnectorClientConfigOverridePolicy connectorClientConfigOverridePolicy
    ) {
        this.metrics = new ConnectMetrics(workerId, config, time);
        this.executor = executorService;
        this.workerId = workerId;
        this.time = time;
        this.plugins = plugins;
        this.config = config;
        this.connectorClientConfigOverridePolicy = connectorClientConfigOverridePolicy;
        this.workerMetricsGroup = new WorkerMetricsGroup(metrics);

        // Internal converters are required properties, thus getClass won't return null.
        this.internalKeyConverter = plugins.newConverter(
                config,
                WorkerConfig.INTERNAL_KEY_CONVERTER_CLASS_CONFIG,
                ClassLoaderUsage.PLUGINS
        );
        this.internalValueConverter = plugins.newConverter(
                config,
                WorkerConfig.INTERNAL_VALUE_CONVERTER_CLASS_CONFIG,
                ClassLoaderUsage.PLUGINS
        );

        this.offsetBackingStore = offsetBackingStore;
        this.offsetBackingStore.configure(config);

        this.workerConfigTransformer = initConfigTransformer();

    }

    private WorkerConfigTransformer initConfigTransformer() {
        final List<String> providerNames = config.getList(WorkerConfig.CONFIG_PROVIDERS_CONFIG);
        Map<String, ConfigProvider> providerMap = new HashMap<>();
        for (String providerName : providerNames) {
            ConfigProvider configProvider = plugins.newConfigProvider(
                    config,
                    WorkerConfig.CONFIG_PROVIDERS_CONFIG + "." + providerName,
                    ClassLoaderUsage.PLUGINS
            );
            providerMap.put(providerName, configProvider);
        }
        return new WorkerConfigTransformer(this, providerMap);
    }

    public WorkerConfigTransformer configTransformer() {
        return workerConfigTransformer;
    }

    protected Herder herder() {
        return herder;
    }

    /**
     * Start worker.
     */
    public void start() {
        log.info("Worker starting");

        offsetBackingStore.start();
        sourceTaskOffsetCommitter = new SourceTaskOffsetCommitter(config);

        log.info("Worker started");
    }

    /**
     * Stop worker.
     */
    public void stop() {
        log.info("Worker stopping");

        long started = time.milliseconds();
        long limit = started + config.getLong(WorkerConfig.TASK_SHUTDOWN_GRACEFUL_TIMEOUT_MS_CONFIG);

        if (!connectors.isEmpty()) {
            log.warn("Shutting down connectors {} uncleanly; herder should have shut down connectors before the Worker is stopped", connectors.keySet());
            stopConnectors();
        }

        if (!tasks.isEmpty()) {
            log.warn("Shutting down tasks {} uncleanly; herder should have shut down tasks before the Worker is stopped", tasks.keySet());
            stopAndAwaitTasks();
        }

        long timeoutMs = limit - time.milliseconds();
        sourceTaskOffsetCommitter.close(timeoutMs);

        offsetBackingStore.stop();
        metrics.stop();

        log.info("Worker stopped");

        workerMetricsGroup.close();
    }

    /**
     * Start a connector managed by this worker.
     *
     * @param connName the connector name.
     * @param connProps the properties of the connector.
     * @param ctx the connector runtime context.
     * @param statusListener a listener for the runtime status transitions of the connector.
     * @param initialState the initial state of the connector.
     * @return true if the connector started successfully.
     */
    public boolean startConnector(
            String connName,
            Map<String, String> connProps,
            ConnectorContext ctx,
            ConnectorStatus.Listener statusListener,
            TargetState initialState
    ) {
        try (LoggingContext loggingContext = LoggingContext.forConnector(connName)) {
            if (connectors.containsKey(connName))
                throw new ConnectException("Connector with name " + connName + " already exists");

            final WorkerConnector workerConnector;
            ClassLoader savedLoader = plugins.currentThreadLoader();
            try {
                final ConnectorConfig connConfig = new ConnectorConfig(plugins, connProps);
                final String connClass = connConfig.getString(ConnectorConfig.CONNECTOR_CLASS_CONFIG);
                log.info("Creating connector {} of type {}", connName, connClass);
                final Connector connector = plugins.newConnector(connClass);
                workerConnector = new WorkerConnector(connName, connector, ctx, metrics, statusListener);
                log.info("Instantiated connector {} with version {} of type {}", connName, connector.version(), connector.getClass());
                savedLoader = plugins.compareAndSwapLoaders(connector);
                workerConnector.initialize(connConfig);
                workerConnector.transitionTo(initialState);
                Plugins.compareAndSwapLoaders(savedLoader);
            } catch (Throwable t) {
                log.error("Failed to start connector {}", connName, t);
                // Can't be put in a finally block because it needs to be swapped before the call on
                // statusListener
                Plugins.compareAndSwapLoaders(savedLoader);
                workerMetricsGroup.recordConnectorStartupFailure();
                statusListener.onFailure(connName, t);
                return false;
            }

            WorkerConnector existing = connectors.putIfAbsent(connName, workerConnector);
            if (existing != null)
                throw new ConnectException("Connector with name " + connName + " already exists");

            log.info("Finished creating connector {}", connName);
            workerMetricsGroup.recordConnectorStartupSuccess();
        }
        return true;
    }

    /**
     * Return true if the connector associated with this worker is a sink connector.
     *
     * @param connName the connector name.
     * @return true if the connector belongs to the worker and is a sink connector.
     * @throws ConnectException if the worker does not manage a connector with the given name.
     */
    public boolean isSinkConnector(String connName) {
        WorkerConnector workerConnector = connectors.get(connName);
        if (workerConnector == null)
            throw new ConnectException("Connector " + connName + " not found in this worker.");

        ClassLoader savedLoader = plugins.currentThreadLoader();
        try {
            savedLoader = plugins.compareAndSwapLoaders(workerConnector.connector());
            return workerConnector.isSinkConnector();
        } finally {
            Plugins.compareAndSwapLoaders(savedLoader);
        }
    }

    /**
     * Get a list of updated task properties for the tasks of this connector.
     *
     * @param connName the connector name.
     * @return a list of updated tasks properties.
     */
    public List<Map<String, String>> connectorTaskConfigs(String connName, ConnectorConfig connConfig) {
        List<Map<String, String>> result = new ArrayList<>();
        try (LoggingContext loggingContext = LoggingContext.forConnector(connName)) {
            log.trace("Reconfiguring connector tasks for {}", connName);

            WorkerConnector workerConnector = connectors.get(connName);
            if (workerConnector == null)
                throw new ConnectException("Connector " + connName + " not found in this worker.");

            int maxTasks = connConfig.getInt(ConnectorConfig.TASKS_MAX_CONFIG);
            Map<String, String> connOriginals = connConfig.originalsStrings();

            Connector connector = workerConnector.connector();
            ClassLoader savedLoader = plugins.currentThreadLoader();
            try {
                savedLoader = plugins.compareAndSwapLoaders(connector);
                String taskClassName = connector.taskClass().getName();
                for (Map<String, String> taskProps : connector.taskConfigs(maxTasks)) {
                    // Ensure we don't modify the connector's copy of the config
                    Map<String, String> taskConfig = new HashMap<>(taskProps);
                    taskConfig.put(TaskConfig.TASK_CLASS_CONFIG, taskClassName);
                    if (connOriginals.containsKey(SinkTask.TOPICS_CONFIG)) {
                        taskConfig.put(SinkTask.TOPICS_CONFIG, connOriginals.get(SinkTask.TOPICS_CONFIG));
                    }
                    if (connOriginals.containsKey(SinkTask.TOPICS_REGEX_CONFIG)) {
                        taskConfig.put(SinkTask.TOPICS_REGEX_CONFIG, connOriginals.get(SinkTask.TOPICS_REGEX_CONFIG));
                    }
                    result.add(taskConfig);
                }
            } finally {
                Plugins.compareAndSwapLoaders(savedLoader);
            }
        }

        return result;
    }

    private void stopConnectors() {
        // Herder is responsible for stopping connectors. This is an internal method to sequentially
        // stop connectors that have not explicitly been stopped.
        for (String connector: connectors.keySet())
            stopConnector(connector);
    }

    /**
     * Stop a connector managed by this worker.
     *
     * @param connName the connector name.
     * @return true if the connector belonged to this worker and was successfully stopped.
     */
    public boolean stopConnector(String connName) {
        try (LoggingContext loggingContext = LoggingContext.forConnector(connName)) {
            log.info("Stopping connector {}", connName);

            WorkerConnector workerConnector = connectors.remove(connName);
            if (workerConnector == null) {
                log.warn("Ignoring stop request for unowned connector {}", connName);
                return false;
            }

            ClassLoader savedLoader = plugins.currentThreadLoader();
            try {
                savedLoader = plugins.compareAndSwapLoaders(workerConnector.connector());
                workerConnector.shutdown();
            } finally {
                Plugins.compareAndSwapLoaders(savedLoader);
            }

            log.info("Stopped connector {}", connName);
        }
        return true;
    }

    /**
     * Get the IDs of the connectors currently running in this worker.
     *
     * @return the set of connector IDs.
     */
    public Set<String> connectorNames() {
        return connectors.keySet();
    }

    /**
     * Return true if a connector with the given name is managed by this worker and is currently running.
     *
     * @param connName the connector name.
     * @return true if the connector is running, false if the connector is not running or is not manages by this worker.
     */
    public boolean isRunning(String connName) {
        WorkerConnector workerConnector = connectors.get(connName);
        return workerConnector != null && workerConnector.isRunning();
    }

    /**
     * Start a task managed by this worker.
     *
     * @param id the task ID.
     * @param connProps the connector properties.
     * @param taskProps the tasks properties.
     * @param statusListener a listener for the runtime status transitions of the task.
     * @param initialState the initial state of the connector.
     * @return true if the task started successfully.
     */
    public boolean startTask(
            ConnectorTaskId id,
            ClusterConfigState configState,
            Map<String, String> connProps,
            Map<String, String> taskProps,
            TaskStatus.Listener statusListener,
            TargetState initialState
    ) {
        final WorkerTask workerTask;
        try (LoggingContext loggingContext = LoggingContext.forTask(id)) {
            log.info("Creating task {}", id);

            if (tasks.containsKey(id))
                throw new ConnectException("Task already exists in this worker: " + id);

            ClassLoader savedLoader = plugins.currentThreadLoader();
            try {
                final ConnectorConfig connConfig = new ConnectorConfig(plugins, connProps);
                String connType = connConfig.getString(ConnectorConfig.CONNECTOR_CLASS_CONFIG);
                ClassLoader connectorLoader = plugins.delegatingLoader().connectorLoader(connType);
                savedLoader = Plugins.compareAndSwapLoaders(connectorLoader);
                final TaskConfig taskConfig = new TaskConfig(taskProps);
                final Class<? extends Task> taskClass = taskConfig.getClass(TaskConfig.TASK_CLASS_CONFIG).asSubclass(Task.class);
                final Task task = plugins.newTask(taskClass);
                log.info("Instantiated task {} with version {} of type {}", id, task.version(), taskClass.getName());

                // By maintaining connector's specific class loader for this thread here, we first
                // search for converters within the connector dependencies.
                // If any of these aren't found, that means the connector didn't configure specific converters,
                // so we should instantiate based upon the worker configuration
                Converter keyConverter = plugins.newConverter(connConfig, WorkerConfig.KEY_CONVERTER_CLASS_CONFIG, ClassLoaderUsage
                                                                                .CURRENT_CLASSLOADER);
                Converter valueConverter = plugins.newConverter(connConfig, WorkerConfig.VALUE_CONVERTER_CLASS_CONFIG, ClassLoaderUsage.CURRENT_CLASSLOADER);
                HeaderConverter headerConverter = plugins.newHeaderConverter(connConfig, WorkerConfig.HEADER_CONVERTER_CLASS_CONFIG,
                                                                             ClassLoaderUsage.CURRENT_CLASSLOADER);
                if (keyConverter == null) {
                    keyConverter = plugins.newConverter(config, WorkerConfig.KEY_CONVERTER_CLASS_CONFIG, ClassLoaderUsage.PLUGINS);
                    log.info("Set up the key converter {} for task {} using the worker config", keyConverter.getClass(), id);
                } else {
                    log.info("Set up the key converter {} for task {} using the connector config", keyConverter.getClass(), id);
                }
                if (valueConverter == null) {
                    valueConverter = plugins.newConverter(config, WorkerConfig.VALUE_CONVERTER_CLASS_CONFIG, ClassLoaderUsage.PLUGINS);
                    log.info("Set up the value converter {} for task {} using the worker config", valueConverter.getClass(), id);
                } else {
                    log.info("Set up the value converter {} for task {} using the connector config", valueConverter.getClass(), id);
                }
                if (headerConverter == null) {
                    headerConverter = plugins.newHeaderConverter(config, WorkerConfig.HEADER_CONVERTER_CLASS_CONFIG, ClassLoaderUsage
                                                                                .PLUGINS);
                    log.info("Set up the header converter {} for task {} using the worker config", headerConverter.getClass(), id);
                } else {
                    log.info("Set up the header converter {} for task {} using the connector config", headerConverter.getClass(), id);
                }

                workerTask = buildWorkerTask(configState, connConfig, id, task, statusListener, initialState, keyConverter, valueConverter,
                                             headerConverter, connectorLoader);
                workerTask.initialize(taskConfig);
                Plugins.compareAndSwapLoaders(savedLoader);
            } catch (Throwable t) {
                log.error("Failed to start task {}", id, t);
                // Can't be put in a finally block because it needs to be swapped before the call on
                // statusListener
                Plugins.compareAndSwapLoaders(savedLoader);
                workerMetricsGroup.recordTaskFailure();
                statusListener.onFailure(id, t);
                return false;
            }

            WorkerTask existing = tasks.putIfAbsent(id, workerTask);
            if (existing != null)
                throw new ConnectException("Task already exists in this worker: " + id);

            executor.submit(workerTask);
            if (workerTask instanceof WorkerSourceTask) {
                sourceTaskOffsetCommitter.schedule(id, (WorkerSourceTask) workerTask);
            }
            workerMetricsGroup.recordTaskSuccess();
            return true;
        }
    }

    private WorkerTask buildWorkerTask(ClusterConfigState configState,
                                       ConnectorConfig connConfig,
                                       ConnectorTaskId id,
                                       Task task,
                                       TaskStatus.Listener statusListener,
                                       TargetState initialState,
                                       Converter keyConverter,
                                       Converter valueConverter,
                                       HeaderConverter headerConverter,
                                       ClassLoader loader) {
        ErrorHandlingMetrics errorHandlingMetrics = errorHandlingMetrics(id);
        final Class<? extends Connector> connectorClass = plugins.connectorClass(
            connConfig.getString(ConnectorConfig.CONNECTOR_CLASS_CONFIG));
        RetryWithToleranceOperator retryWithToleranceOperator = new RetryWithToleranceOperator(connConfig.errorRetryTimeout(),
                connConfig.errorMaxDelayInMillis(), connConfig.errorToleranceType(), Time.SYSTEM);
        retryWithToleranceOperator.metrics(errorHandlingMetrics);

        // Decide which type of worker task we need based on the type of task.
        if (task instanceof SourceTask) {
            retryWithToleranceOperator.reporters(sourceTaskReporters(id, connConfig, errorHandlingMetrics));
            TransformationChain<SourceRecord> transformationChain = new TransformationChain<>(connConfig.<SourceRecord>transformations(), retryWithToleranceOperator);
            log.info("Initializing: {}", transformationChain);
            OffsetStorageReader offsetReader = new OffsetStorageReaderImpl(offsetBackingStore, id.connector(),
                    internalKeyConverter, internalValueConverter);
            OffsetStorageWriter offsetWriter = new OffsetStorageWriter(offsetBackingStore, id.connector(),
                    internalKeyConverter, internalValueConverter);
            Map<String, Object> producerProps = producerConfigs(id, "connector-producer-" + id, config, connConfig, connectorClass,
                                                                connectorClientConfigOverridePolicy);
            KafkaProducer<byte[], byte[]> producer = new KafkaProducer<>(producerProps);

            // Note we pass the configState as it performs dynamic transformations under the covers
            return new WorkerSourceTask(id, (SourceTask) task, statusListener, initialState, keyConverter, valueConverter,
                    headerConverter, transformationChain, producer, offsetReader, offsetWriter, config, configState, metrics, loader,
                    time, retryWithToleranceOperator);
        } else if (task instanceof SinkTask) {
            TransformationChain<SinkRecord> transformationChain = new TransformationChain<>(connConfig.<SinkRecord>transformations(), retryWithToleranceOperator);
            log.info("Initializing: {}", transformationChain);
            SinkConnectorConfig sinkConfig = new SinkConnectorConfig(plugins, connConfig.originalsStrings());
            retryWithToleranceOperator.reporters(sinkTaskReporters(id, sinkConfig, errorHandlingMetrics, connectorClass));

            Map<String, Object> consumerProps = consumerConfigs(id, config, connConfig, connectorClass, connectorClientConfigOverridePolicy);
            KafkaConsumer<byte[], byte[]> consumer = new KafkaConsumer<>(consumerProps);

            return new WorkerSinkTask(id, (SinkTask) task, statusListener, initialState, config, configState, metrics, keyConverter,
                                      valueConverter, headerConverter, transformationChain, consumer, loader, time,
                                      retryWithToleranceOperator);
        } else {
            log.error("Tasks must be a subclass of either SourceTask or SinkTask", task);
            throw new ConnectException("Tasks must be a subclass of either SourceTask or SinkTask");
        }
    }

    static Map<String, Object> producerConfigs(ConnectorTaskId id,
                                               String defaultClientId,
                                               WorkerConfig config,
                                               ConnectorConfig connConfig,
                                               Class<? extends Connector>  connectorClass,
                                               ConnectorClientConfigOverridePolicy connectorClientConfigOverridePolicy) {
        Map<String, Object> producerProps = new HashMap<>();
        producerProps.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, Utils.join(config.getList(WorkerConfig.BOOTSTRAP_SERVERS_CONFIG), ","));
        producerProps.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.ByteArraySerializer");
        producerProps.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.ByteArraySerializer");
        // These settings are designed to ensure there is no data loss. They *may* be overridden via configs passed to the
        // worker, but this may compromise the delivery guarantees of Kafka Connect.
        producerProps.put(ProducerConfig.REQUEST_TIMEOUT_MS_CONFIG, Integer.toString(Integer.MAX_VALUE));
        producerProps.put(ProducerConfig.MAX_BLOCK_MS_CONFIG, Long.toString(Long.MAX_VALUE));
        producerProps.put(ProducerConfig.ACKS_CONFIG, "all");
        producerProps.put(ProducerConfig.MAX_IN_FLIGHT_REQUESTS_PER_CONNECTION, "1");
        producerProps.put(ProducerConfig.DELIVERY_TIMEOUT_MS_CONFIG, Integer.toString(Integer.MAX_VALUE));
        producerProps.put(ProducerConfig.CLIENT_ID_CONFIG, defaultClientId);
        // User-specified overrides
        producerProps.putAll(config.originalsWithPrefix("producer."));

        // Connector-specified overrides
        Map<String, Object> producerOverrides =
            connectorClientConfigOverrides(id, connConfig, connectorClass, ConnectorConfig.CONNECTOR_CLIENT_PRODUCER_OVERRIDES_PREFIX,
                                           ConnectorType.SOURCE, ConnectorClientConfigRequest.ClientType.PRODUCER,
                                           connectorClientConfigOverridePolicy);
        producerProps.putAll(producerOverrides);

        return producerProps;
    }

    static Map<String, Object> consumerConfigs(ConnectorTaskId id,
                                               WorkerConfig config,
                                               ConnectorConfig connConfig,
                                               Class<? extends Connector> connectorClass,
                                               ConnectorClientConfigOverridePolicy connectorClientConfigOverridePolicy) {
        // Include any unknown worker configs so consumer configs can be set globally on the worker
        // and through to the task
        Map<String, Object> consumerProps = new HashMap<>();

        consumerProps.put(ConsumerConfig.GROUP_ID_CONFIG, SinkUtils.consumerGroupId(id.connector()));
        consumerProps.put(ConsumerConfig.CLIENT_ID_CONFIG, "connector-consumer-" + id);
        consumerProps.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG,
                  Utils.join(config.getList(WorkerConfig.BOOTSTRAP_SERVERS_CONFIG), ","));
        consumerProps.put(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, "false");
        consumerProps.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest");
        consumerProps.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.ByteArrayDeserializer");
        consumerProps.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.ByteArrayDeserializer");

        consumerProps.putAll(config.originalsWithPrefix("consumer."));
        // Connector-specified overrides
        Map<String, Object> consumerOverrides =
            connectorClientConfigOverrides(id, connConfig, connectorClass, ConnectorConfig.CONNECTOR_CLIENT_CONSUMER_OVERRIDES_PREFIX,
                                           ConnectorType.SINK, ConnectorClientConfigRequest.ClientType.CONSUMER,
                                           connectorClientConfigOverridePolicy);
        consumerProps.putAll(consumerOverrides);

        return consumerProps;
    }

    static Map<String, Object> adminConfigs(ConnectorTaskId id,
                                            WorkerConfig config,
                                            ConnectorConfig connConfig,
                                            Class<? extends Connector> connectorClass,
                                            ConnectorClientConfigOverridePolicy connectorClientConfigOverridePolicy) {
        Map<String, Object> adminProps = new HashMap<>();
        adminProps.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, Utils.join(config.getList(WorkerConfig.BOOTSTRAP_SERVERS_CONFIG), ","));
        // User-specified overrides
        adminProps.putAll(config.originalsWithPrefix("admin."));

        // Connector-specified overrides
        Map<String, Object> adminOverrides =
            connectorClientConfigOverrides(id, connConfig, connectorClass, ConnectorConfig.CONNECTOR_CLIENT_ADMIN_OVERRIDES_PREFIX,
                                           ConnectorType.SINK, ConnectorClientConfigRequest.ClientType.ADMIN,
                                           connectorClientConfigOverridePolicy);
        adminProps.putAll(adminOverrides);

        return adminProps;
    }

    private static Map<String, Object> connectorClientConfigOverrides(ConnectorTaskId id,
                                                                      ConnectorConfig connConfig,
                                                                      Class<? extends Connector> connectorClass,
                                                                      String clientConfigPrefix,
                                                                      ConnectorType connectorType,
                                                                      ConnectorClientConfigRequest.ClientType clientType,
                                                                      ConnectorClientConfigOverridePolicy connectorClientConfigOverridePolicy) {
        Map<String, Object> clientOverrides = connConfig.originalsWithPrefix(clientConfigPrefix);
        ConnectorClientConfigRequest connectorClientConfigRequest = new ConnectorClientConfigRequest(
            id.connector(),
            connectorType,
            connectorClass,
            clientOverrides,
            clientType
        );
        List<ConfigValue> configValues = connectorClientConfigOverridePolicy.validate(connectorClientConfigRequest);
        List<ConfigValue> errorConfigs = configValues.stream().
            filter(configValue -> configValue.errorMessages().size() > 0).collect(Collectors.toList());
        // These should be caught when the herder validates the connector configuration, but just in case
        if (errorConfigs.size() > 0) {
            throw new ConnectException("Client Config Overrides not allowed " + errorConfigs);
        }
        return clientOverrides;
    }

    ErrorHandlingMetrics errorHandlingMetrics(ConnectorTaskId id) {
        return new ErrorHandlingMetrics(id, metrics);
    }

    private List<ErrorReporter> sinkTaskReporters(ConnectorTaskId id, SinkConnectorConfig connConfig,
                                                  ErrorHandlingMetrics errorHandlingMetrics,
                                                  Class<? extends Connector> connectorClass) {
        ArrayList<ErrorReporter> reporters = new ArrayList<>();
        LogReporter logReporter = new LogReporter(id, connConfig, errorHandlingMetrics);
        reporters.add(logReporter);

        // check if topic for dead letter queue exists
        String topic = connConfig.dlqTopicName();
        if (topic != null && !topic.isEmpty()) {
            Map<String, Object> producerProps = producerConfigs(id, "connector-dlq-producer-" + id, config, connConfig, connectorClass,
                                                                connectorClientConfigOverridePolicy);
            Map<String, Object> adminProps = adminConfigs(id, config, connConfig, connectorClass, connectorClientConfigOverridePolicy);
            DeadLetterQueueReporter reporter = DeadLetterQueueReporter.createAndSetup(adminProps, id, connConfig, producerProps, errorHandlingMetrics);
            reporters.add(reporter);
        }

        return reporters;
    }

    private List<ErrorReporter> sourceTaskReporters(ConnectorTaskId id, ConnectorConfig connConfig,
                                                      ErrorHandlingMetrics errorHandlingMetrics) {
        List<ErrorReporter> reporters = new ArrayList<>();
        LogReporter logReporter = new LogReporter(id, connConfig, errorHandlingMetrics);
        reporters.add(logReporter);

        return reporters;
    }

    private void stopTask(ConnectorTaskId taskId) {
        try (LoggingContext loggingContext = LoggingContext.forTask(taskId)) {
            WorkerTask task = tasks.get(taskId);
            if (task == null) {
                log.warn("Ignoring stop request for unowned task {}", taskId);
                return;
            }

            log.info("Stopping task {}", task.id());
            if (task instanceof WorkerSourceTask)
                sourceTaskOffsetCommitter.remove(task.id());

            ClassLoader savedLoader = plugins.currentThreadLoader();
            try {
                savedLoader = Plugins.compareAndSwapLoaders(task.loader());
                task.stop();
            } finally {
                Plugins.compareAndSwapLoaders(savedLoader);
            }
        }
    }

    private void stopTasks(Collection<ConnectorTaskId> ids) {
        // Herder is responsible for stopping tasks. This is an internal method to sequentially
        // stop the tasks that have not explicitly been stopped.
        for (ConnectorTaskId taskId : ids) {
            stopTask(taskId);
        }
    }

    private void awaitStopTask(ConnectorTaskId taskId, long timeout) {
        try (LoggingContext loggingContext = LoggingContext.forTask(taskId)) {
            WorkerTask task = tasks.remove(taskId);
            if (task == null) {
                log.warn("Ignoring await stop request for non-present task {}", taskId);
                return;
            }

            if (!task.awaitStop(timeout)) {
                log.error("Graceful stop of task {} failed.", task.id());
                task.cancel();
            } else {
                log.debug("Graceful stop of task {} succeeded.", task.id());
            }
        }
    }

    private void awaitStopTasks(Collection<ConnectorTaskId> ids) {
        long now = time.milliseconds();
        long deadline = now + config.getLong(WorkerConfig.TASK_SHUTDOWN_GRACEFUL_TIMEOUT_MS_CONFIG);
        for (ConnectorTaskId id : ids) {
            long remaining = Math.max(0, deadline - time.milliseconds());
            awaitStopTask(id, remaining);
        }
    }

    /**
     * Stop asynchronously all the worker's tasks and await their termination.
     */
    public void stopAndAwaitTasks() {
        stopAndAwaitTasks(new ArrayList<>(tasks.keySet()));
    }

    /**
     * Stop asynchronously a collection of tasks that belong to this worker and await their termination.
     *
     * @param ids the collection of tasks to be stopped.
     */
    public void stopAndAwaitTasks(Collection<ConnectorTaskId> ids) {
        stopTasks(ids);
        awaitStopTasks(ids);
    }

    /**
     * Stop a task that belongs to this worker and await its termination.
     *
     * @param taskId the ID of the task to be stopped.
     */
    public void stopAndAwaitTask(ConnectorTaskId taskId) {
        stopTask(taskId);
        awaitStopTasks(Collections.singletonList(taskId));
    }

    /**
     * Get the IDs of the tasks currently running in this worker.
     */
    public Set<ConnectorTaskId> taskIds() {
        return tasks.keySet();
    }

    public Converter getInternalKeyConverter() {
        return internalKeyConverter;
    }

    public Converter getInternalValueConverter() {
        return internalValueConverter;
    }

    public Plugins getPlugins() {
        return plugins;
    }

    public String workerId() {
        return workerId;
    }

    /**
     * Get the {@link ConnectMetrics} that uses Kafka Metrics and manages the JMX reporter.
     * @return the Connect-specific metrics; never null
     */
    public ConnectMetrics metrics() {
        return metrics;
    }

    public void setTargetState(String connName, TargetState state) {
        log.info("Setting connector {} state to {}", connName, state);

        WorkerConnector workerConnector = connectors.get(connName);
        if (workerConnector != null) {
            ClassLoader connectorLoader =
                    plugins.delegatingLoader().connectorLoader(workerConnector.connector());
            transitionTo(workerConnector, state, connectorLoader);
        }

        for (Map.Entry<ConnectorTaskId, WorkerTask> taskEntry : tasks.entrySet()) {
            if (taskEntry.getKey().connector().equals(connName)) {
                WorkerTask workerTask = taskEntry.getValue();
                transitionTo(workerTask, state, workerTask.loader());
            }
        }
    }

    private void transitionTo(Object connectorOrTask, TargetState state, ClassLoader loader) {
        ClassLoader savedLoader = plugins.currentThreadLoader();
        try {
            savedLoader = Plugins.compareAndSwapLoaders(loader);
            if (connectorOrTask instanceof WorkerConnector) {
                ((WorkerConnector) connectorOrTask).transitionTo(state);
            } else if (connectorOrTask instanceof WorkerTask) {
                ((WorkerTask) connectorOrTask).transitionTo(state);
            } else {
                throw new ConnectException(
                        "Request for state transition on an object that is neither a "
                                + "WorkerConnector nor a WorkerTask: "
                                + connectorOrTask.getClass());
            }
        } finally {
            Plugins.compareAndSwapLoaders(savedLoader);
        }
    }

    WorkerMetricsGroup workerMetricsGroup() {
        return workerMetricsGroup;
    }

    class WorkerMetricsGroup {
        private final MetricGroup metricGroup;
        private final Sensor connectorStartupAttempts;
        private final Sensor connectorStartupSuccesses;
        private final Sensor connectorStartupFailures;
        private final Sensor connectorStartupResults;
        private final Sensor taskStartupAttempts;
        private final Sensor taskStartupSuccesses;
        private final Sensor taskStartupFailures;
        private final Sensor taskStartupResults;

        public WorkerMetricsGroup(ConnectMetrics connectMetrics) {
            ConnectMetricsRegistry registry = connectMetrics.registry();
            metricGroup = connectMetrics.group(registry.workerGroupName());

            metricGroup.addValueMetric(registry.connectorCount, new LiteralSupplier<Double>() {
                @Override
                public Double metricValue(long now) {
                    return (double) connectors.size();
                }
            });
            metricGroup.addValueMetric(registry.taskCount, new LiteralSupplier<Double>() {
                @Override
                public Double metricValue(long now) {
                    return (double) tasks.size();
                }
            });

            MetricName connectorFailurePct = metricGroup.metricName(registry.connectorStartupFailurePercentage);
            MetricName connectorSuccessPct = metricGroup.metricName(registry.connectorStartupSuccessPercentage);
            Frequencies connectorStartupResultFrequencies = Frequencies.forBooleanValues(connectorFailurePct, connectorSuccessPct);
            connectorStartupResults = metricGroup.sensor("connector-startup-results");
            connectorStartupResults.add(connectorStartupResultFrequencies);

            connectorStartupAttempts = metricGroup.sensor("connector-startup-attempts");
            connectorStartupAttempts.add(metricGroup.metricName(registry.connectorStartupAttemptsTotal), new Total());

            connectorStartupSuccesses = metricGroup.sensor("connector-startup-successes");
            connectorStartupSuccesses.add(metricGroup.metricName(registry.connectorStartupSuccessTotal), new Total());

            connectorStartupFailures = metricGroup.sensor("connector-startup-failures");
            connectorStartupFailures.add(metricGroup.metricName(registry.connectorStartupFailureTotal), new Total());

            MetricName taskFailurePct = metricGroup.metricName(registry.taskStartupFailurePercentage);
            MetricName taskSuccessPct = metricGroup.metricName(registry.taskStartupSuccessPercentage);
            Frequencies taskStartupResultFrequencies = Frequencies.forBooleanValues(taskFailurePct, taskSuccessPct);
            taskStartupResults = metricGroup.sensor("task-startup-results");
            taskStartupResults.add(taskStartupResultFrequencies);

            taskStartupAttempts = metricGroup.sensor("task-startup-attempts");
            taskStartupAttempts.add(metricGroup.metricName(registry.taskStartupAttemptsTotal), new Total());

            taskStartupSuccesses = metricGroup.sensor("task-startup-successes");
            taskStartupSuccesses.add(metricGroup.metricName(registry.taskStartupSuccessTotal), new Total());

            taskStartupFailures = metricGroup.sensor("task-startup-failures");
            taskStartupFailures.add(metricGroup.metricName(registry.taskStartupFailureTotal), new Total());
        }

        void close() {
            metricGroup.close();
        }

        void recordConnectorStartupFailure() {
            connectorStartupAttempts.record(1.0);
            connectorStartupFailures.record(1.0);
            connectorStartupResults.record(0.0);
        }

        void recordConnectorStartupSuccess() {
            connectorStartupAttempts.record(1.0);
            connectorStartupSuccesses.record(1.0);
            connectorStartupResults.record(1.0);
        }

        void recordTaskFailure() {
            taskStartupAttempts.record(1.0);
            taskStartupFailures.record(1.0);
            taskStartupResults.record(0.0);
        }

        void recordTaskSuccess() {
            taskStartupAttempts.record(1.0);
            taskStartupSuccesses.record(1.0);
            taskStartupResults.record(1.0);
        }

        protected MetricGroup metricGroup() {
            return metricGroup;
        }
    }
}


text:
iOS native object mapping for MovieLabs Cross-Platform Extras Manifest, Common Metadata, AppData and Style specs, compatible with [CPEExperience](https://github.com/warnerbros/cpe-manifest-ios-experience) for a full UI implementation.

Currently supported specs:
* [Media Manifest v1.5](http://www.movielabs.com/md/manifest) conforming to [Interactivity Profile 1](http://www.movielabs.com/cpe/profiles/)
* [Common Metadata v2.4](http://www.movielabs.com/md/md)
* [CPE-AppData v1.0](http://www.movielabs.com/cpe/appdata)
* [CPE-Style v1.0](http://www.movielabs.com/cpe/style)

## Installation

### CocoaPods

[CocoaPods](http://cocoapods.org) is a dependency manager for Cocoa projects. You can install it with the following command:

```bash
$ gem install cocoapods
```

To integrate CPEData into your Xcode project using CocoaPods, specify it in your `Podfile`:

```ruby
source 'https://github.com/CocoaPods/Specs.git'
platform :ios, '8.0'
use_frameworks!

target '<Your Target Name>' do
    pod 'CPEData', '~> 3.0'
end
```

Then, run the following command:

```bash
$ pod install
```

### Carthage
[Carthage](https://github.com/Carthage/Carthage) is a decentralized dependency manager for Cocoa applications.
To integrate CPEData into your Xcode project using Carthage, specify it in your `Cartfile`:

```
github "warnerbros/cpe-manifest-ios-data" ~> 3.0
```
Then, add `CPEData.framework` and `SWXMLHash.framework` to "Linked Frameworks and Libraries" and Carthage's "copy-frameworks" script

## Usage

Use the static `load` functions in `CPEXMLSuite` for a convenient way to initialize and parse all the supported spec files.

### Providing `URL` objects
```swift
CPEXMLSuite.load(manifestXMLURL: manifestXMLURL, appDataXMLURL: appDataXMLURL, cpeStyleXMLURL: cpeStyleXMLURL) { (error) in
    if let error = error {
        // Respond to error case
    } else {
        // Respond to parsing completion event (ExperienceLauncher.launch)
    }
}
```

### Providing `Data` objects
```swift
CPEXMLSuite.load(manifestXMLData: manifestXMLData, appDataXMLData: appDataXMLData, cpeStyleXMLData: cpeStyleXMLData) { (error) in
    if let error = error {
        // Respond to error case
    } else {
        // Respond to parsing completion event (ExperienceLauncher.launch)
    }
}
```

## Development

Open `Example/CPEDataExampleWorkspace.xcworkspace` in Xcode to build and run the sample project, which allows you to specify your own XML file URLs to be parsed and mapped to the library's native classes. The example project also provides a UI to explore the hierarchy of the parsed data:

![Example hierarchy of parsed Manifest](https://raw.githubusercontent.com/warnerbros/cpe-manifest-ios-data/assets/example_hierarchy.png)

redpajama_set_name: RedPajamaGithub


text:
from lxml import html
import requests
from urlparse import urljoin
import urlparse

# config

# url of the page containing song list
song_list_url = "http://www.songspk.link/audio_single_mp3_songs.html"

# base url used to resolve relative urls
base_url = "http://www.songspk.link/"

# song list -> song page -> mp3

def is_absolute(url):
	return bool(urlparse.urlparse(url).netloc)

# get list of song page urls

page = requests.get(song_list_url)
tree = html.fromstring(page.text)
links = tree.xpath('//a[@class="link"]/@href')

top_links = []
top_relative_links = []

for link in links:
	if is_absolute(link):
		top_links.append(link)
	else:
		# print link
		top_relative_links.append(link)

# get mp3 urls from song page urls

mp3_links = []

def get_mp3_url_from_page (link):
	page = requests.get(link)
	tree = html.fromstring(page.text)
	try:
		url = tree.xpath('//td[@class="Bitrate-td-2"]/a/@href')[0]
	except Exception, e:
		try:
			url = tree.xpath('//div[@class="song-title-bold"]/b/a/@href')[1]
		except Exception, e:
			print e
	return url

def get_mp3_url(mp3_page_urls):
	for link in mp3_page_urls:

		if not is_absolute(link):
			link = urljoin(base_url,link)

		try:
			url = get_mp3_url_from_page(link)
			print url
			mp3_links.append (url)
			pass
		except Exception, e:
			print e

	print len(mp3_links), "songs link fetched."

get_mp3_url(top_relative_links)


text:
<?php

namespace EasyCorp\Bundle\EasyAdminBundle\Tests\Controller;

use EasyCorp\Bundle\EasyAdminBundle\Tests\Fixtures\AbstractTestCase;

class CustomFieldTemplateTest extends AbstractTestCase
{
    public function setUp()
    {
        parent::setUp();

        $this->initClient(array('environment' => 'custom_field_template'));
    }

    public function testListViewCustomFieldTemplate()
    {
        $crawler = $this->requestListView();

        $this->assertContains('Custom template for "name" field in the "list" view.', $crawler->filter('#main table td[data-label="Name"]')->eq(0)->text());
        $this->assertContains('The value of the custom option is "custom_list_value".', $crawler->filter('#main table td[data-label="Name"]')->eq(0)->text());
    }

    public function testShowViewCustomFieldTemplate()
    {
        $crawler = $this->requestShowView();

        $this->assertContains('Custom template for "name" field in the "show" view.', $crawler->filter('#main .form-control')->eq(0)->text());
        $this->assertContains('The value of the custom option is "custom_show_value".', $crawler->filter('#main .form-control')->eq(0)->text());
    }
}


text: package applicationautoscaling


text:
package com.testpoke.core.activation;

import android.content.Context;
import com.testpoke.core.util.log.TP;

import java.lang.ref.WeakReference;

/*
 * Created by Jansel Valentin on 5/4/14.
 */
public final class StatesActivator {
    private static WeakReference<SelfContainedActivator> activators;

    static {
        activators = new WeakReference<SelfContainedActivator>(SelfContainedActivator.prepare());
    }

    public static void activate(Context app) {
        if (null == activators)
            return;

        SelfContainedActivator mActivators = activators.get();

        if (null == mActivators) {
            TP.d("Could not possible to get SelfContainedActivator instance");
            return;
        }
        ActivationToken token = new NaiveActivationToken();

            TP.i("Activating TestPoke modules...");

        for (Activator activator : mActivators) {
            activator.activate(app, token);
        }
        mActivators.clear();
        activators.clear();
        activators = null;
        token = null;
    }

    public static void checkToken(ActivationToken token) {
        if (!(token instanceof NaiveActivationToken))
            throw new IllegalArgumentException("Invalid Activation Token");
    }

    private static class NaiveActivationToken implements ActivationToken {
    }
}


text: google-site-verification: googlee26a693e63b2ef07.html


text:
package org.hl7.fhir.instance.model;

// Generated on Tue, Sep 1, 2015 19:08-0400 for FHIR v1.0.0

import java.util.*;

import org.hl7.fhir.utilities.Utilities;
import org.hl7.fhir.instance.model.annotations.ResourceDef;
import org.hl7.fhir.instance.model.annotations.SearchParamDefinition;
import org.hl7.fhir.instance.model.annotations.Child;
import org.hl7.fhir.instance.model.annotations.Description;
import org.hl7.fhir.instance.model.annotations.Block;
import org.hl7.fhir.instance.model.api.*;
/**
 * This resource is primarily used for the identification and definition of a medication. It covers the ingredients and the packaging for a medication.
 */
@ResourceDef(name="Medication", profile="http://hl7.org/fhir/Profile/Medication")
public class Medication extends DomainResource {

    @Block()
    public static class MedicationProductComponent extends BackboneElement implements IBaseBackboneElement {
        /**
         * Describes the form of the item.  Powder; tablets; carton.
         */
        @Child(name = "form", type = {CodeableConcept.class}, order=1, min=0, max=1, modifier=false, summary=false)
        @Description(shortDefinition="powder | tablets | carton +", formalDefinition="Describes the form of the item.  Powder; tablets; carton." )
        protected CodeableConcept form;

        /**
         * Identifies a particular constituent of interest in the product.
         */
        @Child(name = "ingredient", type = {}, order=2, min=0, max=Child.MAX_UNLIMITED, modifier=false, summary=false)
        @Description(shortDefinition="Active or inactive ingredient", formalDefinition="Identifies a particular constituent of interest in the product." )
        protected List<MedicationProductIngredientComponent> ingredient;

        /**
         * Information about a group of medication produced or packaged from one production run.
         */
        @Child(name = "batch", type = {}, order=3, min=0, max=Child.MAX_UNLIMITED, modifier=false, summary=false)
        @Description(shortDefinition="", formalDefinition="Information about a group of medication produced or packaged from one production run." )
        protected List<MedicationProductBatchComponent> batch;

        private static final long serialVersionUID = 1132853671L;

    /*
     * Constructor
     */
      public MedicationProductComponent() {
        super();
      }

        /**
         * @return {@link #form} (Describes the form of the item.  Powder; tablets; carton.)
         */
        public CodeableConcept getForm() {
          if (this.form == null)
            if (Configuration.errorOnAutoCreate())
              throw new Error("Attempt to auto-create MedicationProductComponent.form");
            else if (Configuration.doAutoCreate())
              this.form = new CodeableConcept(); // cc
          return this.form;
        }

        public boolean hasForm() {
          return this.form != null && !this.form.isEmpty();
        }

        /**
         * @param value {@link #form} (Describes the form of the item.  Powder; tablets; carton.)
         */
        public MedicationProductComponent setForm(CodeableConcept value) {
          this.form = value;
          return this;
        }

        /**
         * @return {@link #ingredient} (Identifies a particular constituent of interest in the product.)
         */
        public List<MedicationProductIngredientComponent> getIngredient() {
          if (this.ingredient == null)
            this.ingredient = new ArrayList<MedicationProductIngredientComponent>();
          return this.ingredient;
        }

        public boolean hasIngredient() {
          if (this.ingredient == null)
            return false;
          for (MedicationProductIngredientComponent item : this.ingredient)
            if (!item.isEmpty())
              return true;
          return false;
        }

        /**
         * @return {@link #ingredient} (Identifies a particular constituent of interest in the product.)
         */
    // syntactic sugar
        public MedicationProductIngredientComponent addIngredient() { //3
          MedicationProductIngredientComponent t = new MedicationProductIngredientComponent();
          if (this.ingredient == null)
            this.ingredient = new ArrayList<MedicationProductIngredientComponent>();
          this.ingredient.add(t);
          return t;
        }

    // syntactic sugar
        public MedicationProductComponent addIngredient(MedicationProductIngredientComponent t) { //3
          if (t == null)
            return this;
          if (this.ingredient == null)
            this.ingredient = new ArrayList<MedicationProductIngredientComponent>();
          this.ingredient.add(t);
          return this;
        }

        /**
         * @return {@link #batch} (Information about a group of medication produced or packaged from one production run.)
         */
        public List<MedicationProductBatchComponent> getBatch() {
          if (this.batch == null)
            this.batch = new ArrayList<MedicationProductBatchComponent>();
          return this.batch;
        }

        public boolean hasBatch() {
          if (this.batch == null)
            return false;
          for (MedicationProductBatchComponent item : this.batch)
            if (!item.isEmpty())
              return true;
          return false;
        }

        /**
         * @return {@link #batch} (Information about a group of medication produced or packaged from one production run.)
         */
    // syntactic sugar
        public MedicationProductBatchComponent addBatch() { //3
          MedicationProductBatchComponent t = new MedicationProductBatchComponent();
          if (this.batch == null)
            this.batch = new ArrayList<MedicationProductBatchComponent>();
          this.batch.add(t);
          return t;
        }

    // syntactic sugar
        public MedicationProductComponent addBatch(MedicationProductBatchComponent t) { //3
          if (t == null)
            return this;
          if (this.batch == null)
            this.batch = new ArrayList<MedicationProductBatchComponent>();
          this.batch.add(t);
          return this;
        }

        protected void listChildren(List<Property> childrenList) {
          super.listChildren(childrenList);
          childrenList.add(new Property("form", "CodeableConcept", "Describes the form of the item.  Powder; tablets; carton.", 0, java.lang.Integer.MAX_VALUE, form));
          childrenList.add(new Property("ingredient", "", "Identifies a particular constituent of interest in the product.", 0, java.lang.Integer.MAX_VALUE, ingredient));
          childrenList.add(new Property("batch", "", "Information about a group of medication produced or packaged from one production run.", 0, java.lang.Integer.MAX_VALUE, batch));
        }

      public MedicationProductComponent copy() {
        MedicationProductComponent dst = new MedicationProductComponent();
        copyValues(dst);
        dst.form = form == null ? null : form.copy();
        if (ingredient != null) {
          dst.ingredient = new ArrayList<MedicationProductIngredientComponent>();
          for (MedicationProductIngredientComponent i : ingredient)
            dst.ingredient.add(i.copy());
        };
        if (batch != null) {
          dst.batch = new ArrayList<MedicationProductBatchComponent>();
          for (MedicationProductBatchComponent i : batch)
            dst.batch.add(i.copy());
        };
        return dst;
      }

      @Override
      public boolean equalsDeep(Base other) {
        if (!super.equalsDeep(other))
          return false;
        if (!(other instanceof MedicationProductComponent))
          return false;
        MedicationProductComponent o = (MedicationProductComponent) other;
        return compareDeep(form, o.form, true) && compareDeep(ingredient, o.ingredient, true) && compareDeep(batch, o.batch, true)
          ;
      }

      @Override
      public boolean equalsShallow(Base other) {
        if (!super.equalsShallow(other))
          return false;
        if (!(other instanceof MedicationProductComponent))
          return false;
        MedicationProductComponent o = (MedicationProductComponent) other;
        return true;
      }

      public boolean isEmpty() {
        return super.isEmpty() && (form == null || form.isEmpty()) && (ingredient == null || ingredient.isEmpty())
           && (batch == null || batch.isEmpty());
      }

  }

    @Block()
    public static class MedicationProductIngredientComponent extends BackboneElement implements IBaseBackboneElement {
        /**
         * The actual ingredient - either a substance (simple ingredient) or another medication.
         */
        @Child(name = "item", type = {Substance.class, Medication.class}, order=1, min=1, max=1, modifier=false, summary=false)
        @Description(shortDefinition="The product contained", formalDefinition="The actual ingredient - either a substance (simple ingredient) or another medication." )
        protected Reference item;

        /**
         * The actual object that is the target of the reference (The actual ingredient - either a substance (simple ingredient) or another medication.)
         */
        protected Resource itemTarget;

        /**
         * Specifies how many (or how much) of the items there are in this Medication.  E.g. 250 mg per tablet.
         */
        @Child(name = "amount", type = {Ratio.class}, order=2, min=0, max=1, modifier=false, summary=false)
        @Description(shortDefinition="How much ingredient in product", formalDefinition="Specifies how many (or how much) of the items there are in this Medication.  E.g. 250 mg per tablet." )
        protected Ratio amount;

        private static final long serialVersionUID = -1217232889L;

    /*
     * Constructor
     */
      public MedicationProductIngredientComponent() {
        super();
      }

    /*
     * Constructor
     */
      public MedicationProductIngredientComponent(Reference item) {
        super();
        this.item = item;
      }

        /**
         * @return {@link #item} (The actual ingredient - either a substance (simple ingredient) or another medication.)
         */
        public Reference getItem() {
          if (this.item == null)
            if (Configuration.errorOnAutoCreate())
              throw new Error("Attempt to auto-create MedicationProductIngredientComponent.item");
            else if (Configuration.doAutoCreate())
              this.item = new Reference(); // cc
          return this.item;
        }

        public boolean hasItem() {
          return this.item != null && !this.item.isEmpty();
        }

        /**
         * @param value {@link #item} (The actual ingredient - either a substance (simple ingredient) or another medication.)
         */
        public MedicationProductIngredientComponent setItem(Reference value) {
          this.item = value;
          return this;
        }

        /**
         * @return {@link #item} The actual object that is the target of the reference. The reference library doesn't populate this, but you can use it to hold the resource if you resolve it. (The actual ingredient - either a substance (simple ingredient) or another medication.)
         */
        public Resource getItemTarget() {
          return this.itemTarget;
        }

        /**
         * @param value {@link #item} The actual object that is the target of the reference. The reference library doesn't use these, but you can use it to hold the resource if you resolve it. (The actual ingredient - either a substance (simple ingredient) or another medication.)
         */
        public MedicationProductIngredientComponent setItemTarget(Resource value) {
          this.itemTarget = value;
          return this;
        }

        /**
         * @return {@link #amount} (Specifies how many (or how much) of the items there are in this Medication.  E.g. 250 mg per tablet.)
         */
        public Ratio getAmount() {
          if (this.amount == null)
            if (Configuration.errorOnAutoCreate())
              throw new Error("Attempt to auto-create MedicationProductIngredientComponent.amount");
            else if (Configuration.doAutoCreate())
              this.amount = new Ratio(); // cc
          return this.amount;
        }

        public boolean hasAmount() {
          return this.amount != null && !this.amount.isEmpty();
        }

        /**
         * @param value {@link #amount} (Specifies how many (or how much) of the items there are in this Medication.  E.g. 250 mg per tablet.)
         */
        public MedicationProductIngredientComponent setAmount(Ratio value) {
          this.amount = value;
          return this;
        }

        protected void listChildren(List<Property> childrenList) {
          super.listChildren(childrenList);
          childrenList.add(new Property("item", "Reference(Substance|Medication)", "The actual ingredient - either a substance (simple ingredient) or another medication.", 0, java.lang.Integer.MAX_VALUE, item));
          childrenList.add(new Property("amount", "Ratio", "Specifies how many (or how much) of the items there are in this Medication.  E.g. 250 mg per tablet.", 0, java.lang.Integer.MAX_VALUE, amount));
        }

      public MedicationProductIngredientComponent copy() {
        MedicationProductIngredientComponent dst = new MedicationProductIngredientComponent();
        copyValues(dst);
        dst.item = item == null ? null : item.copy();
        dst.amount = amount == null ? null : amount.copy();
        return dst;
      }

      @Override
      public boolean equalsDeep(Base other) {
        if (!super.equalsDeep(other))
          return false;
        if (!(other instanceof MedicationProductIngredientComponent))
          return false;
        MedicationProductIngredientComponent o = (MedicationProductIngredientComponent) other;
        return compareDeep(item, o.item, true) && compareDeep(amount, o.amount, true);
      }

      @Override
      public boolean equalsShallow(Base other) {
        if (!super.equalsShallow(other))
          return false;
        if (!(other instanceof MedicationProductIngredientComponent))
          return false;
        MedicationProductIngredientComponent o = (MedicationProductIngredientComponent) other;
        return true;
      }

      public boolean isEmpty() {
        return super.isEmpty() && (item == null || item.isEmpty()) && (amount == null || amount.isEmpty())
          ;
      }

  }

    @Block()
    public static class MedicationProductBatchComponent extends BackboneElement implements IBaseBackboneElement {
        /**
         * The assigned lot number of a batch of the specified product.
         */
        @Child(name = "lotNumber", type = {StringType.class}, order=1, min=0, max=1, modifier=false, summary=false)
        @Description(shortDefinition="", formalDefinition="The assigned lot number of a batch of the specified product." )
        protected StringType lotNumber;

        /**
         * When this specific batch of product will expire.
         */
        @Child(name = "expirationDate", type = {DateTimeType.class}, order=2, min=0, max=1, modifier=false, summary=false)
        @Description(shortDefinition="", formalDefinition="When this specific batch of product will expire." )
        protected DateTimeType expirationDate;

        private static final long serialVersionUID = 1982738755L;

    /*
     * Constructor
     */
      public MedicationProductBatchComponent() {
        super();
      }

        /**
         * @return {@link #lotNumber} (The assigned lot number of a batch of the specified product.). This is the underlying object with id, value and extensions. The accessor "getLotNumber" gives direct access to the value
         */
        public StringType getLotNumberElement() {
          if (this.lotNumber == null)
            if (Configuration.errorOnAutoCreate())
              throw new Error("Attempt to auto-create MedicationProductBatchComponent.lotNumber");
            else if (Configuration.doAutoCreate())
              this.lotNumber = new StringType(); // bb
          return this.lotNumber;
        }

        public boolean hasLotNumberElement() {
          return this.lotNumber != null && !this.lotNumber.isEmpty();
        }

        public boolean hasLotNumber() {
          return this.lotNumber != null && !this.lotNumber.isEmpty();
        }

        /**
         * @param value {@link #lotNumber} (The assigned lot number of a batch of the specified product.). This is the underlying object with id, value and extensions. The accessor "getLotNumber" gives direct access to the value
         */
        public MedicationProductBatchComponent setLotNumberElement(StringType value) {
          this.lotNumber = value;
          return this;
        }

        /**
         * @return The assigned lot number of a batch of the specified product.
         */
        public String getLotNumber() {
          return this.lotNumber == null ? null : this.lotNumber.getValue();
        }

        /**
         * @param value The assigned lot number of a batch of the specified product.
         */
        public MedicationProductBatchComponent setLotNumber(String value) {
          if (Utilities.noString(value))
            this.lotNumber = null;
          else {
            if (this.lotNumber == null)
              this.lotNumber = new StringType();
            this.lotNumber.setValue(value);
          }
          return this;
        }

        /**
         * @return {@link #expirationDate} (When this specific batch of product will expire.). This is the underlying object with id, value and extensions. The accessor "getExpirationDate" gives direct access to the value
         */
        public DateTimeType getExpirationDateElement() {
          if (this.expirationDate == null)
            if (Configuration.errorOnAutoCreate())
              throw new Error("Attempt to auto-create MedicationProductBatchComponent.expirationDate");
            else if (Configuration.doAutoCreate())
              this.expirationDate = new DateTimeType(); // bb
          return this.expirationDate;
        }

        public boolean hasExpirationDateElement() {
          return this.expirationDate != null && !this.expirationDate.isEmpty();
        }

        public boolean hasExpirationDate() {
          return this.expirationDate != null && !this.expirationDate.isEmpty();
        }

        /**
         * @param value {@link #expirationDate} (When this specific batch of product will expire.). This is the underlying object with id, value and extensions. The accessor "getExpirationDate" gives direct access to the value
         */
        public MedicationProductBatchComponent setExpirationDateElement(DateTimeType value) {
          this.expirationDate = value;
          return this;
        }

        /**
         * @return When this specific batch of product will expire.
         */
        public Date getExpirationDate() {
          return this.expirationDate == null ? null : this.expirationDate.getValue();
        }

        /**
         * @param value When this specific batch of product will expire.
         */
        public MedicationProductBatchComponent setExpirationDate(Date value) {
          if (value == null)
            this.expirationDate = null;
          else {
            if (this.expirationDate == null)
              this.expirationDate = new DateTimeType();
            this.expirationDate.setValue(value);
          }
          return this;
        }

        protected void listChildren(List<Property> childrenList) {
          super.listChildren(childrenList);
          childrenList.add(new Property("lotNumber", "string", "The assigned lot number of a batch of the specified product.", 0, java.lang.Integer.MAX_VALUE, lotNumber));
          childrenList.add(new Property("expirationDate", "dateTime", "When this specific batch of product will expire.", 0, java.lang.Integer.MAX_VALUE, expirationDate));
        }

      public MedicationProductBatchComponent copy() {
        MedicationProductBatchComponent dst = new MedicationProductBatchComponent();
        copyValues(dst);
        dst.lotNumber = lotNumber == null ? null : lotNumber.copy();
        dst.expirationDate = expirationDate == null ? null : expirationDate.copy();
        return dst;
      }

      @Override
      public boolean equalsDeep(Base other) {
        if (!super.equalsDeep(other))
          return false;
        if (!(other instanceof MedicationProductBatchComponent))
          return false;
        MedicationProductBatchComponent o = (MedicationProductBatchComponent) other;
        return compareDeep(lotNumber, o.lotNumber, true) && compareDeep(expirationDate, o.expirationDate, true)
          ;
      }

      @Override
      public boolean equalsShallow(Base other) {
        if (!super.equalsShallow(other))
          return false;
        if (!(other instanceof MedicationProductBatchComponent))
          return false;
        MedicationProductBatchComponent o = (MedicationProductBatchComponent) other;
        return compareValues(lotNumber, o.lotNumber, true) && compareValues(expirationDate, o.expirationDate, true)
          ;
      }

      public boolean isEmpty() {
        return super.isEmpty() && (lotNumber == null || lotNumber.isEmpty()) && (expirationDate == null || expirationDate.isEmpty())
          ;
      }

  }

    @Block()
    public static class MedicationPackageComponent extends BackboneElement implements IBaseBackboneElement {
        /**
         * The kind of container that this package comes as.
         */
        @Child(name = "container", type = {CodeableConcept.class}, order=1, min=0, max=1, modifier=false, summary=false)
        @Description(shortDefinition="E.g. box, vial, blister-pack", formalDefinition="The kind of container that this package comes as." )
        protected CodeableConcept container;

        /**
         * A set of components that go to make up the described item.
         */
        @Child(name = "content", type = {}, order=2, min=0, max=Child.MAX_UNLIMITED, modifier=false, summary=false)
        @Description(shortDefinition="What is  in the package?", formalDefinition="A set of components that go to make up the described item." )
        protected List<MedicationPackageContentComponent> content;

        private static final long serialVersionUID = 503772472L;

    /*
     * Constructor
     */
      public MedicationPackageComponent() {
        super();
      }

        /**
         * @return {@link #container} (The kind of container that this package comes as.)
         */
        public CodeableConcept getContainer() {
          if (this.container == null)
            if (Configuration.errorOnAutoCreate())
              throw new Error("Attempt to auto-create MedicationPackageComponent.container");
            else if (Configuration.doAutoCreate())
              this.container = new CodeableConcept(); // cc
          return this.container;
        }

        public boolean hasContainer() {
          return this.container != null && !this.container.isEmpty();
        }

        /**
         * @param value {@link #container} (The kind of container that this package comes as.)
         */
        public MedicationPackageComponent setContainer(CodeableConcept value) {
          this.container = value;
          return this;
        }

        /**
         * @return {@link #content} (A set of components that go to make up the described item.)
         */
        public List<MedicationPackageContentComponent> getContent() {
          if (this.content == null)
            this.content = new ArrayList<MedicationPackageContentComponent>();
          return this.content;
        }

        public boolean hasContent() {
          if (this.content == null)
            return false;
          for (MedicationPackageContentComponent item : this.content)
            if (!item.isEmpty())
              return true;
          return false;
        }

        /**
         * @return {@link #content} (A set of components that go to make up the described item.)
         */
    // syntactic sugar
        public MedicationPackageContentComponent addContent() { //3
          MedicationPackageContentComponent t = new MedicationPackageContentComponent();
          if (this.content == null)
            this.content = new ArrayList<MedicationPackageContentComponent>();
          this.content.add(t);
          return t;
        }

    // syntactic sugar
        public MedicationPackageComponent addContent(MedicationPackageContentComponent t) { //3
          if (t == null)
            return this;
          if (this.content == null)
            this.content = new ArrayList<MedicationPackageContentComponent>();
          this.content.add(t);
          return this;
        }

        protected void listChildren(List<Property> childrenList) {
          super.listChildren(childrenList);
          childrenList.add(new Property("container", "CodeableConcept", "The kind of container that this package comes as.", 0, java.lang.Integer.MAX_VALUE, container));
          childrenList.add(new Property("content", "", "A set of components that go to make up the described item.", 0, java.lang.Integer.MAX_VALUE, content));
        }

      public MedicationPackageComponent copy() {
        MedicationPackageComponent dst = new MedicationPackageComponent();
        copyValues(dst);
        dst.container = container == null ? null : container.copy();
        if (content != null) {
          dst.content = new ArrayList<MedicationPackageContentComponent>();
          for (MedicationPackageContentComponent i : content)
            dst.content.add(i.copy());
        };
        return dst;
      }

      @Override
      public boolean equalsDeep(Base other) {
        if (!super.equalsDeep(other))
          return false;
        if (!(other instanceof MedicationPackageComponent))
          return false;
        MedicationPackageComponent o = (MedicationPackageComponent) other;
        return compareDeep(container, o.container, true) && compareDeep(content, o.content, true);
      }

      @Override
      public boolean equalsShallow(Base other) {
        if (!super.equalsShallow(other))
          return false;
        if (!(other instanceof MedicationPackageComponent))
          return false;
        MedicationPackageComponent o = (MedicationPackageComponent) other;
        return true;
      }

      public boolean isEmpty() {
        return super.isEmpty() && (container == null || container.isEmpty()) && (content == null || content.isEmpty())
          ;
      }

  }

    @Block()
    public static class MedicationPackageContentComponent extends BackboneElement implements IBaseBackboneElement {
        /**
         * Identifies one of the items in the package.
         */
        @Child(name = "item", type = {Medication.class}, order=1, min=1, max=1, modifier=false, summary=false)
        @Description(shortDefinition="A product in the package", formalDefinition="Identifies one of the items in the package." )
        protected Reference item;

        /**
         * The actual object that is the target of the reference (Identifies one of the items in the package.)
         */
        protected Medication itemTarget;

        /**
         * The amount of the product that is in the package.
         */
        @Child(name = "amount", type = {SimpleQuantity.class}, order=2, min=0, max=1, modifier=false, summary=false)
        @Description(shortDefinition="How many are in the package?", formalDefinition="The amount of the product that is in the package." )
        protected SimpleQuantity amount;

        private static final long serialVersionUID = -1150048030L;

    /*
     * Constructor
     */
      public MedicationPackageContentComponent() {
        super();
      }

    /*
     * Constructor
     */
      public MedicationPackageContentComponent(Reference item) {
        super();
        this.item = item;
      }

        /**
         * @return {@link #item} (Identifies one of the items in the package.)
         */
        public Reference getItem() {
          if (this.item == null)
            if (Configuration.errorOnAutoCreate())
              throw new Error("Attempt to auto-create MedicationPackageContentComponent.item");
            else if (Configuration.doAutoCreate())
              this.item = new Reference(); // cc
          return this.item;
        }

        public boolean hasItem() {
          return this.item != null && !this.item.isEmpty();
        }

        /**
         * @param value {@link #item} (Identifies one of the items in the package.)
         */
        public MedicationPackageContentComponent setItem(Reference value) {
          this.item = value;
          return this;
        }

        /**
         * @return {@link #item} The actual object that is the target of the reference. The reference library doesn't populate this, but you can use it to hold the resource if you resolve it. (Identifies one of the items in the package.)
         */
        public Medication getItemTarget() {
          if (this.itemTarget == null)
            if (Configuration.errorOnAutoCreate())
              throw new Error("Attempt to auto-create MedicationPackageContentComponent.item");
            else if (Configuration.doAutoCreate())
              this.itemTarget = new Medication(); // aa
          return this.itemTarget;
        }

        /**
         * @param value {@link #item} The actual object that is the target of the reference. The reference library doesn't use these, but you can use it to hold the resource if you resolve it. (Identifies one of the items in the package.)
         */
        public MedicationPackageContentComponent setItemTarget(Medication value) {
          this.itemTarget = value;
          return this;
        }

        /**
         * @return {@link #amount} (The amount of the product that is in the package.)
         */
        public SimpleQuantity getAmount() {
          if (this.amount == null)
            if (Configuration.errorOnAutoCreate())
              throw new Error("Attempt to auto-create MedicationPackageContentComponent.amount");
            else if (Configuration.doAutoCreate())
              this.amount = new SimpleQuantity(); // cc
          return this.amount;
        }

        public boolean hasAmount() {
          return this.amount != null && !this.amount.isEmpty();
        }

        /**
         * @param value {@link #amount} (The amount of the product that is in the package.)
         */
        public MedicationPackageContentComponent setAmount(SimpleQuantity value) {
          this.amount = value;
          return this;
        }

        protected void listChildren(List<Property> childrenList) {
          super.listChildren(childrenList);
          childrenList.add(new Property("item", "Reference(Medication)", "Identifies one of the items in the package.", 0, java.lang.Integer.MAX_VALUE, item));
          childrenList.add(new Property("amount", "SimpleQuantity", "The amount of the product that is in the package.", 0, java.lang.Integer.MAX_VALUE, amount));
        }

      public MedicationPackageContentComponent copy() {
        MedicationPackageContentComponent dst = new MedicationPackageContentComponent();
        copyValues(dst);
        dst.item = item == null ? null : item.copy();
        dst.amount = amount == null ? null : amount.copy();
        return dst;
      }

      @Override
      public boolean equalsDeep(Base other) {
        if (!super.equalsDeep(other))
          return false;
        if (!(other instanceof MedicationPackageContentComponent))
          return false;
        MedicationPackageContentComponent o = (MedicationPackageContentComponent) other;
        return compareDeep(item, o.item, true) && compareDeep(amount, o.amount, true);
      }

      @Override
      public boolean equalsShallow(Base other) {
        if (!super.equalsShallow(other))
          return false;
        if (!(other instanceof MedicationPackageContentComponent))
          return false;
        MedicationPackageContentComponent o = (MedicationPackageContentComponent) other;
        return true;
      }

      public boolean isEmpty() {
        return super.isEmpty() && (item == null || item.isEmpty()) && (amount == null || amount.isEmpty())
          ;
      }

  }

    /**
     * A code (or set of codes) that specify this medication, or a textual description if no code is available. Usage note: This could be a standard medication code such as a code from RxNorm, SNOMED CT, IDMP etc. It could also be a national or local formulary code, optionally with translations to other code systems.
     */
    @Child(name = "code", type = {CodeableConcept.class}, order=0, min=0, max=1, modifier=false, summary=true)
    @Description(shortDefinition="Codes that identify this medication", formalDefinition="A code (or set of codes) that specify this medication, or a textual description if no code is available. Usage note: This could be a standard medication code such as a code from RxNorm, SNOMED CT, IDMP etc. It could also be a national or local formulary code, optionally with translations to other code systems." )
    protected CodeableConcept code;

    /**
     * Set to true if the item is attributable to a specific manufacturer.
     */
    @Child(name = "isBrand", type = {BooleanType.class}, order=1, min=0, max=1, modifier=false, summary=true)
    @Description(shortDefinition="True if a brand", formalDefinition="Set to true if the item is attributable to a specific manufacturer." )
    protected BooleanType isBrand;

    /**
     * Describes the details of the manufacturer.
     */
    @Child(name = "manufacturer", type = {Organization.class}, order=2, min=0, max=1, modifier=false, summary=true)
    @Description(shortDefinition="Manufacturer of the item", formalDefinition="Describes the details of the manufacturer." )
    protected Reference manufacturer;

    /**
     * The actual object that is the target of the reference (Describes the details of the manufacturer.)
     */
    protected Organization manufacturerTarget;

    /**
     * Information that only applies to products (not packages).
     */
    @Child(name = "product", type = {}, order=3, min=0, max=1, modifier=false, summary=false)
    @Description(shortDefinition="Administrable medication details", formalDefinition="Information that only applies to products (not packages)." )
    protected MedicationProductComponent product;

    /**
     * Information that only applies to packages (not products).
     */
    @Child(name = "package", type = {}, order=4, min=0, max=1, modifier=false, summary=false)
    @Description(shortDefinition="Details about packaged medications", formalDefinition="Information that only applies to packages (not products)." )
    protected MedicationPackageComponent package_;

    private static final long serialVersionUID = 859308699L;

  /*
   * Constructor
   */
    public Medication() {
      super();
    }

    /**
     * @return {@link #code} (A code (or set of codes) that specify this medication, or a textual description if no code is available. Usage note: This could be a standard medication code such as a code from RxNorm, SNOMED CT, IDMP etc. It could also be a national or local formulary code, optionally with translations to other code systems.)
     */
    public CodeableConcept getCode() {
      if (this.code == null)
        if (Configuration.errorOnAutoCreate())
          throw new Error("Attempt to auto-create Medication.code");
        else if (Configuration.doAutoCreate())
          this.code = new CodeableConcept(); // cc
      return this.code;
    }

    public boolean hasCode() {
      return this.code != null && !this.code.isEmpty();
    }

    /**
     * @param value {@link #code} (A code (or set of codes) that specify this medication, or a textual description if no code is available. Usage note: This could be a standard medication code such as a code from RxNorm, SNOMED CT, IDMP etc. It could also be a national or local formulary code, optionally with translations to other code systems.)
     */
    public Medication setCode(CodeableConcept value) {
      this.code = value;
      return this;
    }

    /**
     * @return {@link #isBrand} (Set to true if the item is attributable to a specific manufacturer.). This is the underlying object with id, value and extensions. The accessor "getIsBrand" gives direct access to the value
     */
    public BooleanType getIsBrandElement() {
      if (this.isBrand == null)
        if (Configuration.errorOnAutoCreate())
          throw new Error("Attempt to auto-create Medication.isBrand");
        else if (Configuration.doAutoCreate())
          this.isBrand = new BooleanType(); // bb
      return this.isBrand;
    }

    public boolean hasIsBrandElement() {
      return this.isBrand != null && !this.isBrand.isEmpty();
    }

    public boolean hasIsBrand() {
      return this.isBrand != null && !this.isBrand.isEmpty();
    }

    /**
     * @param value {@link #isBrand} (Set to true if the item is attributable to a specific manufacturer.). This is the underlying object with id, value and extensions. The accessor "getIsBrand" gives direct access to the value
     */
    public Medication setIsBrandElement(BooleanType value) {
      this.isBrand = value;
      return this;
    }

    /**
     * @return Set to true if the item is attributable to a specific manufacturer.
     */
    public boolean getIsBrand() {
      return this.isBrand == null || this.isBrand.isEmpty() ? false : this.isBrand.getValue();
    }

    /**
     * @param value Set to true if the item is attributable to a specific manufacturer.
     */
    public Medication setIsBrand(boolean value) {
        if (this.isBrand == null)
          this.isBrand = new BooleanType();
        this.isBrand.setValue(value);
      return this;
    }

    /**
     * @return {@link #manufacturer} (Describes the details of the manufacturer.)
     */
    public Reference getManufacturer() {
      if (this.manufacturer == null)
        if (Configuration.errorOnAutoCreate())
          throw new Error("Attempt to auto-create Medication.manufacturer");
        else if (Configuration.doAutoCreate())
          this.manufacturer = new Reference(); // cc
      return this.manufacturer;
    }

    public boolean hasManufacturer() {
      return this.manufacturer != null && !this.manufacturer.isEmpty();
    }

    /**
     * @param value {@link #manufacturer} (Describes the details of the manufacturer.)
     */
    public Medication setManufacturer(Reference value) {
      this.manufacturer = value;
      return this;
    }

    /**
     * @return {@link #manufacturer} The actual object that is the target of the reference. The reference library doesn't populate this, but you can use it to hold the resource if you resolve it. (Describes the details of the manufacturer.)
     */
    public Organization getManufacturerTarget() {
      if (this.manufacturerTarget == null)
        if (Configuration.errorOnAutoCreate())
          throw new Error("Attempt to auto-create Medication.manufacturer");
        else if (Configuration.doAutoCreate())
          this.manufacturerTarget = new Organization(); // aa
      return this.manufacturerTarget;
    }

    /**
     * @param value {@link #manufacturer} The actual object that is the target of the reference. The reference library doesn't use these, but you can use it to hold the resource if you resolve it. (Describes the details of the manufacturer.)
     */
    public Medication setManufacturerTarget(Organization value) {
      this.manufacturerTarget = value;
      return this;
    }

    /**
     * @return {@link #product} (Information that only applies to products (not packages).)
     */
    public MedicationProductComponent getProduct() {
      if (this.product == null)
        if (Configuration.errorOnAutoCreate())
          throw new Error("Attempt to auto-create Medication.product");
        else if (Configuration.doAutoCreate())
          this.product = new MedicationProductComponent(); // cc
      return this.product;
    }

    public boolean hasProduct() {
      return this.product != null && !this.product.isEmpty();
    }

    /**
     * @param value {@link #product} (Information that only applies to products (not packages).)
     */
    public Medication setProduct(MedicationProductComponent value) {
      this.product = value;
      return this;
    }

    /**
     * @return {@link #package_} (Information that only applies to packages (not products).)
     */
    public MedicationPackageComponent getPackage() {
      if (this.package_ == null)
        if (Configuration.errorOnAutoCreate())
          throw new Error("Attempt to auto-create Medication.package_");
        else if (Configuration.doAutoCreate())
          this.package_ = new MedicationPackageComponent(); // cc
      return this.package_;
    }

    public boolean hasPackage() {
      return this.package_ != null && !this.package_.isEmpty();
    }

    /**
     * @param value {@link #package_} (Information that only applies to packages (not products).)
     */
    public Medication setPackage(MedicationPackageComponent value) {
      this.package_ = value;
      return this;
    }

      protected void listChildren(List<Property> childrenList) {
        super.listChildren(childrenList);
        childrenList.add(new Property("code", "CodeableConcept", "A code (or set of codes) that specify this medication, or a textual description if no code is available. Usage note: This could be a standard medication code such as a code from RxNorm, SNOMED CT, IDMP etc. It could also be a national or local formulary code, optionally with translations to other code systems.", 0, java.lang.Integer.MAX_VALUE, code));
        childrenList.add(new Property("isBrand", "boolean", "Set to true if the item is attributable to a specific manufacturer.", 0, java.lang.Integer.MAX_VALUE, isBrand));
        childrenList.add(new Property("manufacturer", "Reference(Organization)", "Describes the details of the manufacturer.", 0, java.lang.Integer.MAX_VALUE, manufacturer));
        childrenList.add(new Property("product", "", "Information that only applies to products (not packages).", 0, java.lang.Integer.MAX_VALUE, product));
        childrenList.add(new Property("package", "", "Information that only applies to packages (not products).", 0, java.lang.Integer.MAX_VALUE, package_));
      }

      public Medication copy() {
        Medication dst = new Medication();
        copyValues(dst);
        dst.code = code == null ? null : code.copy();
        dst.isBrand = isBrand == null ? null : isBrand.copy();
        dst.manufacturer = manufacturer == null ? null : manufacturer.copy();
        dst.product = product == null ? null : product.copy();
        dst.package_ = package_ == null ? null : package_.copy();
        return dst;
      }

      protected Medication typedCopy() {
        return copy();
      }

      @Override
      public boolean equalsDeep(Base other) {
        if (!super.equalsDeep(other))
          return false;
        if (!(other instanceof Medication))
          return false;
        Medication o = (Medication) other;
        return compareDeep(code, o.code, true) && compareDeep(isBrand, o.isBrand, true) && compareDeep(manufacturer, o.manufacturer, true)
           && compareDeep(product, o.product, true) && compareDeep(package_, o.package_, true);
      }

      @Override
      public boolean equalsShallow(Base other) {
        if (!super.equalsShallow(other))
          return false;
        if (!(other instanceof Medication))
          return false;
        Medication o = (Medication) other;
        return compareValues(isBrand, o.isBrand, true);
      }

      public boolean isEmpty() {
        return super.isEmpty() && (code == null || code.isEmpty()) && (isBrand == null || isBrand.isEmpty())
           && (manufacturer == null || manufacturer.isEmpty()) && (product == null || product.isEmpty())
           && (package_ == null || package_.isEmpty());
      }

  @Override
  public ResourceType getResourceType() {
    return ResourceType.Medication;
   }

  @SearchParamDefinition(name="container", path="Medication.package.container", description="E.g. box, vial, blister-pack", type="token" )
  public static final String SP_CONTAINER = "container";
  @SearchParamDefinition(name="code", path="Medication.code", description="Codes that identify this medication", type="token" )
  public static final String SP_CODE = "code";
  @SearchParamDefinition(name="ingredient", path="Medication.product.ingredient.item", description="The product contained", type="reference" )
  public static final String SP_INGREDIENT = "ingredient";
  @SearchParamDefinition(name="form", path="Medication.product.form", description="powder | tablets | carton +", type="token" )
  public static final String SP_FORM = "form";
  @SearchParamDefinition(name="content", path="Medication.package.content.item", description="A product in the package", type="reference" )
  public static final String SP_CONTENT = "content";
  @SearchParamDefinition(name="manufacturer", path="Medication.manufacturer", description="Manufacturer of the item", type="reference" )
  public static final String SP_MANUFACTURER = "manufacturer";

}


text:
class CommentsController < ApplicationController
  before_filter :authorize, :only => [:edit, :update, :destroy]

  def index
    @comments = Comment.recent.all(:limit => 30)
    respond_to do |format|
      format.html
      format.rss
    end
  end

  def new
    flash[:notice] = "To submit a comment, please go to a specific episode first."
    redirect_to root_url
  end

  def create
    @comment = Comment.new(params[:comment])
    if params[:preview_button].nil? && params[:not_spam] && params[:email].blank? # fake email to catch spammers
      @comment.request = request
      if @comment.save
        flash[:notice] = "Successfully created comment."
        redirect_to @comment.episode
      else
        render :action => 'new'
      end
    else
      flash.now[:error] = "Caught by spam filter. Make sure javascript is enabled. If it still doesn't work, please let me know: ryan [at] railscasts [dot] com." unless params[:preview_button]
      render :action => 'new'
    end
  end

  def edit
    @comment = Comment.find(params[:id])
  end

  def update
    @comment = Comment.find(params[:id])
    if @comment.update_attributes(params[:comment])
      flash[:notice] = "Successfully updated comment."
      redirect_to @comment.episode
    else
      render :action => 'edit'
    end
  end

  def destroy
    @comment = Comment.find(params[:id])
    @comment.destroy
    flash[:notice] = "Successfully destroyed comment."
    redirect_to comments_path
  end
end