Exemple #1
0
def task(event):
    b = request._get_body_string()
    data = json.loads(b)
    ifmaker = IfMaker(event, data.pop('key'))
    code, content = ifmaker.fetch(**data)
    response.status = code
    return content
def sendBill():
    print "Customer reviews the bill"
    bill=request._get_body_string()
    print "Bill is", bill
    payBill(bill)
    #print bill
    return "bill received"
Exemple #3
0
    def wrapper(*args, **kwargs):
        msg = '"{} {} {}"'.format(request.method, request.path,
                                  request.environ.get('SERVER_PROTOCOL', ''))

        if logger.isEnabledFor(logging.DEBUG):
            logger.debug('%s REQUEST: %s' % (msg, request._get_body_string()))
        else:
            logger.info('%s REQUEST:' % (msg))

        try:
            responseBody = callback(*args, **kwargs)
        except bottle.HTTPError as exc:
            logger.error('HTTPError: status: %s, body: %s, exception: %s' %
                         (exc.status, exc.body, exc.exception))
            raise
        except Exception as exc:
            logger.error('Unknown error: %s' % (exc))
            logger.info('StackTrace: %s' % (traceback.format_exc()))
            raise

        if logger.isEnabledFor(logging.DEBUG):
            logger.debug('%s RESPONSE %s: %s' %
                         (msg, response.status_code, responseBody))
        else:
            logger.info('%s RESPONSE %s:' % (msg, response.status_code))

        return responseBody
def callDownloadApk():
    '''
    url triming
    url = request._get_body_string().split('=')
    requestBody= url[1]
    :return:
    '''

    #Setting timeout as unirest calls get timed out because analysis takes time
    unirest.timeout(600000)
    requestBody = request._get_body_string()

    #Config reading
    if platform.system().lower() == "windows":
        db_config_file = os.path.join(os.path.dirname(sys.executable), 'androbugs-db.cfg')
    else:
        db_config_file = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'androbugs-db.cfg')

    if not os.path.isfile(db_config_file):
        print("[ERROR] AndroBugs Framework DB config file not found: " + db_config_file)
        traceback.print_exc()

    configParser = SafeConfigParser()
    configParser.read(db_config_file)

    downloadPath=configParser.get('General_Config', 'DownloadSciptPath')

    #Calling the download apk method
    cmd = 'python '+downloadPath+'download.py ' + requestBody
    print "cmd is: "+cmd
    os.system(cmd)
    #responseBase = unirest.post("http://localhost:8080/analyseApk", headers={ "Accept": "application/json" },
                                       #body={requestBody})
    return callAnalyseApk(requestBody+".apk")
Exemple #5
0
 def wrapper(*args, **kwargs):
     msg = '"{} {} {}"'.format(request.method, request.path,
                                     request.environ.get('SERVER_PROTOCOL', ''))
     
     if logger.isEnabledFor(logging.DEBUG):
         logger.debug('%s REQUEST: %s' % (msg, request._get_body_string()))
     else:
         logger.info('%s REQUEST:' % (msg))
     
     try:
         responseBody = callback(*args, **kwargs)
     except bottle.HTTPError as exc:
         logger.error('HTTPError: status: %s, body: %s, exception: %s' % (exc.status, exc.body, exc.exception))
         raise
     except Exception as exc:
         logger.error('Unknown error: %s' % (exc))
         logger.info('StackTrace: %s' % (traceback.format_exc()))
         raise
    
     if logger.isEnabledFor(logging.DEBUG):
         logger.debug('%s RESPONSE %s: %s' % (msg, response.status_code, responseBody))
     else:
         logger.info('%s RESPONSE %s:' % (msg, response.status_code))
         
     return responseBody
Exemple #6
0
def expect_json_request(request, schema=None):
    schema = schema or {}
    if 'application/json' not in request.content_type:
        raise InvalidClientRequest(
            'content-type was "%s", it should be "application/json"' %
            request.content_type)
    return parse_and_verify_json(request._get_body_string(), schema)
