text:
"""Create an API definition by interpreting a discovery document.

This module interprets a discovery document to create a tree of classes which
represent the API structure in a way that is useful for generating a library.
For each discovery element (e.g. schemas, resources, methods, ...) there is
a class to represent it which is directly usable in the templates. The
instances of those classes are annotated with extra variables for use
in the template which are language specific.

The current way to make use of this class is to create a programming language
specific subclass of Api, which adds annotations and template variables
appropriate for that language.
TODO(user): Refactor this so that the API can be loaded first, then annotated.
"""

__author__ = 'aiuto@google.com (Tony Aiuto)'

import json
import logging
import operator
import urlparse

from googleapis.codegen import data_types
from googleapis.codegen import template_objects
from googleapis.codegen import utilities
from googleapis.codegen.api_exception import ApiException
from googleapis.codegen.schema import Schema
from googleapis.codegen.utilities import convert_size

_DEFAULT_SERVICE_HOST = 'www.googleapis.com'
_DEFAULT_OWNER_DOMAIN = 'google.com'
_DEFAULT_OWNER_NAME = 'Google'

_RECOGNIZED_GOOGLE_DOMAINS = (
    'google.com',
    'googleapis.com',
    'googleplex.com'
)

_LOGGER = logging.getLogger('codegen')

class Api(template_objects.CodeObject):
  """An API definition.

  This class holds a discovery centric definition of an API. It contains
  members such as "resources" and "schemas" which relate directly to discovery
  concepts. It defines several properties that can be used in code generation
  templates:
    name: The API name.
    version: The API version.
    versionNoDots: The API version with all '.' characters replaced with '_'.
        This is typically used in class names.
    versionNoDash: The API version with all '-' characters replaced with '_'.
        This is typically used in file names where '-' has meaning.

    authScopes: The list of the OAuth scopes used by this API.
    dataWrapper: True if the API definition contains the 'dataWrapper' feature.
    methods: The list of top level API methods.
    models: The list of API data models, both from the schema section of
      discovery and from anonymous objects defined in method definitions.
    parameters: The list of global method parameters (applicable to all methods)
    resources: The list of API resources
  """

  def __init__(self, discovery_doc, language=None):
    super(Api, self).__init__(discovery_doc, self,
                              wire_name=discovery_doc['name'])
    name = self.values['name']
    self._validator.ValidateApiName(name)
    if name != 'freebase':
      self._validator.ValidateApiVersion(self.values['version'])
    canonical_name = self.values.get('canonicalName', name)
    if not self.values.get('canonicalName'):
      self.values['canonicalName'] = canonical_name
    self._class_name = self.ToClassName(canonical_name, self)
    # Guard against language implementor not taking care of spaces
    self._class_name = self._class_name.replace(' ', '')
    self._NormalizeOwnerInformation()
    self._language = language
    self._template_dir = None
    self._surface_features = {}
    self._schemas = {}
    self._methods_by_name = {}
    self._all_methods = []

    self.SetTemplateValue('className', self._class_name)
    self.SetTemplateValue('versionNoDots',
                          self.values['version'].replace('.', '_'))
    self.SetTemplateValue('versionNoDash',
                          self.values['version'].replace('-', '_'))
    self.SetTemplateValue('dataWrapper',
                          'dataWrapper' in discovery_doc.get('features', []))
    self.values.setdefault('title', name)
    self.values.setdefault('exponentialBackoffDefault', False)
    if not self.values.get('revision'):
      self.values['revision'] = 'snapshot'

    self._NormalizeUrlComponents()

    # Information for variant subtypes, a dictionary of the format:
    #
    #  { 'wireName': {'discriminant': discriminant, 'value': value,
    #                 'schema': schema},
    #    ... }
    #
    # ... where wireName is the name of variant subtypes, discriminant
    # the field name of the discriminant, value the discriminant value
    # for this variant, and schema the base schema.
    #
    # This information cannot be stored in the referred schema at
    # reading time because at the time we read it from the base
    # schema, the referenced variant schemas may not yet be loaded. So
    # we first store it here, and after all schemas have been loaded,
    # update the schema template properties.
    self._variant_info = {}

    # Build data types and methods
    self._SetupModules()
    self.void_type = data_types.Void(self)
    self._BuildSchemaDefinitions()
    self._BuildResourceDefinitions()
    self.SetTemplateValue('resources', self._resources)

    # Make data models part of the api dictionary
    self.SetTemplateValue('models', self.ModelClasses())

    # Replace methods dict with Methods
    self._top_level_methods = []
    method_dict = self.values.get('methods') or {}
    for name in sorted(method_dict):
      self._top_level_methods.append(Method(self, name, method_dict[name]))
    self.SetTemplateValue('methods', self._top_level_methods)

    # Global parameters
    self._parameters = []
    param_dict = self.values.get('parameters') or {}
    for name in sorted(param_dict):
      parameter = Parameter(self, name, param_dict[name], self)
      self._parameters.append(parameter)
      if name == 'alt':
        self.SetTemplateValue('alt', parameter)
    self.SetTemplateValue('parameters', self._parameters)

    # Auth scopes
    self._authscopes = []
    if (self.values.get('auth') and
        self.values['auth'].get('oauth2') and
        self.values['auth']['oauth2'].get('scopes')):
      for value, auth_dict in sorted(
          self.values['auth']['oauth2']['scopes'].iteritems()):
        self._authscopes.append(AuthScope(self, value, auth_dict))
      self.SetTemplateValue('authscopes', self._authscopes)

  @property
  def all_schemas(self):
    """The dictionary of all the schema objects found in the API."""
    return self._schemas

  def _SetupModules(self):
    """Compute and set the module(s) which this API belongs under."""
    # The containing module is based on the owner information.
    path = self.values.get('modulePath') or self.values.get('packagePath')
    self._containing_module = template_objects.Module(
        package_path=path,
        owner_name=self.values.get('owner'),
        owner_domain=self.values.get('ownerDomain'))
    self.SetTemplateValue('containingModule', self._containing_module)

    # The API is a child of the containing_module
    base = self.values['name']
    # TODO(user): Introduce a breaking change where we always prefer
    # canonicalName.
    if self.values.get('packagePath'):
      # Lowercase the canonical name only for non-cloud-endpoints Google APIs.
      # This is to avoid breaking changes to existing Google-owned Cloud
      # Endpoints APIs.
      if self.values.get('rootUrl').find('.googleapis.com') > 0:
        base = self.values.get('canonicalName').lower() or base
      else:
        base = self.values.get('canonicalName') or base
    if self.values.get('version_module'):
      base = '%s/%s' % (base, self.values['versionNoDots'])
    self._module = template_objects.Module(package_path=base,
                                           parent=self._containing_module)
    self.SetTemplateValue('module', self._module)

    # The default module for data models defined by this API.
    self._model_module = template_objects.Module(package_path=None,
                                                 parent=self._module)

  def _BuildResourceDefinitions(self):
    """Loop over the resources in the discovery doc and build definitions."""
    self._resources = []
    def_dict = self.values.get('resources') or {}
    for name in sorted(def_dict):
      resource = Resource(self, name, def_dict[name], parent=self)
      self._resources.append(resource)

  def _BuildSchemaDefinitions(self):
    """Loop over the schemas in the discovery doc and build definitions."""
    schemas = self.values.get('schemas')
    if schemas:
      for name, def_dict in schemas.iteritems():
        # Upgrade the string format schema to a dict.
        if isinstance(def_dict, unicode):
          def_dict = json.loads(def_dict)
        self._schemas[name] = self.DataTypeFromJson(def_dict, name)

      # Late bind info for variant types, and mark the discriminant
      # field and value.
      for name, info in self._variant_info.iteritems():
        if name not in self._schemas:
          # The error will be reported elsewhere
          continue
        schema = self._schemas[name]
        for prop in schema.values.get('properties'):
          if prop.values['wireName'] == info['discriminant']:
            # Filter out the discriminant property as it is already
            # contained in the base type.
            schema.SetTemplateValue(
                'properties',
                [p for p in schema.values.get('properties') if p != prop])
            break
        else:
          logging.warn("Variant schema '%s' for base schema '%s' "
                       "has not the expected discriminant property '%s'.",
                       name, info['schema'].values['wireName'],
                       info['discriminant'])
        schema.SetTemplateValue('superClass', info['schema'].class_name)
        # TODO(user): baseType is for backwards compatability only. It should
        # have always been a different name. When the old Java generators roll
        # off, remove it.
        schema.SetTemplateValue('baseType', info['schema'].class_name)
        schema.SetTemplateValue('discriminantValue', info['value'])

  def _NormalizeOwnerInformation(self):
    """Ensure that owner and ownerDomain are set to sane values."""
    owner_domain = self.get('ownerDomain', '')
    if not owner_domain:
      root_url = self.get('rootUrl')
      if root_url:
        owner_domain = urlparse.urlparse(root_url).hostname
        # Normalize google domains.
        if any(owner_domain.endswith(d) for d in _RECOGNIZED_GOOGLE_DOMAINS):
          owner_domain = 'google.com'
    if owner_domain:
      owner_domain = utilities.SanitizeDomain(owner_domain)
    else:
      owner_domain = _DEFAULT_OWNER_DOMAIN

    self.SetTemplateValue('ownerDomain', owner_domain)
    if not self.get('ownerName'):
      if owner_domain == _DEFAULT_OWNER_DOMAIN:
        owner_name = _DEFAULT_OWNER_NAME
      else:
        owner_name = owner_domain.replace('.', '_')
      self.SetTemplateValue('ownerName', owner_name)
    if not self.get('owner'):
      self.SetTemplateValue('owner', self['ownerName'].lower())

  def _NormalizeUrlComponents(self):
    """Sets template values concerning the path to the service.

    Sets rootUrl and servicePath from the values given or defaults based on what
    is available. Verifies them for safeness.  The hierarchy of the possible
    inputs is:
      use rootUrl + servicePath as the best choice if it exists (v1new)
      or rpcPath
      or use baseUrl (v1)
      or use basePath (v1)
      or restBasePath (v0.3)
      or default to 'api/version'

    Raises:
      ValueError: if the values available are inconsistent or disallowed.
    """
    # If both rootUrl and servicePath exist, they equal what is in baseUrl.
    root_url = self.values.get('rootUrl')
    service_path = self.values.get('servicePath')
    rpc_path = self.values.get('rpcPath')
    if root_url:
      # oauth2 has a servicePath of "". This is wierd but OK for that API, but
      # it means we must explicitly check against None.
      if service_path is not None:
        base_url = root_url + service_path
      elif rpc_path:
        base_url = rpc_path
      else:
        raise ValueError('Neither servicePath nor rpcPath is defined.')
    else:
      base_url = self.values.get('baseUrl')

    # If we have a full path ('https://superman.appspot.com/kryptonite/hurts'),
    # then go with that, otherwise just use the various things which might
    # hint at the servicePath.
    best_path = (base_url
                 or self.values.get('basePath')
                 or self.values.get('restBasePath')
                 or '/%s/%s/' % (self.values['name'], self.values['version']))
    if best_path.find('..') >= 0:
      raise ValueError('api path must not contain ".." (%s)' % best_path)
    # And let urlparse to the grunt work of normalizing and parsing.
    url_parts = urlparse.urlparse(best_path)

    scheme = url_parts.scheme or 'https'
    service_host = url_parts.netloc or _DEFAULT_SERVICE_HOST
    base_path = url_parts.path
    if not root_url:
      self._api.SetTemplateValue('rootUrl', '%s://%s/' % (scheme, service_host))
    if service_path is None:
      self._api.SetTemplateValue('servicePath', base_path[1:])

    # Make sure template writers do not revert
    self._api.DeleteTemplateValue('baseUrl')
    self._api.DeleteTemplateValue('basePath')
    self._api.DeleteTemplateValue('serviceHost')

  def ModelClasses(self):
    """Return all the model classes."""
    ret = set(
        s for s in self._schemas.itervalues()
        if isinstance(s, Schema) or isinstance(s, data_types.MapDataType))
    return sorted(ret, key=operator.attrgetter('class_name'))

  def TopLevelModelClasses(self):
    """Return the models which are not children of another model."""
    return [m for m in self.ModelClasses() if not m.parent]

  def DataTypeFromJson(self, type_dict, default_name, parent=None,
                       wire_name=None):
    """Returns a schema object represented by a JSON Schema dictionary.

    Evaluate a JSON schema dictionary and return an appropriate schema object.
    If a data type is defined in-line, then create the schema dynamically. If
    the schema is a $ref to another, return the previously created schema or
    a lazy reference.

    If the type_dict is None, a blank schema will be created.

    Args:
      type_dict: A dict of the form expected of a request or response member
        of a method description.   See the Discovery specification for more.
      default_name: The unique name to give the schema if we have to create it.
      parent: The schema where I was referenced. If we cannot determine that
        this is a top level schema, set the parent to this.
      wire_name: The name which will identify objects of this type in data on
        the wire.
    Returns:
      A Schema object.
    """

    # new or not initialized, create a fresh one
    schema = Schema.Create(self, default_name, type_dict or {}, wire_name,
                           parent)
    # Only put it in our by-name list if it is a real object
    if isinstance(schema, Schema) or isinstance(schema, data_types.MapDataType):
      # Use the path to the schema as a key. This means that an anonymous class
      # for the 'person' property under the schema 'Activity' will have the
      # unique name 'Activity.person', rather than 'ActivityPerson'.
      path = '.'.join(
          [a.values.get('wireName', '<anon>') for a in schema.full_path])
      _LOGGER.debug('DataTypeFromJson: add %s to cache', path)
      self._schemas[path] = schema
    return schema

  def AddMethod(self, method):
    """Add a new method to the set of all methods."""
    self._all_methods.append(method)
    self._methods_by_name[method.values['rpcMethod']] = method

  def MethodByName(self, method_name):
    """Find a method by name.

    Args:
      method_name: (str) the full RPC name of a method defined by this API.

    Returns:
      Method object or None if not found.
    """
    return self._methods_by_name.get(method_name)

  def SchemaByName(self, schema_name):
    """Find a schema by name.

    Args:
      schema_name: (str) name of a schema defined by this API.

    Returns:
      Schema object or None if not found.
    """
    return self._schemas.get(schema_name, None)

  def SetVariantInfo(self, ref, discriminant, value, schema):
    """Sets variant info for the given reference."""
    if ref in self._variant_info:
      logging.warning("Base type of '%s' changed from '%s' to '%s'. "
                      "This is an indication that a variant schema is used "
                      "from multiple base schemas and may result in an "
                      "inconsistent model.",
                      ref, self._base_type[ref].wireName, schema.wireName)
    self._variant_info[ref] = {'discriminant': discriminant, 'value': value,
                               'schema': schema}

  def VisitAll(self, func):
    """Visit all nodes of an API tree and apply a function to each.

    Walks a tree and calls a function on each element of it. This should be
    called after the API is fully loaded.

    Args:
      func: (function) Method to call on each object.
    """
    _LOGGER.debug('Applying function to all nodes')
    func(self._containing_module)
    func(self._module)
    func(self._model_module)
    for resource in self.values['resources']:
      self._VisitResource(resource, func)
    # Top level methods
    for method in self.values['methods']:
      self._VisitMethod(method, func)
    for parameter in self.values['parameters']:
      func(parameter)
      func(parameter.data_type)
    for schema in self._schemas.values():
      self._VisitSchema(schema, func)
    for scope in self.GetTemplateValue('authscopes') or []:
      func(scope)

  def _VisitMethod(self, method, func):
    """Visit a method, calling a function on every child.

    Args:
      method: (Method) The Method to visit.
      func: (function) Method to call on each object.
    """
    func(method)
    for parameter in method.parameters:
      func(parameter)

  def _VisitResource(self, resource, func):
    """Visit a resource tree, calling a function on every child.

    Calls down recursively to sub resources.

    Args:
      resource: (Resource) The Resource to visit.
      func: (function) Method to call on each object.
    """
    func(resource)
    for method in resource.values['methods']:
      self._VisitMethod(method, func)
    for r in resource.values['resources']:
      self._VisitResource(r, func)

  def _VisitSchema(self, schema, func):
    """Visit a schema tree, calling a function on every child.

    Args:
      schema: (Schema) The Schema to visit.
      func: (function) Method to call on each object.
    """
    func(schema)
    func(schema.module)
    for prop in schema.values.get('properties', []):
      func(prop)
    for child in self.children:
      func(child)

  # Do not warn about unused arguments, pylint: disable=unused-argument
  def ToClassName(self, s, element, element_type=None):
    """Convert a name to a suitable class name in the target language.

    This default implementation camel cases the string, which is appropriate
    for some languages.  Subclasses are encouraged to override this.

    Args:
      s: (str) A rosy name of data element.
      element: (object) The object we are making a class name for.
      element_type: (str) Deprecated. The kind of object we are making a class
        name for.  E.g. resource, method, schema.
        TODO(user): replace type in favor of class of element, but that will
        require changing the place where we call ToClassName with no element.
    Returns:
      A name suitable for use as a class in the generator's target language.
    """
    return utilities.CamelCase(s).replace(' ', '')

  def NestedClassNameForProperty(self, name, schema):
    """Returns the class name of an object nested in a property."""
    # TODO(user): This functionality belongs in the language model, but
    # because of the way the api is bootstrapped, that isn't available when we
    # need it.  When language model is available from the start, this should be
    # moved.
    return '%s%s' % (schema.class_name, utilities.CamelCase(name))

  @property
  def class_name(self):
    return self.values['className']

  @property
  def model_module(self):
    return self._model_module

  @property
  def containing_module(self):
    return self._containing_module

  @property
  def all_methods(self):
    """All the methods in the entire API."""
    return self._all_methods

  @property
  def top_level_methods(self):
    """All the methods at the API top level (not in a resource)."""
    return self._top_level_methods

