text:
package ligueBaseball.models;

import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlTransient;

import ligueBaseball.entities.DatabaseEntity;
import ligueBaseball.entities.Player;
import ligueBaseball.entities.Team;
import ligueBaseball.exceptions.FailedToRetrievePlayersOfTeamException;
import ligueBaseball.exceptions.NotInstanceOfClassException;

import org.codehaus.jackson.annotate.JsonProperty;
import org.codehaus.jackson.map.annotate.JsonRootName;
import org.codehaus.jackson.map.annotate.JsonSerialize;
import org.codehaus.jackson.map.annotate.JsonSerialize.Inclusion;

@XmlRootElement(name = "joueur")
@JsonRootName("player")
@JsonSerialize(include = Inclusion.NON_NULL)
public class PlayerModel extends AbstractModel
{
    private int id;
    private String lastName;
    private String firstName;

    private int number;
    private String dateBegin;
    private String dateEnd;

    private TeamModel team;

    public PlayerModel() {

    }

    public PlayerModel(Player player) throws FailedToRetrievePlayersOfTeamException {
        this.createFromEntity(player);
    }

    public int getId()
    {
        return id;
    }

    public void setId(int id)
    {
        this.id = id;
    }

    @XmlAttribute(name = "nom")
    @JsonProperty("lastName")
    public String getLastName()
    {
        return lastName;
    }

    public void setLastName(String lastName)
    {
        this.lastName = lastName;
    }

    @XmlAttribute(name = "prenom")
    @JsonProperty("firstName")
    public String getFirstName()
    {
        return firstName;
    }

    public void setFirstName(String firstName)
    {
        this.firstName = firstName;
    }

    @XmlAttribute(name = "numero")
    @JsonProperty("number")
    public int getNumber()
    {
        return number;
    }

    public void setNumber(int number)
    {
        this.number = number;
    }

    @XmlAttribute(name = "datedebut")
    @JsonProperty("dateBegin")
    public String getDateBegin()
    {
        if (dateBegin != null) {
            return dateBegin;
            // return new SimpleDateFormat("dd-MMM-yyyy").format(dateBegin);
        }
        return "";
    }

    public void setDateBegin(String dateBegin)
    {
        this.dateBegin = dateBegin;
    }

    @XmlTransient
    @JsonProperty("dateEnd")
    public String getDateEnd()
    {
        return dateEnd;
    }

    public void setDateEnd(String dateEnd)
    {
        this.dateEnd = dateEnd;
    }

    @JsonProperty("team")
    public TeamModel getTeam()
    {
        return team;
    }

    public void removeTeam()
    {
        this.team = null;
    }

    @Override
    public void createFromEntity(DatabaseEntity entity) throws FailedToRetrievePlayersOfTeamException
    {
        if (!(entity instanceof Player)) {
            throw new NotInstanceOfClassException(this.getClass());
        }

        Player player = (Player) entity;
        this.setId(player.getId());
        this.setFirstName(player.getFirstName());
        this.setLastName(player.getLastName());
        this.setId(player.getId());
        try {
            if (player.getBeginningDate() != null) {
                this.setDateBegin(player.getBeginningDate().toString());
            }
        } catch (IllegalArgumentException e) {
            // do nothing
        }
        if (player.getEndDate() != null) {
            this.setDateEnd(player.getEndDate().toString());
        }
        this.setNumber(player.getNumber());

        Team team = player.getTeam();
        if (team != null) {
            this.team = new TeamModel(player.getTeam(), false);
        }
    }
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN""http://www.w3.org/TR/REC-html40/loose.dtd">

<TITLE>
BaseHash (GNU cryptographic primitives and tools)
</TITLE>
<META NAME="keywords" CONTENT="gnu.crypto.hash.BaseHash,BaseHash class">
<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../stylesheet.css" TITLE="Style">

      Overview
      Package
    Class
      Tree
      Serialized
      Deprecated
      Index
      Help

For the latest news and information visit
The GNU Crypto project

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

All Classes

  SUMMARY:  NESTED | FIELD | CONSTR | METHOD

DETAIL:  FIELD | CONSTR | METHOD

gnu.crypto.hash

Class BaseHash

java.lang.Object
  |
  +--gnu.crypto.hash.BaseHash

All Implemented Interfaces:
java.lang.Cloneable, IMessageDigest

Direct Known Subclasses:
Haval, MD2, MD4, MD5, RipeMD128, RipeMD160, Sha160, Sha256, Sha384, Sha512, Tiger, Whirlpool

public abstract class BaseHash
extends java.lang.Object
implements IMessageDigest

A base abstract class to facilitate hash implementations.

Field Summary

protected  int
blockSize

          The hash (inner) block size in bytes.

protected  byte[]
buffer

          Temporary input buffer.

protected  long
count

          Number of bytes processed so far.

protected  int
hashSize

          The hash (output) size in bytes.

protected  java.lang.String
name

          The canonical name prefix of the hash.

Constructor Summary

protected
BaseHash(java.lang.String name,
         int hashSize,
         int blockSize)

          Trivial constructor for use by concrete subclasses.

Method Summary

 int
blockSize()

          Returns the algorithm's (inner) block size in bytes.

abstract  java.lang.Object
clone()

          Returns a clone copy of this instance.

 byte[]
digest()

          Completes the message digest by performing final operations such as
 padding and resetting the instance.

protected abstract  byte[]
getResult()

          Constructs the result from the contents of the current context.

 int
hashSize()

          Returns the output length in bytes of this message digest algorithm.

 java.lang.String
name()

          Returns the canonical name of this algorithm.

protected abstract  byte[]
padBuffer()

          Returns the byte array to use as padding before completing a hash
 operation.

 void
reset()

          Resets the current context of this instance clearing any eventually cached
 intermediary values.

protected abstract  void
resetContext()

          Resets the instance for future re-use.

abstract  boolean
selfTest()

          A basic test.

protected abstract  void
transform(byte[] in,
          int offset)

          The block digest transformation per se.

 void
update(byte b)

          Continues a message digest operation using the input byte.

 void
update(byte[] b,
       int offset,
       int len)