Exemple #7
0
 def do_POST_upgrade(self):
     data = request.json
     if not data:
         b = request._get_body_string()
         try:
             b = b.decode('utf-8')
         except:
             pass
         data = json.loads(b)
     return self.do_upgrade(data)
 def do_POST_test(self):
     data = request.json
     if not data:
         b = request._get_body_string()
         try:
             b = b.decode('utf-8')
         except:
             pass
         data = json.loads(b)
     return self.check_manifest(data, self.default_version)
 def do_POST_test(self):
     """Implement POST request to test posted data at default version."""
     data = request.json
     if not data:
         b = request._get_body_string()
         try:
             b = b.decode('utf-8')
         except:
             pass
         data = json.loads(b)
     return self.check_manifest(data, self.default_version)
def del_document():
    data=request._get_body_string()
    entity=json.loads(data)
    entity1 = db['shirts'].find_one({'shirtId':entity['shirtId']})
    if not entity1:
        abort(404, 'No document found with id %s' % entity['shirtId'])
    try:
        db['shirts'].remove({'shirtId':entity['shirtId']})
        return "OK"
    except ValidationError as ve:
        abort(400,str(ve))
 def do_POST_test(self):
     """Implement POST request to test posted data at default version."""
     data = request.json
     if not data:
         b = request._get_body_string()
         try:
             b = b.decode('utf-8')
         except:
             pass
         data = json.loads(b)
     return self.check_manifest(data, self.default_version)
Exemple #12
0
def login():
    body = loads(request._get_body_string().decode(utils.ENCODING))
    if db_utils.is_user_valid(body['username'], body['password']):
        hash_object = hashlib.sha512(bytes(body['username'], utils.ENCODING))
        hex_dig = hash_object.hexdigest()
        expires = utils.get_current_time() + COOKIE_LIFE
        db_utils.add_cookie(hex_dig, expires, body['username'])
        response.set_cookie('Hash', hex_dig)
        response.set_cookie('Alive_Until', str(expires))
    else:
        response.status = 401
Exemple #13
0
def create_stack():

    if plugin == "heat":

        version = bottle.request.get_header('version')
        username = bottle.request.get_header('username')
        password = bottle.request.get_header('password')
        endpoint = bottle.request.get_header('endpoint')
        tenant_name = bottle.request.get_header('tenant_name')
        tenant_id = bottle.request.get_header('tenant_id')
        service = bottle.request.get_header('service')
        region = bottle.request.get_header('region')
        heat_url = bottle.request.get_header('heat_url')
        stack_name = bottle.request.get_header('stack_name')

        stack = stack_create_heat(username, password, endpoint,
                                  tenant_name, heat_url,
                                  request._get_body_string(), stack_name)
        return stack['stack']['id']
    if plugin == "cloudify":
        stack_create_cloudify(request._get_body_string())
Exemple #14
0
def deploy_template():


    stack_name = my_random_string()

    request_file = open('requests/'+stack_name+'.yaml','w')
    request_file.write(request._get_body_string())
    request_file.close()

    orchetration('requests/'+stack_name+'.yaml', {}, True, stack_name)

    return stack_name
Exemple #15
0
def index():
    dt =  get_time_stamp()
    body = request._get_body_string()

    message = {}
    message['timestamp'] = get_time_stamp()
    message['hostname'] = hostname
    message['source'] = ipaddress
    message['message'] = body

    msg = json.dumps(message, ensure_ascii=False)
    queue.put(msg, True)
Exemple #16
0
def output_stack():

    if plugin == "heat":

        version = bottle.request.get_header('version')
        username = bottle.request.get_header('username')
        password = bottle.request.get_header('password')
        endpoint = bottle.request.get_header('endpoint')
        tenant_name = bottle.request.get_header('tenant_name')
        tenant_id = bottle.request.get_header('tenant_id')
        service = bottle.request.get_header('service')
        region = bottle.request.get_header('region')
        heat_url = bottle.request.get_header('heat_url')

        stack_uuid = bottle.request.get_header('uuid')
        stack_data = stack_output_heat(username, password, endpoint,
                                       tenant_name, heat_url, stack_uuid,
                                       request._get_body_string())
        return stack_data
    if plugin == "cloudify":
        stack_output_cloudify(request._get_body_string())