class Resource(template_objects.CodeObject):

  def __init__(self, api, name, def_dict, parent=None):
    """Creates a Resource.

    Args:
      api: (Api) The Api which owns this Resource.
      name: (string) The discovery name of the Resource.
      def_dict: (dict) The discovery dictionary for this Resource.
      parent: (CodeObject) The resource containing this method, if any. Top
         level resources have the API as a parent.
    """
    super(Resource, self).__init__(def_dict, api, parent=parent, wire_name=name)
    self.ValidateName(name)
    class_name = api.ToClassName(name, self, element_type='resource')
    self.SetTemplateValue('className', class_name)
    # Replace methods dict with Methods
    self._methods = []
    method_dict = self.values.get('methods') or {}
    for name in sorted(method_dict):
      self._methods.append(Method(api, name, method_dict[name], parent=self))
    self.SetTemplateValue('methods', self._methods)
    # Get sub resources
    self._resources = []
    r_def_dict = self.values.get('resources') or {}
    for name in sorted(r_def_dict):
      r = Resource(api, name, r_def_dict[name], parent=self)
      self._resources.append(r)
    self.SetTemplateValue('resources', self._resources)

  @property
  def methods(self):
    return self._methods

  @property
  def methods_dict(self):
    return {method['wireName']: method for method in self._methods}

class AuthScope(template_objects.CodeObject):
  """The definition of an auth scope.

  An AuthScope defines these template values
    value: The scope url
    name: a sanitized version of the value, transformed so it generally can
          be used as an indentifier in code. Deprecated, use constantName
    description: the description of the scope.
  It also provides a template property which can be used after a language
  binding is set.
    constantName: A transformation of the value so it is suitable as a constant
                  name in the specific language.
  """

  GOOGLE_PREFIX = 'https://www.googleapis.com/auth/'
  HTTPS_PREFIX = 'https://'

  def __init__(self, api, value, def_dict):
    """Construct an auth scope.

    Args:
      api: (Api) The Api which owns this Property
      value: (string) The unique identifier of this scope, often a URL
      def_dict: (dict) The discovery dictionary for this auth scope.
    """
    super(AuthScope, self).__init__(def_dict, api, wire_name=value)
    self._module = api.module
    self.SetTemplateValue('value', value)
    while value.endswith('/'):
      value = value[:-1]
    if 'description' not in self.values:
      self.SetTemplateValue('description', value)

    # Strip the common prefix to get a unique identifying name
    if value.startswith(AuthScope.GOOGLE_PREFIX):
      scope_id = value[len(AuthScope.GOOGLE_PREFIX):]
    elif value.startswith(AuthScope.HTTPS_PREFIX):
      # some comon scopes are are just a URL
      scope_id = value[len(AuthScope.HTTPS_PREFIX):]
    else:
      scope_id = value
    # We preserve the value stripped of the most common prefixes so we can
    # use it for building constantName in templates.
    self.SetTemplateValue('lastPart', scope_id)

    # replace all non alphanumeric with '_' to form 'name'
    name = ''.join([(c if c.isalnum() else '_') for c in scope_id.upper()])
    self.SetTemplateValue('name', name)

  @property
  def constantName(self):  # pylint: disable=g-bad-name
    """Overrides default behavior of constantName."""
    return self._language_model.ApplyPolicy('constant', self,
                                            self.values['lastPart'])