          Continues a message digest operation, by filling the buffer, processing
 data in the algorithm's HASH_SIZE-bit block(s), updating the context and
 count, and buffering the remaining bytes in buffer for the next
 operation.

Methods inherited from class java.lang.Object

equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

name

protected java.lang.String name

The canonical name prefix of the hash.

hashSize

protected int hashSize

The hash (output) size in bytes.

blockSize

protected int blockSize

The hash (inner) block size in bytes.

count

protected long count

Number of bytes processed so far.

buffer

protected byte[] buffer

Temporary input buffer.

Constructor Detail

BaseHash

protected BaseHash(java.lang.String name,
                   int hashSize,
                   int blockSize)

Trivial constructor for use by concrete subclasses.

Parameters:
name - the canonical name prefix of this instance.
hashSize - the block size of the output in bytes.
blockSize - the block size of the internal transform.

Method Detail

name

public java.lang.String name()

Description copied from interface: IMessageDigest

Returns the canonical name of this algorithm.

Specified by:
name in interface IMessageDigest

Returns:
the canonical name of this instance.

hashSize

public int hashSize()

Description copied from interface: IMessageDigest

Returns the output length in bytes of this message digest algorithm.

Specified by:
hashSize in interface IMessageDigest

Returns:
the output length in bytes of this message digest algorithm.

blockSize

public int blockSize()

Description copied from interface: IMessageDigest

Returns the algorithm's (inner) block size in bytes.

Specified by:
blockSize in interface IMessageDigest

Returns:
the algorithm's inner block size in bytes.

update

public void update(byte b)

Description copied from interface: IMessageDigest

Continues a message digest operation using the input byte.

Specified by:
update in interface IMessageDigest

Parameters:
b - the input byte to digest.

update

public void update(byte[] b,
                   int offset,
                   int len)

Description copied from interface: IMessageDigest

Continues a message digest operation, by filling the buffer, processing
 data in the algorithm's HASH_SIZE-bit block(s), updating the context and
 count, and buffering the remaining bytes in buffer for the next
 operation.

Specified by:
update in interface IMessageDigest

Parameters:
b - the input block.
offset - start of meaningful bytes in input block.
len - number of bytes, in input block, to consider.

digest

public byte[] digest()

Description copied from interface: IMessageDigest

Completes the message digest by performing final operations such as
 padding and resetting the instance.

Specified by:
digest in interface IMessageDigest

Returns:
the array of bytes representing the hash value.

reset

public void reset()

Description copied from interface: IMessageDigest

Resets the current context of this instance clearing any eventually cached
 intermediary values.

Specified by:
reset in interface IMessageDigest

clone

public abstract java.lang.Object clone()

Description copied from interface: IMessageDigest

Returns a clone copy of this instance.

Specified by:
clone in interface IMessageDigest
Overrides:
clone in class java.lang.Object

Returns:
a clone copy of this instance.

selfTest

public abstract boolean selfTest()

Description copied from interface: IMessageDigest

A basic test. Ensures that the digest of a pre-determined message is equal
 to a known pre-computed value.

Specified by:
selfTest in interface IMessageDigest

Returns:
<tt>true</tt> if the implementation passes a basic self-test.
 Returns <tt>false</tt> otherwise.

padBuffer

protected abstract byte[] padBuffer()

Returns the byte array to use as padding before completing a hash
 operation.

Returns:
the bytes to pad the remaining bytes in the buffer before
 completing a hash operation.

getResult

protected abstract byte[] getResult()

Constructs the result from the contents of the current context.

Returns:
the output of the completed hash operation.

resetContext

protected abstract void resetContext()

Resets the instance for future re-use.

transform

protected abstract void transform(byte[] in,
                                  int offset)

The block digest transformation per se.

Parameters:
in - the blockSize long block, as an array of bytes to digest.
offset - the index where the data to digest is located within the
 input buffer.

      Overview
      Package
    Class
      Tree
      Serialized
      Deprecated
      Index
      Help

For the latest news and information visit
The GNU Crypto project

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

All Classes