Exemple #17
0
def test():
    data_bytes = request._get_body_string()

    request_data = json.loads(data_bytes)
    cookie = request_data['cookie']

    returnVal = None
    # Handle new clients
    print(request_data)

    # Retrieve all rows with the cookie as ID
    curs.execute(
        "SELECT COUNT(*) FROM " + connectionTableName + " WHERE cookie=?;",
        (cookie, ))

    if curs.fetchone()[0] == 0:
        # Add new cookie ID into database
        curs.execute(
            "INSERT INTO " + connectionTableName +
            " (cookie, firstAccessDate, numValidMoves) VALUES (?,?,?)",
            (cookie, datetime.today().timestamp(), 0))
    elif request_data['clickPosition'] != -1:
        # if it's a valid move, update number of valid moves registered
        curs.execute(
            "UPDATE " + connectionTableName +
            " SET numValidMoves=numValidMoves+1 WHERE cookie=?", (cookie, ))

    # for row in curs.execute("SELECT * FROM " + connectionTableName):
    #     print(row)
    # commit changes to database
    conn.commit()

    if request_data['game_key'] not in games.keys():
        games[request_data['game_key']] = [Game(cookie), 100]
        returnVal = games[request_data['game_key']][0].handleClick(
            cookie, request_data['clickPosition'])
    else:
        returnVal = games[request_data['game_key']][0].handleClick(
            cookie, request_data['clickPosition'])
        # Reset time to live of games with valid user clicks not just render refreshes
        if request_data['clickPosition'] != -1:
            games[request_data['game_key']][1] = 100
    return HTTPResponse(
        status=200,
        headers={
            "Content-Type": "application/json",
            # "Access-Control-Allow-Origin": "*",
        },
        body=json.dumps(returnVal))
def post_document():
    data = request._get_body_string()
    if not data:
        abort(400, 'No data received')
    entity = json.loads(data)
    print entity['shirtId']
    if not entity.has_key('shirtId'):
        abort(400, 'No shirtId specified')
    try:
        d=datetime.datetime.now()
        date1=d.strftime("%d/%m/%y")
        entity['createdDate']=date1
        db['shirts'].save(entity)
        return "OK"
    except ValidationError as ve:
        abort(400, str(ve))
Exemple #19
0
 def _handle_ld_json(self):
     b = request._get_body_string()
     if request.headers.get('Content-Type', '').strip().startswith("application/ld+json"):
         # put the json into request.json, like application/json does automatically
         # Except it doesn't seem to work :(
         if b:
             request._json = json.loads(b)
         else:
             request._json = request.json
     elif b:
         try:
             j = self._rdf_to_jsonld(b)
             if j:
                 request._json = j
         except:
             raise
Exemple #20
0
def process_bower_json():
    bower_json = request.json

    if not bower_json:
        return abort(406, 'Please provide a bower.json.')

    if not 'name'         in bower_json \
    or not 'dependencies' in bower_json \
    or not isinstance(bower_json['name'],         unicode) \
    or not isinstance(bower_json['dependencies'], dict): \
        return abort(406, 'A valid bower.json object contains ' +
            'at least two keys: name and dependencies.')

    bower_json_str = request._get_body_string()
    pkgpath = pkg.find_package(bower_json_str)
    if pkgpath: redirect(pkgpath)
    abort(406, 'Error processing bower.json.')
Exemple #21
0
def transfer_form():
    post = FormsDict()
    # We default to application/x-www-form-urlencoded for everything that
    # is not multipart and take the fast path (also: 3.1 workaround)
    if not request.content_type.startswith('multipart/'):
        pairs = _parse_qsl(tonat(request._get_body_string(), 'latin1'))
        for key, value in pairs:
            post[key] = value
        return post

    request.environ['bottle.request.post'] = post

    get = request.environ['bottle.get'] = FormsDict()
    pairs = _parse_qsl(request.environ.get('QUERY_STRING', ''))
    for key, value in pairs:
        get[key] = value
    request.environ['bottle.request.query'] = get