class Method(template_objects.CodeObject):
  """The definition of a method."""

  def __init__(self, api, name, def_dict, parent=None):
    """Construct a method.

    Methods in REST discovery are inside of a resource. Note that the method
    name and id are calculable from each other. id will always be equal to
    api_name.resource_name[.sub_resource...].method_name.  At least it should
    be, as that is the transformation Discovery makes from the API definition,
    which is essentially a flat list of methods, into a hierarchy of resources.

    Args:
      api: (Api) The Api which owns this Method.
      name: (string) The discovery name of the Method.
      def_dict: (dict) The discovery dictionary for this Method.
      parent: (CodeObject) The resource containing this Method, if any.

    Raises:
      ApiException: If the httpMethod type is not one we know how to
          handle.
    """
    super(Method, self).__init__(def_dict, api, parent=(parent or api))
    # TODO(user): Fix java templates to name vs. wireName correctly. Then
    # change the __init__ to have wire_name=def_dict.get('id') or name
    # then eliminate this line.
    self.SetTemplateValue('wireName', name)
    self.ValidateName(name)
    class_name = api.ToClassName(name, self, element_type='method')
    if parent and class_name == parent.values['className']:
      # Some languages complain when the collection name is the same as the
      # method name.
      class_name = '%sRequest' % class_name
    # The name is the key of the dict defining use. The id field is what you
    # have to use to call the method via RPC. That is unique, name might not be.
    self.SetTemplateValue('name', name)
    # Fix up very old discovery, which does not have an id.
    if 'id' not in self.values:
      self.values['id'] = name
    self.SetTemplateValue('className', class_name)
    http_method = def_dict.get('httpMethod', 'POST').upper()
    self.SetTemplateValue('httpMethod', http_method)
    self.SetTemplateValue('rpcMethod',
                          def_dict.get('rpcMethod') or def_dict['id'])
    rest_path = def_dict.get('path') or def_dict.get('restPath')
    # TODO(user): if rest_path is not set, raise a good error and fail fast.
    self.SetTemplateValue('restPath', rest_path)

    # Figure out the input and output types and schemas for this method.
    expected_request = self.values.get('request')
    if expected_request:
      # TODO(user): RequestBody is only used if the schema is anonymous.
      # When we go to nested models, this could be a nested class off the
      # Method, making it unique without the silly name.  Same for ResponseBody.
      request_schema = api.DataTypeFromJson(expected_request,
                                            '%sRequestContent' % name,
                                            parent=self)
      self.SetTemplateValue('requestType', request_schema)

    expected_response = def_dict.get('response') or def_dict.get('returns')
    if expected_response:
      response_schema = api.DataTypeFromJson(expected_response,
                                             '%sResponse' % name,
                                             parent=self)
      if self.values['wireName'] == 'get':
        response_schema.values['associatedResource'] = parent
      self.SetTemplateValue('responseType', response_schema)
    else:
      self.SetTemplateValue('responseType', api.void_type)
    # Make sure we can handle this method type and do any fixups.
    if http_method not in ['DELETE', 'GET', 'OPTIONS', 'PATCH', 'POST', 'PUT',
                           'PROPFIND', 'PROPPATCH', 'REPORT']:
      raise ApiException('Unknown HTTP method: %s' % http_method, def_dict)
    if http_method == 'GET':
      self.SetTemplateValue('requestType', None)

    # Replace parameters dict with Parameters.  We try to order them by their
    # position in the request path so that the generated code can track the
    # more human readable definition, rather than the order of the parameters
    # in the discovery doc.
    order = self.values.get('parameterOrder', [])
    req_parameters = []
    opt_parameters = []
    for name, def_dict in self.values.get('parameters', {}).iteritems():
      param = Parameter(api, name, def_dict, self)
      if name == 'alt':
        # Treat the alt parameter differently
        self.SetTemplateValue('alt', param)
        continue

      # Standard params are part of the generic request class
      # We want to push all parameters that aren't declared inside
      # parameterOrder after those that are.
      if param.values['wireName'] in order:
        req_parameters.append(param)
      else:
        # optional parameters are appended in the order they're declared.
        opt_parameters.append(param)
    # pylint: disable=g-long-lambda
    req_parameters.sort(lambda x, y: cmp(order.index(x.values['wireName']),
                                         order.index(y.values['wireName'])))
    req_parameters.extend(opt_parameters)
    self.SetTemplateValue('parameters', req_parameters)

    self._InitMediaUpload(parent)
    self._InitPageable(api)
    api.AddMethod(self)

  def _InitMediaUpload(self, parent):
    media_upload = self.values.get('mediaUpload')
    if media_upload:
      if parent:
        parent.SetTemplateValue('isMedia', True)
      # Get which MIME Media Ranges are accepted for media uploads to this
      # method.
      accepted_mime_ranges = media_upload.get('accept')
      self.SetTemplateValue('accepted_mime_ranges', accepted_mime_ranges)
      max_size = media_upload.get('maxSize')
      self.SetTemplateValue('max_size', max_size)
      self.SetTemplateValue('max_size_bytes',
                            convert_size.ConvertSize(max_size))
      # Find which upload protocols are supported.
      upload_protocols = media_upload['protocols']
      for upload_protocol in upload_protocols:
        self._SetUploadTemplateValues(
            upload_protocol, upload_protocols[upload_protocol])

  def _InitPageable(self, api):
    response_type = self.values.get('responseType')
    if (response_type != api.void_type
        and self.FindCodeObjectWithWireName(
            response_type.values.get('properties'), 'nextPageToken')
        and self.FindCodeObjectWithWireName(
            self.optional_parameters, 'pageToken')):
      self.SetTemplateValue('isPageable', True)

  def _SetUploadTemplateValues(self, upload_protocol, protocol_dict):
    """Sets upload specific template values.

    Args:
      upload_protocol: (str) The name of the upload protocol. Eg: 'simple' or
        'resumable'.
      protocol_dict: (dict) The dictionary that corresponds to this upload
        protocol. It typically contains keys like 'path', 'multipart' etc.
    """
    self.SetTemplateValue('%s_upload_supported' % upload_protocol, True)
    upload_path = protocol_dict.get('path')
    if upload_path:
      self.SetTemplateValue('%s_upload_path' % upload_protocol, upload_path)
      self.SetTemplateValue('%s_upload_multipart' % upload_protocol,
                            protocol_dict.get('multipart', False))

  @property
  def media_upload_parameters(self):
    return self.values.get('mediaUpload')

  @property
  def parameters(self):
    return self.values['parameters']

  @property
  def optional_parameters(self):
    return [p for p in self.values['parameters'] if not p.required]

  @property
  def required_parameters(self):
    return [p for p in self.values['parameters'] if p.required]

  @property
  def path_parameters(self):
    return [p for p in self.values['parameters'] if p.location == 'path']

  @property
  def query_parameters(self):
    return [p for p in self.values['parameters'] if p.location == 'query']

  @staticmethod
  def FindCodeObjectWithWireName(things, wire_name):
    """Looks for an element having the given wire_name.

    Args:
      things: (array of DataType) List of parameters or properties to search.
      wire_name: (str) The wireName we are looking to find.

    Returns:
      None or element with the given wire_name.
    """
    if not things: return None
    for e in things:
      if e.values['wireName'] == wire_name: return e
    return None

  #
  # Expose some properties with the naming convention we use in templates
  #
  def optionalParameters(self):  # pylint: disable=g-bad-name
    return self.optional_parameters

  def requiredParameters(self):  # pylint: disable=g-bad-name
    return self.required_parameters

  def pathParameters(self):  # pylint: disable=g-bad-name
    return self.path_parameters

  def queryParameters(self):  # pylint: disable=g-bad-name
    return self.query_parameters

class Parameter(template_objects.CodeObject):
  """The definition of a method parameter."""

  def __init__(self, api, name, def_dict, method):
    super(Parameter, self).__init__(def_dict, api, parent=method,
                                    wire_name=name)
    self.ValidateName(name)
    self.schema = api

    # TODO(user): Deal with dots in names better. What we should do is:
    # For x.y, x.z create a little class X, with members y and z. Then
    # have the constructor method take an X.

    self._repeated = self.values.get('repeated', False)
    self._required = self.values.get('required', False)
    self._location = (self.values.get('location')
                      or self.values.get('restParameterType')
                      or 'query')
    # TODO(user): Why not just use Schema.Create here?
    referenced_schema = self.values.get('$ref')
    if referenced_schema:
      self._data_type = (api.SchemaByName(referenced_schema) or
                         data_types.SchemaReference(referenced_schema, api))
    elif def_dict.get('type') == 'array':
      self._data_type = Schema.Create(api, name, def_dict, name, method)
    elif self.values.get('enum'):
      self._data_type = data_types.Enum(def_dict,
                                        api,
                                        name,
                                        self.values.get('enum'),
                                        self.values.get('enumDescriptions'),
                                        parent=method)
      self.SetTemplateValue('enumType', self._data_type)
    else:
      self._data_type = data_types.PrimitiveDataType(def_dict, api, parent=self)
    if self._repeated:
      self._data_type = data_types.ArrayDataType(name, self._data_type,
                                                 parent=self)

  @property
  def repeated(self):
    return self._repeated

  @property
  def required(self):
    return self._required

  @property
  def location(self):
    return self._location

  @property
  def code_type(self):
    return self._data_type.code_type

  @property
  def data_type(self):
    return self._data_type


text:
var clubs = require('../clubs.json');
var models = require('../models');

exports.view = function(req, res){
	authenticate(req, res);
}

function authenticate(req, res){
    models.User
        .find({
            "_id": req.query["auth"],
        })
        .exec(exists);

    function exists(err, users) {
        if (err) {
            console.log(err);
            res.redirect('/');
        }else{
        	if(users.length !== 0){
        		createView(req, res, users[0]);
				return;
        	}
        	res.redirect('/');
        }
    };
}