  SUMMARY:  NESTED | FIELD | CONSTR | METHOD

DETAIL:  FIELD | CONSTR | METHOD

Copyright © 2001, 2002, 2003, 2004 Free Software Foundation, Inc.

redpajama_set_name: RedPajamaGithub


text:
var Querystring = require('querystring');
var Iron = require('iron');
var Items = require('items');
var Cryptiles = require('cryptiles');
var Boom = require('boom');
var Hoek = require('hoek');

// Declare internals

var internals = {};

internals.defaults = {
    global: {
        strictHeader: true,
        failAction: 'error',                            // 'error' bails on first error, other values ignored
    },
    cookie: {
        isSecure: false,
        isHttpOnly: false,
        path: null,
        domain: null,
        ttl: null,                                      // MSecs, 0 means remove
        encoding: 'none'                                // options: 'base64json', 'base64', 'form', 'iron', 'none'
    }
};

exports.Definitions = internals.Definitions = function (options) {

    this.settings = Hoek.applyToDefaults(internals.defaults.global, options || {});
    this.cookieDefaults = Hoek.applyToDefaults(internals.defaults.cookie, this.settings);
    this.cookies = {};
    this.names = [];
};

internals.Definitions.prototype.add = function (name, options) {

    Hoek.assert(name && typeof name === 'string', 'Invalid name');
    Hoek.assert(!this.cookies[name], 'State already defined:', name);

    this.cookies[name] = Hoek.applyToDefaults(this.cookieDefaults, options || {});
    this.names.push(name);
};

internals.empty = new internals.Definitions();

// Header format

//                      1: name                2: quoted  3: value
internals.parseRx = /\s*([^=\s]+)\s*=\s*(?:(?:"([^\"]*)")|([^\;]*))(?:(?:;\s*)|$)/g;

internals.validateRx = {
    nameRx: {
        strict: /^[^\x00-\x20\(\)<>@\,;\:\\"\/\[\]\?\=\{\}\x7F]+$/,
        loose: /^[^=\s]+$/
    },
    valueRx: {
        strict: /^[^\x00-\x20\"\,\;\\\x7F]*$/,
        loose: /^(?:"([^\"]*)")|(?:[^\;]*)$/
    },
    domainRx: /^\.?[a-z\d]+(?:(?:[a-z\d]*)|(?:[a-z\d\-]*[a-z\d]))(?:\.[a-z\d]+(?:(?:[a-z\d]*)|(?:[a-z\d\-]*[a-z\d])))*$/,
    domainLabelLenRx: /^\.?[a-z\d\-]{1,63}(?:\.[a-z\d\-]{1,63})*$/,
    pathRx: /^\/[^\x00-\x1F\;]*$/
};

//                      1: name         2: value
internals.pairsRx = /\s*([^=\s]+)\s*=\s*([^\;]*)(?:(?:;\s*)|$)/g;

exports.parse = function (cookies, definitions, next) {

    var state = {};
    var names = [];
    var verify = cookies.replace(internals.parseRx, function ($0, $1, $2, $3) {

        var name = $1;
        var value = $2 || $3 || '';

        if (state[name]) {
            if (!Array.isArray(state[name])) {
                state[name] = [state[name]];
            }

            state[name].push(value);
        }
        else {
            state[name] = value;
            names.push(name);
        }

        return '';
    });

    // Validate cookie header syntax

    if (verify !== '' &&
        definitions.settings.failAction === 'error') {

        return next(Boom.badRequest('Bad cookie header'), null, {});
    }

    // Fail action

    var invalids = {};

    var shouldStop = function (error, name, value, definition) {

        invalids[name] = {
            value: value,
            settings: definition,
            reason: error.message
        };

        if (definition.failAction === 'error') {
            next(Boom.badRequest('Bad cookie value: ' + Hoek.escapeHtml(name)), null, invalids);
            return true;
        }

        return false;
    };

    // Parse cookies

    var parsed = {};
    Items.serial(names, function (name, nextName) {

        var value = state[name];
        var definition = definitions.cookies[name] || definitions.cookieDefaults;

        // Validate cookie

        if (definition.strictHeader) {
            if (!name.match(internals.validateRx.nameRx.strict)) {
                if (shouldStop(Boom.badRequest('Invalid cookie name'), name, value, definition)) {
                    return;     // shouldStop calls next()
                }
            }

            var values = [].concat(state[name]);
            for (var v = 0, vl = values.length; v < vl; ++v) {
                if (!values[v].match(internals.validateRx.valueRx.strict)) {
                    if (shouldStop(Boom.badRequest('Invalid cookie value'), name, value, definition)) {
                        return;     // shouldStop calls next()
                    }
                }
            }
        }

        // Check cookie format

        if (definition.encoding === 'none') {
            parsed[name] = value;
            return nextName();
        }

        // Single value

        if (!Array.isArray(value)) {
            internals.unsign(name, value, definition, function (err, unsigned) {

                if (err) {
                    if (shouldStop(err, name, value, definition)) {
                        return;     // shouldStop calls next()
                    }

                    return nextName();
                }

                internals.decode(unsigned, definition, function (err, result) {

                    if (err) {
                        if (shouldStop(err, name, value, definition)) {
                            return;     // shouldStop calls next()
                        }

                        return nextName();
                    }

                    parsed[name] = result;
                    return nextName();
                });
            });

            return;
        }

        // Array

        var arrayResult = [];
        Items.serial(value, function (arrayValue, nextArray) {

            internals.unsign(name, arrayValue, definition, function (err, unsigned) {

                if (err) {
                    if (shouldStop(err, name, value, definition)) {
                        return;     // shouldStop calls next()
                    }

                    return nextName();
                }

                internals.decode(unsigned, definition, function (err, result) {

                    if (err) {
                        if (shouldStop(err, name, value, definition)) {
                            return;     // shouldStop calls next()
                        }

                        return nextName();
                    }

                    arrayResult.push(result);
                    nextArray();
                });
            });
        },
        function (err) {

            parsed[name] = arrayResult;
            return nextName();
        });
    },
    function (err) {

        // All cookies parsed

        return next(null, parsed, invalids);
    });
};

internals.macPrefix = 'hapi.signed.cookie.1';

internals.unsign = function (name, value, definition, next) {

    if (!definition.sign) {
        return next(null, value);
    }

    var pos = value.lastIndexOf('.');
    if (pos === -1) {
        return next(Boom.badRequest('Missing signature separator'));
    }

    var unsigned = value.slice(0, pos);
    var sig = value.slice(pos + 1);

    if (!sig) {
        return next(Boom.badRequest('Missing signature'));
    }

    var sigParts = sig.split('*');
    if (sigParts.length !== 2) {
        return next(Boom.badRequest('Bad signature format'));
    }

    var hmacSalt = sigParts[0];
    var hmac = sigParts[1];

    var macOptions = Hoek.clone(definition.sign.integrity || Iron.defaults.integrity);
    macOptions.salt = hmacSalt;
    Iron.hmacWithPassword(definition.sign.password, macOptions, [internals.macPrefix, name, unsigned].join('\n'), function (err, mac) {

        if (err) {
            return next(err);
        }

        if (!Cryptiles.fixedTimeComparison(mac.digest, hmac)) {
            return next(Boom.badRequest('Bad hmac value'));
        }

        return next(null, unsigned);
    });
};

internals.decode = function (value, definition, next) {

    // Encodings: 'base64json', 'base64', 'form', 'iron', 'none'

    if (definition.encoding === 'iron') {
        Iron.unseal(value, definition.password, definition.iron || Iron.defaults, function (err, unsealed) {

            if (err) {
                return next(err);
            }

            return next(null, unsealed);
        });

        return;
    }

    var result = value;

    try {
        switch (definition.encoding) {
            case 'base64json':
                var decoded = (new Buffer(value, 'base64')).toString('binary');
                result = JSON.parse(decoded);
                break;
            case 'base64':
                result = (new Buffer(value, 'base64')).toString('binary');
                break;
            case 'form':
                result = Querystring.parse(value);
                break;
        }
    }
    catch (err) {
        return next(err);
    }

    return next(null, result);
};

exports.format = function (cookies, definitions, callback) {

    definitions = definitions || internals.empty;

    if (!cookies ||
        (Array.isArray(cookies) && !cookies.length)) {

        return Hoek.nextTick(callback)(null, []);
    }

    if (!Array.isArray(cookies)) {
        cookies = [cookies];
    }

    var header = [];
    Items.serial(cookies, function (cookie, next) {

        // Apply definition to local configuration

        var base = definitions.cookies[cookie.name] || definitions.cookieDefaults;
        var definition = cookie.options ? Hoek.applyToDefaults(base, cookie.options) : base;

        // Validate name

        var nameRx = (definition.strictHeader ? internals.validateRx.nameRx.strict : internals.validateRx.nameRx.loose);
        if (!nameRx.test(cookie.name)) {
            return callback(Boom.badImplementation('Invalid cookie name: ' + cookie.name));
        }

        // Prepare value (encode, sign)

        exports.prepareValue(cookie.name, cookie.value, definition, function (err, value) {

            if (err) {
                return callback(err);
            }

            // Validate prepared value

            var valueRx = (definition.strictHeader ? internals.validateRx.valueRx.strict : internals.validateRx.valueRx.loose);
            if (value &&
                (typeof value !== 'string' || !value.match(valueRx))) {

                return callback(Boom.badImplementation('Invalid cookie value: ' + cookie.value));
            }

            // Construct cookie

            var segment = cookie.name + '=' + (value || '');

            if (definition.ttl !== null &&
                definition.ttl !== undefined) {            // Can be zero

                var expires = new Date(definition.ttl ? Date.now() + definition.ttl : 0);
                segment += '; Max-Age=' + Math.floor(definition.ttl / 1000) + '; Expires=' + expires.toUTCString();
            }

            if (definition.isSecure) {
                segment += '; Secure';
            }

            if (definition.isHttpOnly) {
                segment += '; HttpOnly';
            }

            if (definition.domain) {
                var domain = definition.domain.toLowerCase();
                if (!domain.match(internals.validateRx.domainLabelLenRx)) {
                    return callback(Boom.badImplementation('Cookie domain too long: ' + definition.domain));
                }

                if (!domain.match(internals.validateRx.domainRx)) {
                    return callback(Boom.badImplementation('Invalid cookie domain: ' + definition.domain));
                }

                segment += '; Domain=' + domain;
            }

            if (definition.path) {
                if (!definition.path.match(internals.validateRx.pathRx)) {
                    return callback(Boom.badImplementation('Invalid cookie path: ' + definition.path));
                }

                segment += '; Path=' + definition.path;
            }

            header.push(segment);
            return next();
        });
    },
    function (err) {

        return callback(null, header);
    });
};

exports.prepareValue = function (name, value, options, callback) {

    Hoek.assert(options && typeof options === 'object', 'Missing or invalid options');

    // Encode value

    internals.encode(value, options, function (err, encoded) {

        if (err) {
            return callback(Boom.badImplementation('Failed to encode cookie (' + name + ') value: ' + err.message));
        }

        // Sign cookie

        internals.sign(name, encoded, options.sign, function (err, signed) {

            if (err) {
                return callback(Boom.badImplementation('Failed to sign cookie (' + name + ') value: ' + err.message));
            }

            return callback(null, signed);
        });
    });
};

internals.encode = function (value, options, callback) {

    callback = Hoek.nextTick(callback);

    // Encodings: 'base64json', 'base64', 'form', 'iron', 'none'

    if (value === undefined) {
        return callback(null, value);
    }

    if (options.encoding === 'none') {
        return callback(null, value);
    }

    if (options.encoding === 'iron') {
        Iron.seal(value, options.password, options.iron || Iron.defaults, function (err, sealed) {

            if (err) {
                return callback(err);
            }

            return callback(null, sealed);
        });

        return;
    }

    var result = value;

    try {
        switch (options.encoding) {
            case 'base64':
                result = (new Buffer(value, 'binary')).toString('base64');
                break;
            case 'base64json':
                var stringified = JSON.stringify(value);
                result = (new Buffer(stringified, 'binary')).toString('base64');
                break;
            case 'form':
                result = Querystring.stringify(value);
                break;
        }
    }
    catch (err) {
        return callback(err);
    }

    return callback(null, result);
};

internals.sign = function (name, value, options, callback) {

    if (value === undefined ||
        !options) {

        return Hoek.nextTick(callback)(null, value);
    }

    Iron.hmacWithPassword(options.password, options.integrity || Iron.defaults.integrity, [internals.macPrefix, name, value].join('\n'), function (err, mac) {

        if (err) {
            return callback(err);
        }

        var signed = value + '.' + mac.salt + '*' + mac.digest;
        return callback(null, signed);
    });
};

exports.exclude = function (cookies, excludes) {

    var result = '';
    var verify = cookies.replace(internals.pairsRx, function ($0, $1, $2) {

        if (excludes.indexOf($1) === -1) {
            result += (result ? ';' : '') + $1 + '=' + $2;
        }

        return '';
    });

    return verify === '' ? result : Boom.badRequest('Bad cookie header');
};


text:
from tornado import log

from graphite_beacon import _compat as _
from graphite_beacon.template import TEMPLATES

LOGGER = log.gen_log

class HandlerMeta(type):

    loaded = {}
    handlers = {}

    def __new__(mcs, name, bases, params):
        cls = super(HandlerMeta, mcs).__new__(mcs, name, bases, params)
        name = params.get('name')
        if name:
            mcs.handlers[name] = cls
            LOGGER.info("Register Handler: %s", name)
        return cls

    @classmethod
    def clean(mcs):
        mcs.loaded = {}

    @classmethod
    def get(mcs, reactor, name):
        if name not in mcs.loaded:
            mcs.loaded[name] = mcs.handlers[name](reactor)
        return mcs.loaded[name]

class AbstractHandler(_.with_metaclass(HandlerMeta)):

    name = None
    defaults = {}

    def __init__(self, reactor):
        self.reactor = reactor
        self.options = dict(self.defaults)
        self.options.update(self.reactor.options.get(self.name, {}))
        self.init_handler()
        LOGGER.debug('Handler "%s" has inited: %s', self.name, self.options)

    def get_short(self, level, alert, value, target=None, ntype=None, rule=None):  # pylint: disable=unused-argument
        tmpl = TEMPLATES[ntype]['short']
        return tmpl.generate(
            level=level, reactor=self.reactor, alert=alert, value=value, target=target).strip()

    def init_handler(self):
        """ Init configuration here."""
        raise NotImplementedError()

    def notify(self, level, alert, value, target=None, ntype=None, rule=None):
        raise NotImplementedError()

registry = HandlerMeta  # pylint: disable=invalid-name

from .hipchat import HipChatHandler      # pylint: disable=wrong-import-position
from .http import HttpHandler            # pylint: disable=wrong-import-position
from .log import LogHandler              # pylint: disable=wrong-import-position
from .pagerduty import PagerdutyHandler  # pylint: disable=wrong-import-position
from .slack import SlackHandler          # pylint: disable=wrong-import-position
from .smtp import SMTPHandler            # pylint: disable=wrong-import-position
from .cli import CliHandler              # pylint: disable=wrong-import-position
from .opsgenie import OpsgenieHandler    # pylint: disable=wrong-import-position
from .victorops import VictorOpsHandler  # pylint: disable=wrong-import-position
from .telegram import TelegramHandler    # pylint: disable=wrong-import-position


text:
from __future__ import print_function
from __future__ import unicode_literals
from __future__ import division

from rest_framework import status

from django.http import JsonResponse
from django.core.cache import caches
from django.db import connections

from mmw.middleware import bypass_middleware

import uuid

@bypass_middleware
def health_check(request):
    response = {}

    for check in [_check_cache, _check_database]:
        response.update(check())

    if all(map(lambda x: x[0]['default']['ok'], response.values())):
        return JsonResponse(response, status=status.HTTP_200_OK)
    else:
        return JsonResponse(response,
                            status=status.HTTP_503_SERVICE_UNAVAILABLE)

def _check_cache(cache='default'):
    key = 'health-check-{}'.format(uuid.uuid4())

    try:
        caches[cache].set(key, uuid.uuid4())

        # Loss of connectivity to Redis does not always throw an
        # exception because DJANGO_REDIS_IGNORE_EXCEPTIONS is True.
        if caches[cache].get(key) is None:
            response = {cache: {'ok': False}}
        else:
            response = {cache: {'ok': True}}
            caches[cache].delete(key)
    except Exception as e:
        response = {
            cache: {
                'ok': False,
                'msg': str(e)
            },
        }

    return {'caches': [response]}

def _check_database(database='default'):
    try:
        connections[database].introspection.table_names()

        response = {database: {'ok': True}}
    except Exception as e:
        response = {
            database: {
                'ok': False,
                'msg': str(e)
            },
        }

    return {'databases': [response]}


text:
package com.sap.core.odata.core;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.fail;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyBoolean;
import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

import java.io.InputStream;
import java.util.Arrays;

import org.junit.Test;
import org.mockito.Matchers;
import org.mockito.Mockito;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;

import com.sap.core.odata.api.ODataService;
import com.sap.core.odata.api.ODataServiceFactory;
import com.sap.core.odata.api.batch.BatchHandler;
import com.sap.core.odata.api.commons.HttpStatusCodes;
import com.sap.core.odata.api.commons.ODataHttpMethod;
import com.sap.core.odata.api.edm.EdmException;
import com.sap.core.odata.api.exception.ODataBadRequestException;
import com.sap.core.odata.api.exception.ODataException;
import com.sap.core.odata.api.exception.ODataMethodNotAllowedException;
import com.sap.core.odata.api.processor.ODataProcessor;
import com.sap.core.odata.api.processor.ODataResponse;
import com.sap.core.odata.api.processor.part.BatchProcessor;
import com.sap.core.odata.api.processor.part.EntityComplexPropertyProcessor;
import com.sap.core.odata.api.processor.part.EntityLinkProcessor;
import com.sap.core.odata.api.processor.part.EntityLinksProcessor;
import com.sap.core.odata.api.processor.part.EntityMediaProcessor;
import com.sap.core.odata.api.processor.part.EntityProcessor;
import com.sap.core.odata.api.processor.part.EntitySetProcessor;
import com.sap.core.odata.api.processor.part.EntitySimplePropertyProcessor;
import com.sap.core.odata.api.processor.part.EntitySimplePropertyValueProcessor;
import com.sap.core.odata.api.processor.part.FunctionImportProcessor;
import com.sap.core.odata.api.processor.part.FunctionImportValueProcessor;
import com.sap.core.odata.api.processor.part.MetadataProcessor;
import com.sap.core.odata.api.processor.part.ServiceDocumentProcessor;
import com.sap.core.odata.core.uri.UriInfoImpl;
import com.sap.core.odata.core.uri.UriType;
import com.sap.core.odata.testutil.fit.BaseTest;

/**
 * Tests for request dispatching according to URI type and HTTP method.
 * @author SAP AG
 */
public class DispatcherTest extends BaseTest {

  public static ODataService getMockService() throws ODataException {
    ServiceDocumentProcessor serviceDocument = mock(ServiceDocumentProcessor.class);
    when(serviceDocument.readServiceDocument(any(UriInfoImpl.class), anyString())).thenAnswer(getAnswer());

    EntitySetProcessor entitySet = mock(EntitySetProcessor.class);
    when(entitySet.readEntitySet(any(UriInfoImpl.class), anyString())).thenAnswer(getAnswer());
    when(entitySet.countEntitySet(any(UriInfoImpl.class), anyString())).thenAnswer(getAnswer());
    when(entitySet.createEntity(any(UriInfoImpl.class), any(InputStream.class), anyString(), anyString())).thenAnswer(getAnswer());

    EntityProcessor entity = mock(EntityProcessor.class);
    when(entity.readEntity(any(UriInfoImpl.class), anyString())).thenAnswer(getAnswer());
    when(entity.existsEntity(any(UriInfoImpl.class), anyString())).thenAnswer(getAnswer());
    when(entity.deleteEntity(any(UriInfoImpl.class), anyString())).thenAnswer(getAnswer());
    when(entity.updateEntity(any(UriInfoImpl.class), any(InputStream.class), anyString(), anyBoolean(), anyString())).thenAnswer(getAnswer());

    EntityComplexPropertyProcessor entityComplexProperty = mock(EntityComplexPropertyProcessor.class);
    when(entityComplexProperty.readEntityComplexProperty(any(UriInfoImpl.class), anyString())).thenAnswer(getAnswer());
    when(entityComplexProperty.updateEntityComplexProperty(any(UriInfoImpl.class), any(InputStream.class), anyString(), anyBoolean(), anyString())).thenAnswer(getAnswer());

    EntitySimplePropertyProcessor entitySimpleProperty = mock(EntitySimplePropertyProcessor.class);
    when(entitySimpleProperty.readEntitySimpleProperty(any(UriInfoImpl.class), anyString())).thenAnswer(getAnswer());
    when(entitySimpleProperty.updateEntitySimpleProperty(any(UriInfoImpl.class), any(InputStream.class), anyString(), anyString())).thenAnswer(getAnswer());

    EntitySimplePropertyValueProcessor entitySimplePropertyValue = mock(EntitySimplePropertyValueProcessor.class);
    when(entitySimplePropertyValue.readEntitySimplePropertyValue(any(UriInfoImpl.class), anyString())).thenAnswer(getAnswer());
    when(entitySimplePropertyValue.deleteEntitySimplePropertyValue(any(UriInfoImpl.class), anyString())).thenAnswer(getAnswer());
    when(entitySimplePropertyValue.updateEntitySimplePropertyValue(any(UriInfoImpl.class), any(InputStream.class), anyString(), anyString())).thenAnswer(getAnswer());

    EntityLinkProcessor entityLink = mock(EntityLinkProcessor.class);
    when(entityLink.readEntityLink(any(UriInfoImpl.class), anyString())).thenAnswer(getAnswer());
    when(entityLink.existsEntityLink(any(UriInfoImpl.class), anyString())).thenAnswer(getAnswer());
    when(entityLink.deleteEntityLink(any(UriInfoImpl.class), anyString())).thenAnswer(getAnswer());
    when(entityLink.updateEntityLink(any(UriInfoImpl.class), any(InputStream.class), anyString(), anyString())).thenAnswer(getAnswer());

    EntityLinksProcessor entityLinks = mock(EntityLinksProcessor.class);
    when(entityLinks.readEntityLinks(any(UriInfoImpl.class), anyString())).thenAnswer(getAnswer());
    when(entityLinks.countEntityLinks(any(UriInfoImpl.class), anyString())).thenAnswer(getAnswer());
    when(entityLinks.createEntityLink(any(UriInfoImpl.class), any(InputStream.class), anyString(), anyString())).thenAnswer(getAnswer());

    MetadataProcessor metadata = mock(MetadataProcessor.class);
    when(metadata.readMetadata(any(UriInfoImpl.class), anyString())).thenAnswer(getAnswer());

    BatchProcessor batch = mock(BatchProcessor.class);
    when(batch.executeBatch(any(BatchHandler.class), anyString(), any(InputStream.class))).thenAnswer(getAnswer());

    FunctionImportProcessor functionImport = mock(FunctionImportProcessor.class);
    when(functionImport.executeFunctionImport(any(UriInfoImpl.class), anyString())).thenAnswer(getAnswer());

    FunctionImportValueProcessor functionImportValue = mock(FunctionImportValueProcessor.class);
    when(functionImportValue.executeFunctionImportValue(any(UriInfoImpl.class), anyString())).thenAnswer(getAnswer());

    EntityMediaProcessor entityMedia = mock(EntityMediaProcessor.class);
    when(entityMedia.readEntityMedia(any(UriInfoImpl.class), anyString())).thenAnswer(getAnswer());
    when(entityMedia.deleteEntityMedia(any(UriInfoImpl.class), anyString())).thenAnswer(getAnswer());
    when(entityMedia.updateEntityMedia(any(UriInfoImpl.class), any(InputStream.class), anyString(), anyString())).thenAnswer(getAnswer());

    ODataService service = mock(ODataService.class);
    when(service.getServiceDocumentProcessor()).thenReturn(serviceDocument);
    when(service.getEntitySetProcessor()).thenReturn(entitySet);
    when(service.getEntityProcessor()).thenReturn(entity);
    when(service.getEntityComplexPropertyProcessor()).thenReturn(entityComplexProperty);
    when(service.getEntitySimplePropertyProcessor()).thenReturn(entitySimpleProperty);
    when(service.getEntitySimplePropertyValueProcessor()).thenReturn(entitySimplePropertyValue);
    when(service.getEntityLinkProcessor()).thenReturn(entityLink);
    when(service.getEntityLinksProcessor()).thenReturn(entityLinks);
    when(service.getMetadataProcessor()).thenReturn(metadata);
    when(service.getBatchProcessor()).thenReturn(batch);
    when(service.getFunctionImportProcessor()).thenReturn(functionImport);
    when(service.getFunctionImportValueProcessor()).thenReturn(functionImportValue);
    when(service.getEntityMediaProcessor()).thenReturn(entityMedia);

    return service;
  }

  private static Answer<ODataResponse> getAnswer() {
    return new Answer<ODataResponse>() {
      @Override
      public ODataResponse answer(final InvocationOnMock invocation) {
        return mockResponse(invocation.getMethod().getName());
      }
    };
  }

  private static ODataResponse mockResponse(final String value) {
    ODataResponse response = mock(ODataResponse.class);
    when(response.getStatus()).thenReturn(HttpStatusCodes.PAYMENT_REQUIRED);
    when(response.getEntity()).thenReturn(value);

    return response;
  }

  private static UriInfoImpl mockUriInfo(final UriType uriType, final boolean isValue) throws EdmException {
    UriInfoImpl uriInfo = mock(UriInfoImpl.class);
    when(uriInfo.getUriType()).thenReturn(uriType);
    when(uriInfo.isValue()).thenReturn(isValue);
    return uriInfo;
  }

  private static void checkDispatch(final ODataHttpMethod method, final UriType uriType, final boolean isValue, final String expectedMethodName) throws ODataException {
    ODataServiceFactory factory = mock(ODataServiceFactory.class);

    final ODataResponse response = new Dispatcher(factory, getMockService())
        .dispatch(method, mockUriInfo(uriType, isValue), null, "application/xml", "*/*");
    assertEquals(expectedMethodName, response.getEntity());
  }

  private static void checkDispatch(final ODataHttpMethod method, final UriType uriType, final String expectedMethodName) throws ODataException {
    checkDispatch(method, uriType, false, expectedMethodName);
  }

  private static void wrongDispatch(final ODataHttpMethod method, final UriType uriType) {
    try {
      checkDispatch(method, uriType, null);
      fail("Expected ODataException not thrown");
    } catch (ODataMethodNotAllowedException e) {
      assertNotNull(e);
    } catch (ODataException e) {
      fail("Expected ODataMethodNotAllowedException not thrown");
    }
  }

  private static void notSupportedDispatch(final ODataHttpMethod method, final UriType uriType) {
    try {
      checkDispatch(method, uriType, null);
      fail("Expected ODataException not thrown");
    } catch (ODataBadRequestException e) {
      assertNotNull(e);
    } catch (ODataException e) {
      fail("Expected ODataBadRequestException not thrown");
    }
  }

  @Test
  public void dispatch() throws Exception {
    checkDispatch(ODataHttpMethod.GET, UriType.URI0, "readServiceDocument");

    checkDispatch(ODataHttpMethod.GET, UriType.URI1, "readEntitySet");
    checkDispatch(ODataHttpMethod.POST, UriType.URI1, "createEntity");

    checkDispatch(ODataHttpMethod.GET, UriType.URI2, "readEntity");
    checkDispatch(ODataHttpMethod.PUT, UriType.URI2, "updateEntity");
    checkDispatch(ODataHttpMethod.DELETE, UriType.URI2, "deleteEntity");
    checkDispatch(ODataHttpMethod.PATCH, UriType.URI2, "updateEntity");
    checkDispatch(ODataHttpMethod.MERGE, UriType.URI2, "updateEntity");

    checkDispatch(ODataHttpMethod.GET, UriType.URI3, "readEntityComplexProperty");
    checkDispatch(ODataHttpMethod.PUT, UriType.URI3, "updateEntityComplexProperty");
    checkDispatch(ODataHttpMethod.PATCH, UriType.URI3, "updateEntityComplexProperty");
    checkDispatch(ODataHttpMethod.MERGE, UriType.URI3, "updateEntityComplexProperty");

    checkDispatch(ODataHttpMethod.GET, UriType.URI4, "readEntitySimpleProperty");
    checkDispatch(ODataHttpMethod.PUT, UriType.URI4, "updateEntitySimpleProperty");
    checkDispatch(ODataHttpMethod.PATCH, UriType.URI4, "updateEntitySimpleProperty");
    checkDispatch(ODataHttpMethod.MERGE, UriType.URI4, "updateEntitySimpleProperty");
    checkDispatch(ODataHttpMethod.GET, UriType.URI4, true, "readEntitySimplePropertyValue");
    checkDispatch(ODataHttpMethod.PUT, UriType.URI4, true, "updateEntitySimplePropertyValue");
    checkDispatch(ODataHttpMethod.DELETE, UriType.URI4, true, "deleteEntitySimplePropertyValue");
    checkDispatch(ODataHttpMethod.PATCH, UriType.URI4, true, "updateEntitySimplePropertyValue");
    checkDispatch(ODataHttpMethod.MERGE, UriType.URI4, true, "updateEntitySimplePropertyValue");

    checkDispatch(ODataHttpMethod.GET, UriType.URI5, "readEntitySimpleProperty");
    checkDispatch(ODataHttpMethod.PUT, UriType.URI5, "updateEntitySimpleProperty");
    checkDispatch(ODataHttpMethod.PATCH, UriType.URI5, "updateEntitySimpleProperty");
    checkDispatch(ODataHttpMethod.MERGE, UriType.URI5, "updateEntitySimpleProperty");
    checkDispatch(ODataHttpMethod.GET, UriType.URI5, true, "readEntitySimplePropertyValue");
    checkDispatch(ODataHttpMethod.PUT, UriType.URI5, true, "updateEntitySimplePropertyValue");
    checkDispatch(ODataHttpMethod.DELETE, UriType.URI5, true, "deleteEntitySimplePropertyValue");
    checkDispatch(ODataHttpMethod.PATCH, UriType.URI5, true, "updateEntitySimplePropertyValue");
    checkDispatch(ODataHttpMethod.MERGE, UriType.URI5, true, "updateEntitySimplePropertyValue");

    checkDispatch(ODataHttpMethod.GET, UriType.URI6A, "readEntity");

    checkDispatch(ODataHttpMethod.GET, UriType.URI6B, "readEntitySet");
    checkDispatch(ODataHttpMethod.POST, UriType.URI6B, "createEntity");

    checkDispatch(ODataHttpMethod.GET, UriType.URI7A, "readEntityLink");
    checkDispatch(ODataHttpMethod.PUT, UriType.URI7A, "updateEntityLink");
    checkDispatch(ODataHttpMethod.DELETE, UriType.URI7A, "deleteEntityLink");
    checkDispatch(ODataHttpMethod.PATCH, UriType.URI7A, "updateEntityLink");
    checkDispatch(ODataHttpMethod.MERGE, UriType.URI7A, "updateEntityLink");

    checkDispatch(ODataHttpMethod.GET, UriType.URI7B, "readEntityLinks");
    checkDispatch(ODataHttpMethod.POST, UriType.URI7B, "createEntityLink");

    checkDispatch(ODataHttpMethod.GET, UriType.URI8, "readMetadata");

    checkDispatch(ODataHttpMethod.POST, UriType.URI9, "executeBatch");

    checkDispatch(ODataHttpMethod.GET, UriType.URI10, "executeFunctionImport");
    checkDispatch(ODataHttpMethod.GET, UriType.URI11, "executeFunctionImport");
    checkDispatch(ODataHttpMethod.GET, UriType.URI12, "executeFunctionImport");
    checkDispatch(ODataHttpMethod.GET, UriType.URI13, "executeFunctionImport");
    checkDispatch(ODataHttpMethod.GET, UriType.URI14, "executeFunctionImport");
    checkDispatch(ODataHttpMethod.GET, UriType.URI14, true, "executeFunctionImportValue");

    checkDispatch(ODataHttpMethod.GET, UriType.URI15, "countEntitySet");

    checkDispatch(ODataHttpMethod.GET, UriType.URI16, "existsEntity");

    checkDispatch(ODataHttpMethod.GET, UriType.URI17, "readEntityMedia");
    checkDispatch(ODataHttpMethod.PUT, UriType.URI17, "updateEntityMedia");
    checkDispatch(ODataHttpMethod.DELETE, UriType.URI17, "deleteEntityMedia");

    checkDispatch(ODataHttpMethod.GET, UriType.URI50A, "existsEntityLink");

    checkDispatch(ODataHttpMethod.GET, UriType.URI50B, "countEntityLinks");
  }

  @Test
  public void dispatchNotAllowedCombinations() throws Exception {
    wrongDispatch(null, UriType.URI0);

    wrongDispatch(ODataHttpMethod.PUT, UriType.URI0);
    wrongDispatch(ODataHttpMethod.POST, UriType.URI0);
    wrongDispatch(ODataHttpMethod.DELETE, UriType.URI0);
    wrongDispatch(ODataHttpMethod.PATCH, UriType.URI0);
    wrongDispatch(ODataHttpMethod.MERGE, UriType.URI0);

    wrongDispatch(ODataHttpMethod.PUT, UriType.URI1);
    wrongDispatch(ODataHttpMethod.DELETE, UriType.URI1);
    wrongDispatch(ODataHttpMethod.PATCH, UriType.URI1);
    wrongDispatch(ODataHttpMethod.MERGE, UriType.URI1);

    wrongDispatch(ODataHttpMethod.POST, UriType.URI2);

    wrongDispatch(ODataHttpMethod.POST, UriType.URI3);
    wrongDispatch(ODataHttpMethod.DELETE, UriType.URI3);

    wrongDispatch(ODataHttpMethod.POST, UriType.URI4);
    wrongDispatch(ODataHttpMethod.DELETE, UriType.URI4);

    wrongDispatch(ODataHttpMethod.POST, UriType.URI5);
    wrongDispatch(ODataHttpMethod.DELETE, UriType.URI5);

    wrongDispatch(ODataHttpMethod.POST, UriType.URI6A);

    wrongDispatch(ODataHttpMethod.PUT, UriType.URI6B);
    wrongDispatch(ODataHttpMethod.DELETE, UriType.URI6B);
    wrongDispatch(ODataHttpMethod.PATCH, UriType.URI6B);
    wrongDispatch(ODataHttpMethod.MERGE, UriType.URI6B);

    wrongDispatch(ODataHttpMethod.POST, UriType.URI7A);

    wrongDispatch(ODataHttpMethod.PUT, UriType.URI7B);
    wrongDispatch(ODataHttpMethod.DELETE, UriType.URI7B);
    wrongDispatch(ODataHttpMethod.PATCH, UriType.URI7B);
    wrongDispatch(ODataHttpMethod.MERGE, UriType.URI7B);

    wrongDispatch(ODataHttpMethod.PUT, UriType.URI8);
    wrongDispatch(ODataHttpMethod.POST, UriType.URI8);
    wrongDispatch(ODataHttpMethod.DELETE, UriType.URI8);
    wrongDispatch(ODataHttpMethod.PATCH, UriType.URI8);
    wrongDispatch(ODataHttpMethod.MERGE, UriType.URI8);

    wrongDispatch(ODataHttpMethod.GET, UriType.URI9);
    wrongDispatch(ODataHttpMethod.PUT, UriType.URI9);
    wrongDispatch(ODataHttpMethod.DELETE, UriType.URI9);
    wrongDispatch(ODataHttpMethod.PATCH, UriType.URI9);
    wrongDispatch(ODataHttpMethod.MERGE, UriType.URI9);

    wrongDispatch(ODataHttpMethod.PUT, UriType.URI15);
    wrongDispatch(ODataHttpMethod.POST, UriType.URI15);
    wrongDispatch(ODataHttpMethod.DELETE, UriType.URI15);
    wrongDispatch(ODataHttpMethod.PATCH, UriType.URI15);
    wrongDispatch(ODataHttpMethod.MERGE, UriType.URI15);

    wrongDispatch(ODataHttpMethod.PUT, UriType.URI16);
    wrongDispatch(ODataHttpMethod.POST, UriType.URI16);
    wrongDispatch(ODataHttpMethod.DELETE, UriType.URI16);
    wrongDispatch(ODataHttpMethod.PATCH, UriType.URI16);
    wrongDispatch(ODataHttpMethod.MERGE, UriType.URI16);

    wrongDispatch(ODataHttpMethod.POST, UriType.URI17);
    wrongDispatch(ODataHttpMethod.PATCH, UriType.URI17);
    wrongDispatch(ODataHttpMethod.MERGE, UriType.URI17);

    wrongDispatch(ODataHttpMethod.PUT, UriType.URI50A);
    wrongDispatch(ODataHttpMethod.POST, UriType.URI50A);
    wrongDispatch(ODataHttpMethod.DELETE, UriType.URI50A);
    wrongDispatch(ODataHttpMethod.PATCH, UriType.URI50A);
    wrongDispatch(ODataHttpMethod.MERGE, UriType.URI50A);

    wrongDispatch(ODataHttpMethod.PUT, UriType.URI50B);
    wrongDispatch(ODataHttpMethod.POST, UriType.URI50B);
    wrongDispatch(ODataHttpMethod.DELETE, UriType.URI50B);
    wrongDispatch(ODataHttpMethod.PATCH, UriType.URI50B);
    wrongDispatch(ODataHttpMethod.MERGE, UriType.URI50B);
  }

  @Test
  public void dispatchNotSupportedCombinations() throws Exception {
    notSupportedDispatch(ODataHttpMethod.PUT, UriType.URI6A);
    notSupportedDispatch(ODataHttpMethod.DELETE, UriType.URI6A);
    notSupportedDispatch(ODataHttpMethod.PATCH, UriType.URI6A);
    notSupportedDispatch(ODataHttpMethod.MERGE, UriType.URI6A);
  }

  private static void checkFeature(final UriType uriType, final boolean isValue, final Class<? extends ODataProcessor> feature) throws ODataException {
    ODataServiceFactory factory = mock(ODataServiceFactory.class);
    new Dispatcher(factory, getMockService());
    assertEquals(feature, Dispatcher.mapUriTypeToProcessorFeature(mockUriInfo(uriType, isValue)));
    assertEquals(feature, Dispatcher.mapUriTypeToProcessorFeature(mockUriInfo(uriType, isValue)));
  }

  @Test
  public void processorFeature() throws Exception {
    checkFeature(UriType.URI0, false, ServiceDocumentProcessor.class);
    checkFeature(UriType.URI1, false, EntitySetProcessor.class);
    checkFeature(UriType.URI2, false, EntityProcessor.class);
    checkFeature(UriType.URI3, false, EntityComplexPropertyProcessor.class);
    checkFeature(UriType.URI4, false, EntitySimplePropertyProcessor.class);
    checkFeature(UriType.URI4, true, EntitySimplePropertyValueProcessor.class);
    checkFeature(UriType.URI5, false, EntitySimplePropertyProcessor.class);
    checkFeature(UriType.URI5, true, EntitySimplePropertyValueProcessor.class);
    checkFeature(UriType.URI6A, false, EntityProcessor.class);
    checkFeature(UriType.URI6B, false, EntitySetProcessor.class);
    checkFeature(UriType.URI7A, false, EntityLinkProcessor.class);
    checkFeature(UriType.URI7B, false, EntityLinksProcessor.class);
    checkFeature(UriType.URI8, false, MetadataProcessor.class);
    checkFeature(UriType.URI9, false, BatchProcessor.class);
    checkFeature(UriType.URI10, false, FunctionImportProcessor.class);
    checkFeature(UriType.URI11, false, FunctionImportProcessor.class);
    checkFeature(UriType.URI12, false, FunctionImportProcessor.class);
    checkFeature(UriType.URI13, false, FunctionImportProcessor.class);
    checkFeature(UriType.URI14, false, FunctionImportProcessor.class);
    checkFeature(UriType.URI14, true, FunctionImportValueProcessor.class);
    checkFeature(UriType.URI15, false, EntitySetProcessor.class);
    checkFeature(UriType.URI16, false, EntityProcessor.class);
    checkFeature(UriType.URI17, false, EntityMediaProcessor.class);
    checkFeature(UriType.URI50A, false, EntityLinkProcessor.class);
    checkFeature(UriType.URI50B, false, EntityLinksProcessor.class);
  }

  @Test
  public void contentNegotiationDefaultCharset() throws Exception {
    negotiateContentTypeCharset("application/xml", "application/xml;charset=utf-8", false);
  }

  @Test
  public void contentNegotiationDefaultCharsetAsDollarFormat() throws Exception {
    negotiateContentTypeCharset("application/xml", "application/xml;charset=utf-8", true);
  }

  @Test
  public void contentNegotiationSupportedCharset() throws Exception {
    negotiateContentTypeCharset("application/xml;charset=utf-8", "application/xml;charset=utf-8", false);
  }

  @Test
  public void contentNegotiationSupportedCharsetAsDollarFormat() throws Exception {
    negotiateContentTypeCharset("application/xml;charset=utf-8", "application/xml;charset=utf-8", true);
  }

  @SuppressWarnings("unchecked")
  private void negotiateContentTypeCharset(final String requestType, final String supportedType, final boolean asFormat)
      throws SecurityException, IllegalArgumentException, NoSuchFieldException, IllegalAccessException, ODataException {

    ODataServiceFactory factory = mock(ODataServiceFactory.class);
    ODataService service = Mockito.mock(ODataService.class);
    Dispatcher dispatcher = new Dispatcher(factory, service);

    UriInfoImpl uriInfo = new UriInfoImpl();
    uriInfo.setUriType(UriType.URI1); //
    if (asFormat) {
      uriInfo.setFormat(requestType);
    }

    Mockito.when(service.getSupportedContentTypes(Matchers.any(Class.class))).thenReturn(Arrays.asList(supportedType));
    EntitySetProcessor processor = Mockito.mock(EntitySetProcessor.class);
    ODataResponse response = Mockito.mock(ODataResponse.class);
    Mockito.when(response.getContentHeader()).thenReturn(supportedType);
    Mockito.when(processor.readEntitySet(uriInfo, supportedType)).thenReturn(response);
    Mockito.when(service.getEntitySetProcessor()).thenReturn(processor);

    InputStream content = null;
    ODataResponse odataResponse = dispatcher.dispatch(ODataHttpMethod.GET, uriInfo, content, requestType, supportedType);
    assertEquals(supportedType, odataResponse.getContentHeader());
  }
}


text:
var common = require('../common');
var http = require('http');
var assert = require('assert');

// first 204 or 304 works, subsequent anything fails
var codes = [204, 200];

// Methods don't really matter, but we put in something realistic.
var methods = ['DELETE', 'DELETE'];

var server = http.createServer(function(req, res) {
  var code = codes.shift();
  assert.equal('number', typeof code);
  assert.ok(code > 0);
  console.error('writing %d response', code);
  res.writeHead(code, {});
  res.end();
});

var client = http.createClient(common.PORT);

function nextRequest() {
  var method = methods.shift();
  console.error('writing request: %s', method);

  var request = client.request(method, '/');
  request.on('response', function(response) {
    response.on('end', function() {
      if (methods.length == 0) {
        console.error('close server');
        server.close();
      } else {
        // throws error:
        nextRequest();
        // works just fine:
        //process.nextTick(nextRequest);
      }
    });
  });
  request.end();
}

server.listen(common.PORT, nextRequest);