Exemple #22
0
def hello_world():
    t_id = request.params.get('id')
    t_type = request.params.get('type')
    t_token = request.params.get('token')

    if (t_token != 'r0se_token' or t_id == None or t_type == None):
        return 'error'
    msg = request._get_body_string().decode()
    print('id ' + str(t_id) + '  type: ' + str(t_type) + ' token ' +
          str(t_token))
    print('msg: ' + str(msg))

    if (t_type == 'group'):
        event = SendMsgEvent(int(t_id), msg, is_group=True)
        bcc.postEvent(event)
    elif (t_type == 'friend'):
        event = SendMsgEvent(int(t_id), msg, is_group=False)
        bcc.postEvent(event)
    return 'ok'
Exemple #23
0
def webhook():
    logger.info('Delivery is started.')
    body = request._get_body_string()

    def start(task):
        ctx = Context()
        ctx.config.update(app.config)
        Thread(target=task, args=(ctx, )).start()

    # check signature
    # set defaults to prevent giving out 500
    signature = request.headers.get('X-Hub-Signature', '=')
    sha, signature = signature.split('=')
    secret = str.encode(app.config.get('github.secret', ''))
    digest = hmac.new(secret, body, digestmod='sha1').hexdigest()
    if hmac.compare_digest(digest, signature):
        # check branch or tag
        name = app.config.get('github.name', 'master')
        payload = json.loads(body.decode('utf-8'))

        # check for hook creation event
        zen = payload.get('zen', None)
        if zen:
            logger.info(zen)
        else:
            logger.info('Delivery ID={}'.format(
                request.headers.get('X-GitHub-Delivery', 'Unknown')))
            # either 'refs/heads/<name>' or 'refs/tags/<name>'
            heads_or_tags, pushed_name = payload['ref'].split('/')[-2:]
            logger.info('Name of a branch or a tag being pushed: {}'.format(
                pushed_name))
            if heads_or_tags == 'tags':
                start(tag)
            elif pushed_name == name:
                start(deploy)
            else:
                logger.info('Skipping delivery.')

    else:
        response.status = 401
        logger.error('Delivery was not authorized.')

    return json.dumps({})