//change as needed
function createView(req, res, userData){
	var userData = userData || {};
	// res.render('favorites', clubs);
	var favorites = {'favorites': userData['favorites']};
	res.render('favorites', favorites);
}

exports.addFavorite = function(req, res) {
	var jsondata = req.body;

	var userid = jsondata['userid'];

	var favoriteClub = {
		"id": jsondata['currentClub[id]'],
		"clubID": jsondata['currentClub[clubID]'],
		"name": jsondata['currentClub[name]'],
	};

	models.User.findOne({"_id": userid}).exec(saveToFavorites);

	function saveToFavorites(err, user) {
		if (err) return handleError(err);

		var alreadyInFavorites = false;

		for(var i=0; i < user.favorites.length; i++) {
		  if ( user.favorites[i]['id'] == favoriteClub['id'] ) {
		  	alreadyInFavorites = true;
		  	break;
		  }
		}

		if(!alreadyInFavorites) {
			user.favorites.push(favoriteClub);
		}

		user.save(function(err){
			if (err) return handleError(err);
		});
		//console.log('user:');
		//console.log(user);
		res.send();
	}

};

redpajama_set_name: RedPajamaGithub


text:
require 'test_helper'
require_relative '../patient_test'

class PatientTest::Exportable < PatientTest
  describe 'export concern methods' do
    before { @patient = create :patient }

    describe "exportable pledges sum" do
      it "returns 0 if no pledges" do
        assert_equal @patient.external_pledge_sum, 0
      end

      it "returns sum of pledges when they exist" do
        @patient.external_pledges.create attributes_for(:external_pledge, amount: 100)
        @patient.external_pledges.create attributes_for(:external_pledge, amount: 200)
        assert_equal @patient.external_pledge_sum, 300
      end
    end

    describe 'age range tests' do
      it 'should return the right age for numbers' do
        @patient.age = nil
        assert_equal @patient.age_range, :not_specified

        [15, 17].each do |age|
          @patient.update age: age
          assert_equal @patient.age_range, :under_18
        end

        [18, 20, 24].each do |age|
          @patient.update age: age
          assert_equal @patient.age_range, :age18_24
        end

        [25, 30, 34].each do |age|
          @patient.update age: age
          assert_equal @patient.age_range, :age25_34
        end

        [35, 40, 44].each do |age|
          @patient.update age: age
          assert_equal @patient.age_range, :age35_44
        end

        [45, 50, 54].each do |age|
          @patient.update age: age
          assert_equal @patient.age_range, :age45_54
        end

        [55, 60, 100].each do |age|
          @patient.update age: age
          assert_equal @patient.age_range, :age55plus
        end

        [101, 'yolo'].each do |bad_age|
          @patient.age = bad_age
          assert_equal @patient.age_range, :bad_value
        end
      end
    end

    describe 'preferred language tests' do
      it 'should return the right language' do
        ['', nil].each do |language|
          @patient.update language: language
          assert_equal @patient.preferred_language, 'English'
        end

        @patient.update language: 'Spanish'
        assert_equal @patient.preferred_language, 'Spanish'
      end
    end

    describe 'household size tests' do
      it 'should return prefer not to answer with -1' do
        @patient.update household_size_children: -1, household_size_adults: -1
        assert_equal 'Prefer not to answer', @patient.get_household_size_children
        assert_equal 'Prefer not to answer', @patient.get_household_size_adults
      end

      it 'should return number otherwise' do
        @patient.update household_size_children: 4, household_size_adults: 3
        assert_equal 4, @patient.get_household_size_children
        assert_equal 3, @patient.get_household_size_adults
      end

      it 'should null out for archived patients' do
        archived = create :archived_patient
        assert_nil archived.get_household_size_children
        assert_nil archived.get_household_size_adults
      end
    end
  end
end


text:
<?php

namespace Kunstmaan\LeadGenerationBundle\Form\Popup;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\FormBuilderInterface;

abstract class AbstractPopupAdminType extends AbstractType
{
    /**
     * Builds the form.
     *
     * This method is called for each type in the hierarchy starting form the
     * top most type. Type extensions can further modify the form.
     *
     * @see FormTypeExtensionInterface::buildForm()
     *
     * @param FormBuilderInterface $builder The form builder
     * @param array                $options The options
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add('name', TextType::class, [
            'label' => 'kuma_lead_generation.form.popup.name.label',
            'attr' => [
                'info_text' => 'kuma_lead_generation.form.popup.name.info_text',
            ],
        ]);
        $builder->add('htmlId', TextType::class);
    }
}


text:
namespace Sophie.Core.Objects
{
    public sealed class ObjUpvalue : Obj
    {
        // Pointer to the variable this upvalue is referencing.

        // If the upvalue is closed (i.e. the local variable it was pointing too has
        // been popped off the stack) then the closed-over value will be hoisted out
        // of the stack into here. [value] will then be changed to point to this.

        // Open upvalues are stored in a linked list by the fiber. This points to the
        // next upvalue in that list.

        // Creates a new open upvalue pointing to [value] on the stack.
        public ObjUpvalue(Obj c, int index)
        {
            Container = c;
            Next = null;
            Index = index;
        }

        public Obj Container;
        public ObjUpvalue Next;
        public readonly int Index;
    }
}


text:
var denon = require('../../lib/app')
  , config = require('./config');

var avr = new denon(new denon.transports.telnet(config));

avr.connect();
avr.on('connect', function() {
  console.log('Connected');
  avr.getSource(function(err, source) {
    if (err) {
      console.log(err.toString());
      return;
    }

    console.log('The current source is', source);
  });
});

// close the connection and node process after 2 seconds
setTimeout(function() {
  avr.getConnection().destroy();
  process.exit(0);
}, 2000);

process.on('SIGINT', function() {
  console.log("Caught interrupt signal");

  avr.getConnection().destroy();
  process.exit(0);
});


text:
namespace s2 {

template <typename Encoding>
struct convert<Encoding, char32_t> {
  static size_t length(char32_t val) {
    null_iterator<typename Encoding::storage_type> it;
    Encoding::encode(it, val);
    return it.count;
  }
  template <typename It>
  static void encode(It &it, char32_t val) {
    Encoding::encode(it, val);
  }
};
template <typename Encoding>
struct convert<Encoding, char16_t> {
  static size_t length(char16_t val) {
    null_iterator<typename Encoding::storage_type> it;
    Encoding::encode(it, val);
    return it.count;
  }
  template <typename It>
  static void encode(It &it, char16_t val) {
    Encoding::encode(it, val);
  }
};
template <typename Encoding>
struct convert<Encoding, char> {
  static size_t length(char val) {
    null_iterator<typename Encoding::storage_type> it;
    Encoding::encode(it, val);
    return it.count;
  }
  template <typename It>
  static void encode(It &it, char val) {
    Encoding::encode(it, val);
  }
};
template <typename Encoding, typename Encoding2>
struct convert<Encoding, s2::basic_string_view<Encoding2>> {
  static size_t length(const s2::basic_string_view<Encoding2>& val) {
    null_iterator<typename Encoding::storage_type> it;
    for (auto&& c : val) {
      Encoding::encode(it, c);
    }
    return it.count;
  }
  template <typename It>
  static void encode(It &it, const s2::basic_string_view<Encoding2>& val) {
    for (auto&& c : val) {
      Encoding::encode(it, c);
    }
  }
};
template <typename Encoding>
struct convert<Encoding, uint64_t> {
  static constexpr char charlist[37] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
  static size_t length(uint64_t val) {
    size_t count = 0;
    if (val >= 10) {
      count = length(val / 10);
    }
    null_iterator<typename Encoding::storage_type> it;
    static_assert(10 < sizeof(charlist));
    Encoding::encode(it, charlist[val % 10]);
    count += it.count;
    return count;
  }
  template <typename It>
  static void encode(It &it, uint64_t val) {
    if (val >= 10) {
      encode(it, val / 10);
    }
    Encoding::encode(it, '0' + (val % 10));
  }
};
template <typename Encoding>
struct convert<Encoding, int64_t> {
  static size_t length(int64_t val) {
    size_t count = 0;
    uint64_t abs_x = (uint64_t)val;
    if (val < 0) {
      null_iterator<typename Encoding::storage_type> it;
      Encoding::encode(it, '-');
      count += it.count;
      abs_x = 0ull - abs_x;
    }
    count += convert<Encoding, uint64_t>::length(abs_x);
    return count;
  }
  template <typename It>
  static void encode(It &it, int64_t val) {
    uint64_t abs_x = (uint64_t)val;
    if (val < 0) {
      Encoding::encode(it, '-');
      abs_x = 0ull - abs_x;
    }
    convert<Encoding, uint64_t>::encode(it, abs_x);
  }
};

template <typename Encoding> struct convert<Encoding, unsigned int> : convert<Encoding, uint64_t> {};
template <typename Encoding> struct convert<Encoding, unsigned short> : convert<Encoding, uint64_t> {};
template <typename Encoding> struct convert<Encoding, unsigned char> : convert<Encoding, uint64_t> {};
template <typename Encoding> struct convert<Encoding, signed int> : convert<Encoding, int64_t> {};
template <typename Encoding> struct convert<Encoding, signed short> : convert<Encoding, int64_t> {};
template <typename Encoding> struct convert<Encoding, signed char> : convert<Encoding, int64_t> {};

}


text:
package cct.interfaces;

/**
 *
Title: Computational Chemistry Tookit

 *
 *
Description:

 *
 *
Copyright: Copyright (c) 2005-2010 Dr. Vladislav Vassiliev

 *
 *
Company: ANU

 *
 * @author Dr. Vladislav Vassiliev
 * @version 1.0
 */
public interface VolumetricDataInterface {

   /**
    * Parses file with volumetric data
    * @param filename String -  file name
    * @throws Exception - if any error occurs
    */
   void parseVolumetricData(String filename) throws Exception;

   /**
    * Returns description of the whole volumetric data
    * @return String
    */
   String getCubeDescription();

   /**
    * Returns description of nth cube
    * @param n int -  cube number
    * @return String
    */
   String getCubeLabel(int n);

   /**
    * Returns minimum function value
    * @return double
    */
   double getMinFunValue();

   /**
    * Returns maximum function value
    * @return double
    */
   double getMaxFunValue();

   /**
    * Returns number of volumetric cubes
    * @return int
    */
   int countCubes();

   /**
    * Returns 3d array of volumetric data
    * @return float[][][]
    */
   float[][][] getVolumetricData();

   /**
    * Returns 3d array of volumetric data for n-th cube
    * @param n int - cube number
    * @return float[][][]
    */
   float[][][] getVolumetricData(int n);

   /**
    * Data origin of a cube, i.e. minimal x, y and z
    * @return double[]
    */
   double[] getDataOrigin();

   /**
    * Number of voxels along every axis (x,y,z)
    * @return int[]
    */
   int[] getNumberOfVoxels();

   // Lengths (in A) of a cube along all axes -
   float[][] getAxisVectors();

   /**
    * Returns molecular goemetry (if any). null is no molecular geometry in the cube file
    * @param molecule MoleculeInterface
    */
   void getMolecule(MoleculeInterface molecule);
}


text:
	<title>Garden for the Environment - Photos</title>

Welcome to Garden for the Environment!

	Home | Photos | Contact

	Home | Photos | Contact


text:
import { getCsrfToken } from '../../../utils/server';

// expand all outputs in Auto-Grading Testcases section
function openAllAutoGrading() {
    // show all divs whose id starts with testcase_
    const clickable_divs = $("[id^='tc_']");

    for (let i = 0; i < clickable_divs.length; i++) {
        const clickable_div = clickable_divs[i];
        const num = clickable_div.id.split('_')[1];
        const content_div = $(`#testcase_${num}`);
        if (content_div.css('display') === 'none') {
            clickable_div.click();
        }
    }
}

function regrade(single_regrade: number, highest_version: number, gradeable_id: string, user_id: string) {
    //if only regrading active version, late day fields left as 0 because they are irrelevant for regrading
    if (single_regrade) {
        window.handleRegrade(highest_version, getCsrfToken(), gradeable_id, user_id, true);
    }
    //regrading all versions
    else {
        window.handleRegrade(highest_version, getCsrfToken(), gradeable_id, user_id, false, true);
    }
}

// close all outputs in Auto-Grading Testcases section
function closeAllAutoGrading() {
    // hide all divs whose id starts with testcase_
    $("[id^='testcase_']").hide();
    $("[id^='details_tc_']").find('span').hide();
    $("[id^='details_tc_']").find('.loading-tools-show').show();
}

$(() => {
    const autogradingResultsJQuery: JQuery = $('#autograding_results');
    const HIGHEST_VERSION = parseInt(autogradingResultsJQuery.attr('data-highest-version')!);
    const GRADEABLE_ID = autogradingResultsJQuery.attr('data-gradeable-id')!;
    const USER_ID = autogradingResultsJQuery.attr('data-user-id')!;

    $('#autograding-results-open-all').on('click', () => {
        openAllAutoGrading();
    });
    $('#autograding-results-close-all').on('click', () => {
        closeAllAutoGrading();
    });
    $('#autograding-results-regrade-active').on('click', () => {
        regrade(1, HIGHEST_VERSION, GRADEABLE_ID, USER_ID);
    });
    $('#autograding-results-regrade-all').on('click', () => {
        regrade(0, HIGHEST_VERSION, GRADEABLE_ID, USER_ID);
    });
});


text: module.exports = require('./lib/pavement');


text:
<?php

declare(strict_types=1);

namespace phpseclib3\Net\SSH2;

/**
 * @internal
 */
abstract class ChannelConnectionFailureReason
{
    public const ADMINISTRATIVELY_PROHIBITED = 1;
    public const CONNECT_FAILED = 2;
    public const UNKNOWN_CHANNEL_TYPE = 3;
    public const RESOURCE_SHORTAGE = 4;
}


text:
<!--
 -
 - Licensed to the Apache Software Foundation (ASF) under one
 - or more contributor license agreements.  See the NOTICE file
 - distributed with this work for additional information
 - regarding copyright ownership.  The ASF licenses this file
 - to you under the Apache License, Version 2.0 (the
 - "License"); you may not use this file except in compliance
 - with the License.  You may obtain a copy of the License at
 -
 -   http://www.apache.org/licenses/LICENSE-2.0
 -
 - Unless required by applicable law or agreed to in writing,
 - software distributed under the License is distributed on an
 - "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 - KIND, either express or implied.  See the License for the
 - specific language governing permissions and limitations
 - under the License.
 -
 -->
<project name="module" xmlns:artifact="antlib:org.apache.maven.artifact.ant">

  <import file="common.xml"/>

  <path id="maven-ant-tasks.classpath" path="${project.root}/lib/maven-ant-tasks-2.1.1.jar" />
  <typedef resource="org/apache/maven/artifact/ant/antlib.xml"
           uri="antlib:org.apache.maven.artifact.ant"
           classpathref="maven-ant-tasks.classpath" />

  <map property="module" value="${basedir}" split="${path.separator}">
    <globmapper from="${project.root}${file.separator}*" to="*"/>
  </map>

  <map property="module.name" value="${module}">
    <filtermapper>
        <replacestring from="${file.separator}" to="-"/>
    </filtermapper>
  </map>

  <echo message="Running ant for module : ${module}" level="info"/>

  <property file="${project.root}/build.deps"/>

  <property name="module.build"        location="${build.scratch}/${module}"/>
  <property name="module.classes"      location="${module.build}/classes"/>
  <property name="module.instrumented" location="${module.build}/classes-instrumented"/>
  <property name="module.precompiled"  location="${module.build}/src"/>
  <property name="module.api"          location="${build.api}/${module}/"/>
  <property name="module.test.api"     location="${build.test.api}/${module}"/>
  <property name="module.test.classes" location="${module.build}/test/classes"/>
  <property name="module.results"      location="${build.results}/${module}"/>
  <property name="module.failed"       location="${module.results}/FAILED"/>
  <property name="module.src"          location="src/main/java"/>
  <property name="module.test.src"     location="src/test/java"/>
  <property name="module.bin"          location="bin"/>
  <property name="module.etc"          location="etc"/>

  <property name="module.namever"      value="${project.name}-${module.name}-${andes.version}"/>
  <property name="module.namever.osgi" value="${project.name}-${module.name}_${andes.version}.0.osgi"/>
  <property name="module.release.base" value="${basedir}/release"/>
  <property name="module.release"      value="${module.release.base}/${module.namever}"/>
  <property name="module.release.lib"  value="${module.release}/lib"/>
  <property name="module.release.zip"  location="${module.release.base}/${module.namever}.zip"/>
  <property name="module.release.tar"  location="${module.release.base}/${module.namever}.tar"/>
  <property name="module.release.tgz"  location="${module.release.base}/${module.namever}.tar.gz"/>
  <property name="module.release.bz2"  location="${module.release}/${module.namever}.tar.bz2"/>

  <property name="module.genpom.args"  value=""/>
  <property name="maven.remote.repo"     value="file://${module.release.base}/maven"/>

  <property name="broker.log.prefix" value="BROKER: "/>
  <property name="broker.log.interleave" value="true"/>

  <property name="module.qpid.jar"     location="${module.release.lib}/qpid-all.jar"/>
  <basename property="qpid.jar.name"  file="${module.qpid.jar}"/>

  <property name="module.coverage"     location="${module.build}/coverage"/>
  <property name="cobertura.datafile"  location="${module.instrumented}/cobetura.ser"/>

  <available property="module.test.src.exists" file="${module.test.src}"/>
  <available property="module.etc.exists" file="${module.etc}"/>
  <available property="module.bin.exists" file="${module.bin}"/>

  <property name="module.source.jar"
            location="${build.lib}/${project.name}-${module.name}-${andes.version}-sources.jar"/>

  <!-- module.depends and module.test.depends are supplied by the importing file -->
  <property name="module.depends"       value=""/>
  <property name="module.test.depends"  value=""/>
  <property name="module.test.excludes" value=""/>

  <map property="module.depends.path" value="${module.depends}" join="${path.separator}">
    <globmapper from="*" to="${build.scratch}/*/classes"/>
  </map>

  <map property="module.test.depends.path" value="${module.test.depends}" join="${path.separator}">
    <globmapper from="*" to="${build.scratch}/*/classes"/>
  </map>

   <!-- Add depenencies dependencies to path -->
   <map property="module.depends.libs" value="${module.depends}" join=" ">
       <chainedmapper>
           <filtermapper>
               <replacestring from="${file.separator}" to="-"/>
           </filtermapper>
           <propertymapper from="*" to="*.libs"/>
       </chainedmapper>
   </map>
    <condition property="module.depends.libs.includes" value="__EMPTY__" else="${module.depends.libs}">
      <equals trim="true" arg1="${module.depends.libs}" arg2=""/>
    </condition>

    <!-- Add depenencies test dependencies to path -->
    <map property="module.test.depends.libs" value="${module.test.depends}" join=" ">
        <chainedmapper>
            <filtermapper>
                <replacestring from="${file.separator}" to="-"/>
            </filtermapper>
            <propertymapper from="*" to="*.libs"/>
        </chainedmapper>
    </map>
    <condition property="module.test.depends.libs.includes" value="__EMPTY__" else="${module.test.depends.libs}">
      <equals trim="true" arg1="${module.test.depends.libs}" arg2=""/>
    </condition>

  <indirect name="module.libs"         variable="${module.name}.libs"/>
  <condition property="module.libs.includes" value="__EMPTY__" else="${module.libs}">
    <equals trim="true" arg1="${module.libs}" arg2=""/>
  </condition>

  <indirect name="module.test.libs"    variable="${module.name}.test.libs"/>
  <condition property="module.test.libs.includes" value="__EMPTY__" else="${module.test.libs}">
    <equals trim="true" arg1="${module.test.libs}" arg2=""/>
  </condition>

  <path id="module.libs">
    <fileset dir="${project.root}" includes="lib/*"/>
    <fileset dir="${project.root}" includes="${module.depends.libs.includes}"/>
  </path>

  <path id="module.test.libs">
    <fileset dir="${project.root}" includes="lib/*"/>
    <fileset dir="${project.root}" includes="${module.test.depends.libs.includes}"/>
  </path>

  <path id="module.src.path">
    <pathelement location="${module.src}"/>
    <pathelement location="${module.precompiled}"/>
  </path>

  <path id="module.test.src.path">
    <pathelement location="${module.test.src}"/>
  </path>