Exemple #24
0
def goodprice_wx():
    xmldata = touni(request._get_body_string())
    alog.info(xmldata, 'goodprice_wx')
    #try:
    if True:
        recMsg = wx_receive.parse_xml(xmldata)
        if isinstance(recMsg, wx_receive.Msg) and recMsg.MsgType == 'text':
            toUser = recMsg.FromUserName
            fromUser = recMsg.ToUserName
            recv_content = touni(recMsg.Content)
            calc = GoodPriceCalc()
            alog.debug(recv_content, 'goodprice_wx', 'recMsg.Content')
            price_data = calc.calc(recv_content)
            content = calc.to_text(price_data, '<br>')
            replyMsg = wx_reply.TextMsg(toUser, fromUser, recv_content)
            s = replyMsg.send()
            alog.debug(s, 'goodprice_wx', 'reply')
            return s
        else:
            alog.info(s, 'goodprice_wx', u'不支持')
            return "success"
    """ except Exception as Argment:
def callDownloadApk():
    '''
    url triming
    url = request._get_body_string().split('=')
    requestBody= url[1]
    :return:
    '''

    #Setting timeout as unirest calls get timed out because analysis takes time
    unirest.timeout(600000)
    requestBody = request._get_body_string()

    #Config reading
    if platform.system().lower() == "windows":
        db_config_file = os.path.join(os.path.dirname(sys.executable),
                                      'androbugs-db.cfg')
    else:
        db_config_file = os.path.join(
            os.path.dirname(os.path.abspath(__file__)), 'androbugs-db.cfg')

    if not os.path.isfile(db_config_file):
        print("[ERROR] AndroBugs Framework DB config file not found: " +
              db_config_file)
        traceback.print_exc()

    configParser = SafeConfigParser()
    configParser.read(db_config_file)

    downloadPath = configParser.get('General_Config', 'DownloadSciptPath')

    #Calling the download apk method
    cmd = 'python ' + downloadPath + 'download.py ' + requestBody
    print "cmd is: " + cmd
    os.system(cmd)
    #responseBase = unirest.post("http://localhost:8080/analyseApk", headers={ "Accept": "application/json" },
    #body={requestBody})
    return callAnalyseApk(requestBody + ".apk")
def markPresence():
    requestBody = request._get_body_string()
    workers.orderQueue.put(requestBody)
    print requestBody
    return "Success"
Exemple #27
0
def send():
    workers.billQueue.put(request._get_body_string())
    #print requestBody
    return "Success"
Exemple #28
0
    def process_request(self):
        # ensure content negotiation has not already been applied
        if hasattr(request, 'nctx'):
            raise RuntimeError('Content negotiation applied twice on same request')
            
        # assign negotiation context
        request.nctx = nctx = ContentNegotiationContext()
        nctx.negotiator = self

        # determine which content types are accepted by the client
        try:
            raw_accept = request.headers.get('Accept', '*/*')
            nctx.request_accept = MediaTypeList(raw_accept)
        except ParseError as e:
            raise ex.ClientError(
                status_code='400 Invalid Accept',
                error_code='bad_request',
                error_desc="The request header 'Accept' was malformed")

        # determine what content type is sent by the request
        try:
            raw_content_type = request.headers.get('Content-Type', None)
            if raw_content_type:
                nctx.request_content_type = MediaType(raw_content_type)
        except ParseError:
            raise ex.ClientError(
                status_code='400 Invalid Content Type',
                error_code='bad_request',
                error_desc="The request header 'Content-Type' was malformed")

        # looks like content negotiation is enabled on this view
        request.body_parsed = None
        body = request._get_body_string()

        # assign default renderer class
        if self.mismatch_renderer_class:
            nctx.renderer = self.mismatch_renderer_class
            nctx.response_content_type = nctx.renderer.default_media_type

        # find appropriate renderer
        if nctx.request_accept:
            nctx.renderer, nctx.response_content_type = \
                self.select_renderer(nctx.request_accept)
            
            # could not negotiate an appropriate renderer
            if (not nctx.renderer and self.renderer_classes \
                and not self.mismatch_renderer_class):
                raise ex.ClientError(
                    status_code='406 Not Acceptable',
                    error_code='bad_request',
                    error_desc="The server could not negotiate response content based " \
                               "on the 'Accept-*' request headers")

        # attempt to guess content type if necessary
        if body and not raw_content_type:
            nctx.request_content_type = self.guess_content_type(body)

        # find appropriate content parser
        if nctx.request_content_type:
            nctx.parser = self.select_parser(nctx.request_content_type)

            # XXX: needs test
            if not nctx.parser:
                raise ex.ClientError(
                    status_code='415 Unsupported Media Type',
                    error_code='bad_request',
                    error_desc='The specified content type for request body is unsupported')

        # process body
        if nctx.parser:
            try:
                request.body_parsed = nctx.parser.parse(body)
            except Exception as exc:
                raise ex.ClientError(
                    status_code='400 Invalid Body',
                    error_code='bad_request',
                    error_desc='There was an error parsing the request body',
                    error_detail=str(exc))
Exemple #29
0
def add_recipe():
    response.content_type = 'application/json'
    body = loads(request._get_body_string().decode(utils.ENCODING))
    return dumps(db_utils.add_recipe(Recipe(body['name'], body['products'], body['description'])))
Exemple #30
0
def edit_user():
    body = loads(request._get_body_string().decode(utils.ENCODING))
    hash = request.get_cookie('Hash')
    if utils.is_admin(hash) or body['username'] == db_utils.get_cookie(hash)['user']:
        db_utils.edit_user(User(body['username'], body['password'], body['admin']))
    response.status = 401
Exemple #31
0
def add_user():
    if utils.is_admin(request.get_cookie('Hash')):
        response.content_type = 'application/json'
        body = loads(request._get_body_string().decode(utils.ENCODING))
        return dumps(db_utils.add_user(body['username'], body['password'], body['admin']))
    response.status = 401
Exemple #32
0
def placement():

    algo = bottle.request.get_header('algorithm')

    version = bottle.request.get_header('version')
    username = bottle.request.get_header('username')
    password = bottle.request.get_header('password')
    endpoint = bottle.request.get_header('endpoint')
    tenant_name = bottle.request.get_header('tenant_name')
    tenant_id = bottle.request.get_header('tenant_id')
    service = bottle.request.get_header('service')
    region = bottle.request.get_header('region')

    listVMs_json = json.loads(request._get_body_string())
    nbVMs = 0
    listVMs = {}

    for resource in listVMs_json:
        listVMs[listVMs_json[resource]['order']] = {}
        listVMs[listVMs_json[resource]
                ['order']]['cpu'] = listVMs_json[resource]['num_cpus']
        listVMs[listVMs_json[resource]
                ['order']]['mem'] = listVMs_json[resource]['mem_size']
        listVMs[listVMs_json[resource]
                ['order']]['sto'] = listVMs_json[resource]['disk_size']
        listVMs[listVMs_json[resource]['order']]['name'] = resource
        nbVMs = nbVMs + 1

    instanceIG_file = open("instanceIG" + str(nbVMs) + "-0", "w")
    instanceIG_file.write("Number of Servers\n")
    instanceIG_file.write(str(nbVMs) + " 1 1\n")
    instanceIG_file.write("Nodes\n")
    for vm in listVMs:
        instanceIG_file.write(
            str(vm) + " " + str(vm) + " " + str(listVMs[vm]['cpu']) +
            " 3 1 0\n")

    instanceIG_file.write("EDGES\n")
    for i in range(nbVMs - 1):
        instanceIG_file.write(str(i) + " " + str(i + 1) + " 100\n")

    instanceIG_file.close()

    s = requests.Session()
    print("GETing {} \n".format(MONI_URL))
    headers = {}
    headers['content-type'] = 'application/json'
    headers['version'] = version
    headers['username'] = username
    headers['password'] = password
    headers['endpoint'] = endpoint
    headers['tenant_name'] = tenant_name
    headers['tenant_id'] = tenant_id
    headers['service'] = service
    headers['region'] = region

    r = s.get(MONI_URL, headers=headers, stream=False)
    if r.status_code == 200:
        servers = json.loads(r.text)
        sorted_servers = sorted(
            servers['Reserved_resources']['CPU']['CPU_free_size'],
            key=natural_keys)
        instanceRG_file = open("instanceRG" + str(len(sorted_servers)) + "-0",
                               "w")
        instanceRG_file.write("Number of Nodes, Number of Servers\n")
        instanceRG_file.write(
            str(len(sorted_servers)) + " " + str(len(sorted_servers)) + "\n")
        instanceRG_file.write("Nodes\n")
        index_server = 0
        for server in sorted_servers:
            instanceRG_file.write(
                str(index_server) + " S:" + str(index_server) + " " +
                str(servers['Reserved_resources']['CPU']['CPU_free_size']
                    [server]) + " 0\n")
            index_server = index_server + 1

        instanceRG_file.write("EDGES\n")
        for i in range(len(sorted_servers) - 1):
            for j in range(len(sorted_servers) - 1, i, -1):
                instanceRG_file.write(str(i) + " " + str(j) + " 1000\n")

        instanceRG_file.close()

    else:
        print("=>Failure, status code: {} \n".format(r.status_code))
        response.status = r.status_code

    subprocess.call([
        'java', '-jar', 'placementAlgo.jar',
        'nbNodeRG=' + str(len(sorted_servers)), 'nbServerIG=' + str(nbVMs),
        'indexRG=0', 'indexIG=0', algo + '=true'
    ])

    if algo == 'mcts':
        SolutionMapping_file_name = "SolutionMappingMCTS-instanceRG" + str(
            len(sorted_servers)) + "-0-instanceIG" + str(nbVMs) + "-0"
    if algo == 'greedy':
        SolutionMapping_file_name = "SolutionMappingGreedy-instanceRG" + str(
            len(sorted_servers)) + "-0-instanceIG" + str(nbVMs) + "-0"
    if algo == 'eigen':
        SolutionMapping_file_name = "SolutionMappingEigen-instanceRG" + str(
            len(sorted_servers)) + "-0-instanceIG" + str(nbVMs) + "-0"

    SolutionMapping_file = open(SolutionMapping_file_name, "r")
    mapping_solution = {}
    for j in range(nbVMs):
        line = SolutionMapping_file.readline()
        mapping_solution[listVMs[int(
            line.split()[0])]['name']] = sorted_servers[int(line.split()[1])]

    return mapping_solution
def send():
    workers.garnishQueue.put(request._get_body_string())
    #print requestBody
    return "Success"
Exemple #34
0
def create_rfps():
    if plugin == "odl":
        print odl_create_rfps(json.loads(request._get_body_string()))
    if plugin == "onos":
        print onos_create_rfps(request._get_body_string())
def sendBill():
    bill=request._get_body_string()
    payBill(bill)
    print bill
    return "bill received"
Exemple #36
0
    def process_request(self):
        # ensure content negotiation has not already been applied
        if hasattr(request, 'nctx'):
            raise RuntimeError(
                'Content negotiation applied twice on same request')

        # assign negotiation context
        request.nctx = nctx = ContentNegotiationContext()
        nctx.negotiator = self

        # determine which content types are accepted by the client
        try:
            raw_accept = request.headers.get('Accept', '*/*')
            nctx.request_accept = MediaTypeList(raw_accept)
        except ParseError as e:
            raise ClientError(
                status_code='400 Invalid Accept',
                error_code='bad_request',
                error_desc="The request header 'Accept' was malformed")

        # determine what content type is sent by the request
        try:
            raw_content_type = request.headers.get('Content-Type', None)
            if raw_content_type:
                nctx.request_content_type = MediaType(raw_content_type)
        except ParseError:
            raise ClientError(
                status_code='400 Invalid Content Type',
                error_code='bad_request',
                error_desc="The request header 'Content-Type' was malformed")

        # looks like content negotiation is enabled on this view
        request.body_parsed = None
        body = request._get_body_string()

        # assign default renderer class
        if self.default_renderer:
            nctx.renderer = self.default_renderer
            nctx.response_content_type = nctx.renderer.default_media_type

        # find appropriate renderer
        if nctx.request_accept:
            nctx.renderer, nctx.response_content_type = \
                self.select_renderer(nctx.request_accept)

            # could not negotiate an appropriate renderer
            if (not nctx.renderer and self.renderers \
                and not self.default_renderer):
                raise ClientError(
                    status_code='406 Not Acceptable',
                    error_code='bad_request',
                    error_desc="The server could not negotiate response content based " \
                               "on the 'Accept-*' request headers")

        # attempt to guess content type if necessary
        if body and not raw_content_type:
            nctx.request_content_type = self.guess_content_type(body)

        # find appropriate content parser
        if nctx.request_content_type:
            nctx.parser = self.select_parser(nctx.request_content_type)

            # XXX: needs test
            if not nctx.parser:
                raise ClientError(
                    status_code='415 Unsupported Media Type',
                    error_code='bad_request',
                    error_desc=
                    'The specified content type for request body is unsupported'
                )

        # process body
        if nctx.parser:
            try:
                request.body_parsed = nctx.parser.parse(body)
            except Exception as exc:
                #import pdb; pdb.set_trace()
                raise ClientError(
                    status_code='400 Invalid Body',
                    error_code='bad_request',
                    error_desc='There was an error parsing the request body',
                    error_detail=str(exc))