  <condition property="module.jar"
             value="${build.plugins}/${project.name}-${module.name}-${andes.version}.jar"
             else="${build.lib}/${project.name}-${module.name}-${andes.version}.jar">
    <and>
      <isset property="module.plugin"/>
      <istrue value="${module.plugin}"/>
    </and>
  </condition>

  <property name="module.test.jar"
            location="${build.lib}/${project.name}-${module.name}-tests-${andes.version}.jar"/>

  <path id="module.class.path">
    <pathelement location="${module.classes}"/>
    <pathelement path="${module.depends.path}"/>
    <path refid="module.libs"/>
  </path>

  <path id="module.test.path">
    <pathelement path="${module.test.classes}"/>
    <path refid="module.class.path"/>
    <pathelement path="${module.test.depends.path}"/>
    <path refid="module.test.libs"/>
  </path>

  <property name="javac.deprecation" value="off"/>

  <target name="debug">
    <echo-prop name="basedir"/>
    <echo-prop name="project.root"/>
    <echo-prop name="module"/>
    <echo-prop name="module.libs"/>
    <echo-prop name="module.test.libs"/>
    <echo-prop name="module.name"/>
    <echo-prop name="module.jar"/>
    <echo-prop name="module.depends"/>
    <echo-prop name="module.depends.path"/>
    <echo-prop name="module.test.depends"/>
    <echo-prop name="module.test.depends.path"/>
    <echo-prop name="module.depends.libs"/>
    <echo-prop name="module.test.depends.libs"/>
    <echo-path refid="module.src.path"/>
    <echo-path refid="module.class.path"/>
    <echo-path refid="module.test.path"/>
  </target>

  <target name="prepare">
    <mkdir dir="${build.bin}"/>
    <mkdir dir="${build.etc}"/>
    <mkdir dir="${build.lib}"/>
    <mkdir dir="${build.results}"/>
    <mkdir dir="${build.data}"/>
    <mkdir dir="${build.plugins}"/>
    <mkdir dir="${module.classes}"/>
    <mkdir dir="${module.precompiled}"/>
    <mkdir dir="${module.api}"/>
    <mkdir dir="${module.test.api}"/>
    <mkdir dir="${module.test.classes}"/>
    <mkdir dir="${module.results}"/>
  </target>

  <target name="pom" depends="prepare" if="module.genpom">
    <jython path="${mllib.dir}">
      <args>
        <arg line='"${project.root}/genpom"'/>
        <arg line='-s "${project.root}/lib/poms"'/>
        <arg line='-o "${build.scratch}/qpid-${module.name}.pom"'/>
        <arg line="-u ${project.url}"/>
        <arg line="-g ${project.groupid}"/>
        <arg line="-v ${andes.version}${maven.version.suffix}"/>
        <arg line="-p qpid"/>
        <arg line='-m "${module.depends}"'/>
        <arg line="-a ${module.name}"/>
        <arg line="${module.genpom.args}"/>
        <arg line="${module.libs}"/>
      </args>
    </jython>
  </target>

  <target name="release-mvn" depends="pom" if="module.genpom" description="Install the artifacts into the local repository and prepare the release">
    <antcall target="build"/>

    <artifact:pom id="module.pom" file="${build.scratch}/qpid-${module.name}.pom"/>

    <artifact:install file="${module.jar}" pomRefId="module.pom" settingsFile="${maven.settings.xml}">
        <localRepository path="${maven.local.repo}"/>
    </artifact:install>

    <artifact:deploy file="${module.jar}" pomRefId="module.pom" uniqueVersion="${maven.unique.version}" settingsFile="${maven.settings.xml}">
      <attach file="${module.source.jar}" classifier="sources"/>
      <localRepository path="${maven.local.repo}"/>
      <remoteRepository url="${maven.remote.repo}"/>
    </artifact:deploy>
  </target>

  <target name="precompile"/>

  <target name="compile" depends="prepare,precompile" description="compile sources">

    <echo message="Targeting : ${java.target}" level="info"/>

    <javac source="${java.source}" target="${java.target}"
           destdir="${module.classes}" debug="on" debuglevel="lines,vars,source" includeantruntime="false"
           deprecation="${javac.deprecation}">
      <compilerarg line="${javac.compiler.args}"/>
      <src refid="module.src.path"/>
      <classpath refid="module.class.path"/>
    </javac>

    <!-- copy any non java src files into the build tree, e.g. log4j.properties -->
    <copy todir="${module.classes}" verbose="true">
      <fileset dir="${module.src}">
        <exclude name="**/*.java"/>
        <exclude name="**/package.html"/>
      </fileset>
    </copy>
  </target>

  <target name="precompile-tests" if="module.test.src.exists"/>

  <target name="compile-tests" depends="compile,precompile-tests" if="module.test.src.exists"
          description="compilte unit tests">
    <javac target="${java.target}" source="${java.source}"
           destdir="${module.test.classes}" debug="on"
           deprecation="${javac.deprecation}"
           srcdir="${module.test.src}" includeantruntime="false">
      <classpath refid="module.test.path"/>
    </javac>

    <!-- copy any non java src files into the build tree, e.g. log4j.properties -->
    <copy todir="${module.test.classes}" verbose="true">
      <fileset dir="${module.test.src}">
        <exclude name="**/*.java"/>
        <exclude name="**/package.html"/>
      </fileset>
    </copy>
  </target>

  <property name="profile" value="defaults"/>
  <property name="testprofile.file" value="${test.profiles}/testprofile.${profile}"/>

  <available file="${testprofile.file}" property="testprofile.file.present"/>
  <fail unless="testprofile.file.present" message="The requested test profile was not found: ${testprofile.file}"/>

  <property file="${testprofile.file}" prefix="preload"/>
  <property name="preload.include" value=""/>
  <condition property="profiles"
             value="${preload.include} ${profile}"
             else="default ${preload.include} ${profile}">
    <equals arg1="${profile}" arg2="default"/>
  </condition>
  <map property="_profile_files" value="${profiles}" join=" ">
    <globmapper from="*" to="*.testprofile"/>
  </map>
  <concat destfile="${build.scratch}/test-${profile}.properties" force="no" fixlastline="yes">
    <filelist dir="${test.profiles}" files="${_profile_files}"/>
  </concat>
  <property file="${build.scratch}/test-${profile}.properties"/>

  <map property="test.excludefiles" value="${test.excludes}">
    <globmapper from="*" to="${test.profiles}/*"/>
  </map>

  <condition property="dontruntest" value="dontruntest" else="runtest">
         <contains substring="${module.name}" string="${exclude.modules}" />
  </condition>

  <property name="jvm.args" value=""/>
  <property name="broker.existing.qpid.work" value=""/>

  <target name="test" depends="build,compile-tests" if="module.test.src.exists"
         unless="${dontruntest}" description="execute unit tests">

    <delete file="${module.failed}"/>

    <echo message="Using profile:${profile}" level="info"/>
    <junit fork="yes" forkmode="once" maxmemory="${test.mem}" reloading="no"
           haltonfailure="${haltonfailure}" haltonerror="${haltonerror}"
           failureproperty="test.failures" printsummary="on" timeout="6000000" >

      <jvmarg line="${jvm.args}" />

      <sysproperty key="amqj.logging.level" value="${amqj.logging.level}"/>
      <sysproperty key="amqj.server.logging.level" value="${amqj.server.logging.level}"/>
      <sysproperty key="amqj.protocol.logging.level" value="${amqj.protocol.logging.level}"/>
      <sysproperty key="log4j.debug" value="${log4j.debug}"/>
      <sysproperty key="root.logging.level" value="${root.logging.level}"/>
      <sysproperty key="log4j.configuration" value="${log4j.configuration}"/>
      <sysproperty key="java.naming.factory.initial" value="${java.naming.factory.initial}"/>
      <sysproperty key="java.naming.provider.url" value="${java.naming.provider.url}"/>
      <sysproperty key="broker" value="${broker}"/>
      <sysproperty key="broker.clean" value="${broker.clean}"/>
      <sysproperty key="broker.clean.between.tests" value="${broker.clean.between.tests}"/>
      <sysproperty key="broker.existing.qpid.work" value="${broker.existing.qpid.work}"/>
      <sysproperty key="broker.persistent" value="${broker.persistent}"/>
      <sysproperty key="broker.version" value="${broker.version}"/>
      <sysproperty key="broker.ready" value="${broker.ready}" />
      <sysproperty key="broker.stopped" value="${broker.stopped}" />
      <sysproperty key="broker.config" value="${broker.config}" />
      <sysproperty key="messagestore.class.name" value="${messagestore.class.name}" />
      <sysproperty key="test.output" value="${module.results}"/>
      <sysproperty key="qpid.amqp.version" value="${qpid.amqp.version}"/>

      <syspropertyset>
        <propertyref prefix="test"/>
      </syspropertyset>
      <syspropertyset>
        <propertyref prefix="profile"/>
      </syspropertyset>
      <syspropertyset>
        <propertyref prefix="javax.net.ssl"/>
      </syspropertyset>
      <syspropertyset>
         <propertyref prefix="broker"/>
      </syspropertyset>

      <sysproperty key="max_prefetch" value ="${max_prefetch}"/>
      <sysproperty key="qpid.dest_syntax" value ="${qpid.dest_syntax}"/>

      <sysproperty key="example.plugin.target" value="${project.root}/build/lib/plugins"/>
      <sysproperty key="QPID_EXAMPLE_HOME" value="${qpid.home}"/>
      <sysproperty key="QPID_HOME" value="${qpid.home}"/>
      <sysproperty key="QPID_WORK" value="${qpid.work}"/>

      <formatter type="plain"/>
      <formatter type="xml"/>

      <classpath refid="module.test.path"/>

      <batchtest todir="${module.results}">
        <fileset dir="${module.test.src}" excludes="${module.test.excludes}">
          <include name="**/${test}.java"/>
        </fileset>
      </batchtest>
    </junit>

    <antcall target="touch-failed"/>

    <condition property="failed">
      <and>
        <isfalse value="${test.failures.ignore}"/>
        <available file="${module.failed}"/>
      </and>
    </condition>

    <fail if="failed" message="TEST SUITE FAILED"/>

  </target>

  <target name="report-module" description="generate junit reports for each module">
    <junitreport todir="${module.results}">
        <fileset dir="${module.results}">
            <include name="TEST-*.xml"/>
        </fileset>
        <report format="frames" todir="${module.results}/report/html"/>
    </junitreport>
  </target>

  <target name="touch-failed" if="test.failures">
    <touch file="${module.failed}"/>
    <touch file="${build.failed}"/>
  </target>

  <target name="copy-bin" if="module.bin.exists" description="copy bin directory if it exists to build tree">
    <copy todir="${build.bin}" failonerror="false">
      <fileset dir="${module.bin}"/>
    </copy>
    <chmod dir="${build.bin}" perm="ugo+rx" includes="**/*"/>
  </target>

  <target name="copy-bin-release" if="module.bin.exists" description="copy dependencies into module release">
    <copy todir="${module.release}/bin" failonerror="true">
      <fileset dir="${module.bin}" />
    </copy>
    <chmod dir="${module.release}/bin" perm="ugo+rx" includes="**/*"/>
  </target>

  <target name="copy-etc" if="module.etc.exists" description="copy etc directory if it exists to build tree">
    <copy todir="${build.etc}" failonerror="false">
      <fileset dir="${module.etc}"/>
    </copy>
  </target>

  <target name="copy-etc-release" if="module.etc.exists" description="copy etc directory if it exists to build tree">
    <copy todir="${module.release}/etc" failonerror="false" flatten="true">
        <fileset dir="${module.etc}"/>
    </copy>
  </target>

  <target name="postbuild" description="run after a build"/>

  <target name="build" depends="jar,jar-tests,jar-sources,libs,copy-bin,copy-etc,postbuild" description="compile and copy resources into build tree"/>
  <target name="jar.manifest" depends="compile" if="module.manifest">
    <jar destfile="${module.jar}" basedir="${module.classes}" manifest="${module.manifest}"/>
  </target>

  <target name="jar.nomanifest" depends="compile" unless="module.manifest">
    <jar destfile="${module.jar}" basedir="${module.classes}">
       <metainf dir="${project.root}/resources/" />
    </jar>
  </target>

  <target name="jar" depends="jar.manifest,jar.nomanifest" description="create jar"/>

  <target name="jar-tests" depends="compile-tests" description="create unit test jar">
    <jar destfile="${module.test.jar}" basedir="${module.test.classes}"/>
  </target>

  <target name="jar-sources" depends="prepare" description="create sources jar">
    <jar destfile="${module.source.jar}">
      <fileset dir="${project.root}/resources">
        <include name="LICENSE"/>
        <include name="NOTICE"/>
      </fileset>
      <fileset dir="${module.src}" includes="**/*.java"/>
      <fileset dir="${module.precompiled}" includes="**/*.java"/>
    </jar>
  </target>

  <target name="libs" description="copy dependencies into build tree">
    <copylist todir="${build.lib}" dir="${project.root}" files="${module.libs}"/>
  </target>

  <map property="module.depends.jars" value="${module.depends}" join=",">
    <globmapper from="*" to="${project.name}-*-${andes.version}.jar"/>
    <filtermapper>
        <replacestring from="/" to="-"/>
    </filtermapper>
  </map>

  <target name="libs-release" description="copy dependencies into module release">
    <!-- Copy the module dependencies -->
      <echo message="${module.libs}"/>
    <copylist todir="${module.release}/lib" dir="${project.root}" files="${module.libs}"/>
    <copylist todir="${module.release}/lib" dir="${project.root}" files="${module.depends.libs}"/>

    <!-- Copy the jar for this module -->
    <copy todir="${module.release}/lib" failonerror="true">
        <fileset file="${module.jar}"/>
        <fileset dir="${build.lib}" includes="${module.depends.jars}"/>
    </copy>
  </target>

  <target name="resources" description="copy resources into build tree">
    <copy todir="${build}" failonerror="false" flatten="true">
      <fileset dir="${basedir}${file.separator}.." includes="${resources}"/>
    </copy>
  </target>

  <target name="resources-release" description="copy resources into module release">
    <copy todir="${module.release}" failonerror="false" flatten="true">
      <fileset dir="${resources}" excludes="META-INF"/>
    </copy>
  </target>

  <uptodate property="doc.done" targetfile="${module.api}/index.html">
    <srcfiles dir="${module.src}" includes="**/*.java"/>
  </uptodate>

  <property name="module.doc.access" value="package"/>
  <target name="doc" depends="prepare" unless="doc.done" description="generate api-doc">
    <javadoc access="${module.doc.access}" destdir="${module.api}" author="false" version="true" use="true"
        windowtitle="${project.name} - ${module.name} - API Documentation"
   		sourcepathref="module.src.path" classpathref="module.class.path" packagenames="*">
      <arg value="-J-Dhttp.proxyHost=${http.proxyHost}"/>
      <arg value="-J-Dhttp.proxyPort=${http.proxyPort}"/>
      <bottom><![CDATA[<em><a href="http://www.apache.org/licenses/LICENSE-2.0">Licensed to the Apache Software Foundation</a></em>]]></bottom>
      <link href="http://java.sun.com/j2se/1.5.0/docs/api/"/>
      <link href="http://download.oracle.com/docs/cd/E17477_01/javaee/5/api/"/>
      <link href="http://commons.apache.org/configuration/apidocs/"/>
      <tag name="todo" scope="all" description="Todo:" />
    </javadoc>
  </target>

  <uptodate property="test-doc.done" targetfile="${module.test.api}/index.html">
    <srcfiles dir="${module.test.src}" includes="**/*.java"/>
  </uptodate>

  <property name="module.test.doc.access" value="public"/>
  <target name="test-doc" depends="prepare" unless="testdoc.done" if="module.test.src.exists" description="generate test api-doc">
    <javadoc access="${module.test.doc.access}" destdir="${module.test.api}" author="false" version="true" use="true"
        windowtitle="${project.name} - ${module.name} - Test API Documentation"
   		sourcepathref="module.test.src.path" classpathref="module.test.path" packagenames="*">
      <arg value="-J-Dhttp.proxyHost=${http.proxyHost}"/>
      <arg value="-J-Dhttp.proxyPort=${http.proxyPort}"/>
      <bottom><![CDATA[<em><a href="http://www.apache.org/licenses/LICENSE-2.0">Licensed to the Apache Software Foundation</a></em>]]></bottom>
      <link href="http://java.sun.com/j2se/1.5.0/docs/api/"/>
      <link href="http://download.oracle.com/docs/cd/E17477_01/javaee/5/api/"/>
      <link href="http://commons.apache.org/configuration/apidocs/"/>
      <tag name="todo" scope="all" description="Todo:" />
    </javadoc>
  </target>

  <target name="release-bin-prepare">
    <mkdir dir="${module.release}"/>
    <available property="module.release.exists" file="${module.release}"/>
  </target>

  <target name="check-module-manifest">
    <uptodate property="module-manifest.done" targetfile="${qpid.jar}">
      <srcfiles dir="${build.lib}" includes="**/*.jar" excludes="**/${qpid.jar.name}"/>
    </uptodate>
  </target>

  <target name="module-manifest" depends="check-module-manifest" unless="module-manifest.done">
    <path id="class.path">
      <fileset dir="${module.release.lib}" >
        <include name="*.jar"/>
        <exclude name="${qpid.jar.name}"/>
      </fileset>
    </path>
    <pathconvert property="qpid.jar.classpath" pathsep=" " dirsep="/">
      <path refid="class.path"/>
      <globmapper from="${module.release.lib}${file.separator}*" to="*"/>
    </pathconvert>

    <jar destfile="${module.qpid.jar}">
      <manifest>
        <attribute name="Class-Path" value="${qpid.jar.classpath}"/>
      </manifest>
      <metainf dir="${project.root}/resources/"/>
    </jar>

    <touch file="${module.qpid.jar}"/>
  </target>

  <target name="zip-release"  depends="build-release-bin" description="build module release archive">
    <zip destfile="${module.release.zip}">
      <zipfileset dir="${module.release}" prefix="${module.namever}" filemode="755">
        <include name="bin/*"/>
	<exclude name="bin/*.txt"/>
      </zipfileset>

      <zipfileset dir="${module.release}" prefix="${module.namever}" filemode="644">
        <include name="bin/*.txt"/>
      </zipfileset>

      <zipfileset dir="${module.release}" prefix="${module.namever}" excludes="${module.release.excludes}" filemode="644" dirmode="755">
        <exclude name="bin/**"/>
	    <exclude name="**/*.class"/>
      </zipfileset>
    </zip>
  </target>

  <target name="bundle" description="Build module osgi artifact. Override and depend on bundle-tasks to use"/>

  <target name="bundle-tasks" depends="jar">
   <taskdef resource="aQute/bnd/ant/taskdef.properties" classpath="${project.root}/lib/bnd-0.0.384.jar"/>
   <echo message="Bundling ${build}/lib/${module.namever}.jar with ${module.src}/${module.name}.bnd"/>
   <bnd
      classpath="${build}/lib/${module.namever}.jar"
      eclipse="false"
      failok="false"
      exceptions="true"
      output="${build}/lib/${module.namever.osgi}.jar"
      files="${module.src}/${module.name}.bnd"/>
  </target>

    <target name="tar-release" depends="zip-release" description="build release archive">
      <tar destfile="${module.release.tar}" longfile="gnu" >
        <zipfileset src="${module.release.zip}"/>
      </tar>
    </target>

    <target name="gzip-release" depends="tar-release" description="build release archive">
      <gzip src="${module.release.tar}" destfile="${module.release.tgz}"/>
    </target>

    <target name="bzip2-release" depends="tar-release" description="build release archive">
      <bzip2 src="${module.release.tar}" destfile="${module.release.bz2}"/>
    </target>

    <target name="doc-release" description="no-op override if a doc step is requried "/>

    <target name="build-release-bin" depends="release-bin-prepare,libs-release,copy-bin-release,
                                              copy-etc-release,doc-release,resources-release,release-bin-other,module-manifest"
            description="Task that includes all tasks required to create a module binary release"/>

    <!-- ,zip-release,gzip-release -->
  <target name="release-bin-tasks" depends="gzip-release" description="build all release archives except .bz2"/>

  <target name="release-bin-all-tasks" depends="bzip2-release" description="build all release archives"/>

  <!-- Dummy targets to no-op for most modules. Override if a module package is required -->
  <target name="release-bin-other" description="Override if there is tasks required for the module bin release to occur last"/>
  <target name="release-bin" description="Override and depend on release-bin-tasks to generate"/>
  <target name="release-bin-all" description="Override and depend on release-bin-tasks to generate"/>

  <target name="clean" description="remove build artifacts">
    <delete dir="${module.build}"/>
    <delete dir="${module.results}"/>
    <delete dir="${module.release.base}"/>
    <delete dir="${module.instrumented}"/>
  </target>

  <target name="instrument" depends="cobertura-init">
    <cobertura-instrument todir="${module.instrumented}"
                          datafile="${cobertura.datafile}">
      <fileset dir="${module.classes}">
        <include name="**/*.class"/>
      </fileset>
    </cobertura-instrument>
  </target>

  <target name="cover-test" depends="instrument">

    <mkdir dir="${build.coveragereport}" />
    <junit fork="yes" forkmode="once" maxmemory="${test.mem}" reloading="no"
           haltonfailure="${haltonfailure}" haltonerror="${haltonerror}"
           failureproperty="test.failures" printsummary="on" timeout="600000" >

      <sysproperty key="amqj.logging.level" value="${amqj.logging.level}"/>
      <sysproperty key="amqj.protocol.logging.level" value="${amqj.protocol.logging.level}"/>
      <sysproperty key="log4j.debug" value="${log4j.debug}"/>
      <sysproperty key="root.logging.level" value="${root.logging.level}"/>
      <sysproperty key="log4j.configuration" value="${log4j.configuration}"/>
      <sysproperty key="java.naming.factory.initial" value="${java.naming.factory.initial}"/>
      <sysproperty key="java.naming.provider.url" value="${java.naming.provider.url}"/>
      <sysproperty key="broker" value="${broker}"/>
      <sysproperty key="broker.clean" value="${broker.clean}"/>
      <sysproperty key="broker.version" value="${broker.version}"/>
      <sysproperty key="broker.ready" value="${broker.ready}" />
      <sysproperty key="test.output" value="${module.results}"/>

      <syspropertyset>
        <propertyref prefix="test"/>
      </syspropertyset>
      <syspropertyset>
          <propertyref prefix="broker"/>
      </syspropertyset>

      <sysproperty key="max_prefetch" value ="${max_prefetch}"/>
      <sysproperty key="example.plugin.target" value="${project.root}/build/lib/plugins"/>
      <sysproperty key="QPID_EXAMPLE_HOME" value="${project.root}/build"/>
      <sysproperty key="QPID_HOME" value="${project.root}/build"/>

      <sysproperty key="net.sourceforge.cobertura.datafile"
		file="${cobertura.datafile}" />

      <formatter type="plain"/>
      <formatter type="xml"/>

      <classpath path="${module.instrumented}"/>
      <classpath>
        <fileset dir="${build}">
	  <include name="**/classes-instrumented/*.class"/>
	</fileset>
      </classpath>
      <classpath refid="module.test.path"/>
      <classpath refid="cobertura.classpath"/>

      <batchtest todir="${module.results}">
        <fileset dir="${module.test.src}" excludes="${module.test.excludes}">
          <include name="**/${test}.java"/>
        </fileset>
      </batchtest>
    </junit>
  </target>

  <target name="coverage-report" depends="cobertura-init">
      <echo message="${cobertura.datafile}"/>
      <cobertura-report format="html"
                      destdir="${module.coverage}"
		      datafile="${cobertura.datafile}">
      <fileset dir="${module.src}" includes="**/*.java" />
    </cobertura-report>
  </target>

  <property name="version.file" location="${module.classes}/qpidversion.properties"/>
  <property file="${version.file}" prefix="old."/>

  <target name="check-version">
    <exec executable="svnversion" spawn="false" failifexecutionfails="false"
        dir="${project.root}" outputproperty="svnversion.output">
      <arg line="."/>
    </exec>
    <condition property="version.stale">
      <not>
        <equals arg1="${svnversion.output}" arg2="${old.qpid.svnversion}"/>
      </not>
    </condition>
  </target>

  <target name="create-version" depends="check-version" if="version.stale">
    <!-- Write the version.properties out.-->
    <!-- Echos exactly as shown, so leave no spaces before/after lines -->
    <echo file="${version.file}" append="false">qpid.version=${andes.version}
qpid.svnversion=${svnversion.output}
qpid.name=${project.name}
</echo>
  </target>

   <!-- Additions to perform LogMessage generation
    To activate for your plugin add the following to your plugin build.xml

    <target name="precompile" depends="gen_logging"/>

   -->

    <property name="gentools.home" location="${project.root}/../gentools" />
    <property name="generated.dir" location="${module.precompiled}" />
    <property name="velocity.compile.dir" value="${build.scratch}/broker/velocity"/>
    <property name="velocity.timestamp" location="${generated.dir}/velocity.timestamp" />

    <target name="compile_velocity" >
        <mkdir dir="${velocity.compile.dir}" />
        <!-- Compile LogMessages Velocity Generator -->
        <javac source="${java.source}" target="${java.target}"
               destdir="${velocity.compile.dir}" debug="on" includeantruntime="false"
               deprecation="${javac.deprecation}"
               srcdir="${project.root}/broker/src/velocity/java" >
          <classpath>
            <pathelement path="${gentools.home}/lib/velocity-1.4.jar" />
          </classpath>
          <compilerarg line="${javac.compiler.args}"/>
        </javac>
    </target>

    <target name="check_velocity_deps">
      <uptodate property="velocity.notRequired" targetfile="${velocity.timestamp}">
        <srcfiles dir="${module.src}" includes="**/*_logmessages.properties" />
        <srcfiles dir="${project.root}/broker/src/velocity/" includes="**/*.java **/*.vm" />
      </uptodate>
    </target>

    <target name="gen_logging" depends="compile_velocity,check_velocity_deps" unless="velocity.notRequired">
      <mkdir dir="${generated.dir}"/>

      <path id="logmessages.path">
        <fileset  dir="${module.src}">
          <include name="**/*_logmessages.properties"/>
        </fileset>
      </path>

      <pathconvert property="logmessages"
                   refid="logmessages.path"
                   pathsep="' '"/>

      <echo message="logmessages is ${logmessages}"/>

      <java classname="org.wso2.andes.server.logging.GenerateLogMessages" fork="true" dir="${gentools.home}/src" failonerror="true">
        <arg line="'${logmessages}'"/>
          <arg value="-j"/>
          <arg value="-o"/>
          <arg value="${generated.dir}"/>
          <arg value="-t"/>
          <arg value="${project.root}/broker/src/velocity/templates/org/wso2/andes/server/logging/messages"/>
          <arg value="-s"/>
          <arg value="${module.src}"/>

        <classpath>
          <pathelement path="${module.src}"/>
          <pathelement path="${velocity.compile.dir}" />
          <fileset dir="${project.root}/lib">
            <include name="**/*.jar"/>
          </fileset>
          <pathelement path="${gentools.home}/lib/velocity-1.4.jar" />
        </classpath>
      </java>
      <touch file="${velocity.timestamp}" />
    </target>

    <target name="eclipse" depends="eclipse-setup,eclipse-project,eclipse-source-only,eclipse-source-and-test"/>

    <target name="eclipse-setup">
      <taskdef name="eclipse" classname="prantl.ant.eclipse.EclipseTask" />

      <!-- Build set of directories representing the dependencies -->

      <dirset id="eclipse.required.projectdirs.path" dir="${project.root}" includes="${module.depends} ${module.test.depends} neverBeEmpty">
        <!-- Select only those projects from module.depends that contain a build.xml.  This serves to exclude dependencies that
             don't become Eclipse projects e.g. broker-plugins and common-tests -->
        <present targetdir="${project.root}">
          <mapper type="glob" from="*" to="*/build.xml"/>
        </present>
      </dirset>

      <!-- Convert from the set of directories into Eclipse project names proceeded by forward slashes -->

      <pathconvert property="eclipse.required.projectnames" refid="eclipse.required.projectdirs.path" pathsep=" " dirsep="-">
        <map from="${project.root}${file.separator}" to=''/>
      </pathconvert>
      <map property="eclipse.required.slashedprojectnames" value="${eclipse.required.projectnames}" join="${path.separator}">
        <globmapper from="*" to="/*"/>
      </map>

      <echo message="Ant module dependencies : ${module.depends} ${module.test.depends} converted to Eclipse required project(s): ${eclipse.required.slashedprojectnames}"/>
      <path id="eclipse.required.slashedprojectnames.path">
        <pathelement path="${eclipse.required.slashedprojectnames}"/>
      </path>
    </target>

    <!-- Create the Eclipse .project -->
    <target name="eclipse-project">
      <eclipse updatealways="${eclipse.updatealways}">
        <project name="${module.name}"/>

        <!-- If the Eclipse task were to ever support the generation of
             linked resources, we would configure it to generate
             the following:

             scratch_src -> ${module.precompiled}

             in each project.   This would avoid the 'linked sources'
             manual step documented on the Wiki.
        -->
      </eclipse>
    </target>

    <!-- Create the Eclipse .classpath -->
    <target name="eclipse-source-only" unless="module.test.src.exists">
      <eclipse updatealways="${eclipse.updatealways}">
        <settings>
          <jdtcore compilercompliance="${eclipse.compilercompliance}" />
        </settings>
        <classpath>
          <container path="${eclipse.container}" />
          <source path="${module.src}" />
          <source pathref="eclipse.required.slashedprojectnames.path" />
          <library pathref="module.libs"/>
          <output path="classes" />
        </classpath>
      </eclipse>
    </target>

    <!-- Create the Eclipse .classpath -->
    <target name="eclipse-source-and-test" if="module.test.src.exists">
      <eclipse updatealways="${eclipse.updatealways}">
        <settings>
          <jdtcore compilercompliance="${eclipse.compilercompliance}" />
        </settings>
        <classpath>
          <container path="${eclipse.container}" />
          <source path="${module.src}" />
          <source path="${module.test.src}" />
          <source pathref="eclipse.required.slashedprojectnames.path" />
          <library pathref="module.libs"/>
          <library pathref="module.test.libs"/>
          <output path="classes" />
        </classpath>
      </eclipse>
    </target>
</project>


text:
<?php

namespace Slim\Exception;

use InvalidArgumentException;
use Psr\Container\ContainerExceptionInterface;

/**
 * Container Exception
 */
class ContainerException extends InvalidArgumentException implements ContainerExceptionInterface
{

}