Verify the returned JSON answer.
355175
private void verifyBulkJsonResponse(JSONAware pJsonResponse) throws J4pException {
        if (!(pJsonResponse instanceof JSONArray)) {
            if (pJsonResponse instanceof JSONObject) {
                JSONObject errorObject = (JSONObject) pJsonResponse;

                if (!errorObject.containsKey("status") || (Long) errorObject.get("status") != 200) {
                    throw new J4pRemoteException(null, errorObject);
                }
            }
            throw new J4pException("Invalid JSON answer for a bulk request (expected an array but got a " + pJsonResponse.getClass() + ")");
        }
    }
97362
def _JsonValueToPythonValue(json_value):
    """"""
    util.Typecheck(json_value, JsonValue)
    _ValidateJsonValue(json_value)
    if json_value.is_null:
        return None
    entries = [(f, json_value.get_assigned_value(f.name))
               for f in json_value.all_fields()]
    assigned_entries = [(f, value)
                        for f, value in entries if value is not None]
    field, value = assigned_entries[0]
    if not isinstance(field, messages.MessageField):
        return value
    elif field.message_type is JsonObject:
        return _JsonObjectToPythonValue(value)
    elif field.message_type is JsonArray:
        return _JsonArrayToPythonValue(value)
801873
def verify_response(response)
      if response.response.status == 401
        return PasswordRequired.new if !@device.password?
        return WrongPassword.new    if @device.password?
      end

      response
    end
960311
def to_json(self, value):
        """"""
        if not self.is_valid(value):
            raise ex.SerializeException('Invalid value: {}'.format(value))
        return value
415495
def _response_value(self, response, json=True):
        
        if json:
            contentType = response.headers.get("Content-Type", "")
            if not contentType.startswith(("application/json",
                                           "text/javascript")):
                if response.status_code == 200:
                    raise CloudStackException(
                        "JSON (application/json) was expected, got {!r}"
                        .format(contentType),
                        response=response)

                raise CloudStackException(
                    "HTTP {0.status_code} {0.reason}"
                    .format(response),
                    "Make sure endpoint URL {!r} is correct."
                    .format(self.endpoint),
                    response=response)

            try:
                data = response.json()
            except ValueError as e:
                raise CloudStackException(
                    "HTTP {0.status_code} {0.reason}"
                    .format(response),
                    "{0!s}. Malformed JSON document".format(e),
                    response=response)

            [key] = data.keys()
            data = data[key]
        else:
            data = response.text

        if response.status_code != 200:
            raise CloudStackException(
                "HTTP {0} response from CloudStack".format(
                    response.status_code),
                data,
                response=response)

        return data
298568
def validate_json(self):
        
        if not hasattr(self, 'guidance_json'):
            return False

        checksum = self.guidance_json.get('checksum')
        contents = self.guidance_json.get('db')

        hash_key = ("{}{}".format(json.dumps(contents, sort_keys=True),
                                  self.assignment.endpoint).encode())

        digest = hashlib.md5(hash_key).hexdigest()

        if not checksum:
            log.warning("Checksum on guidance not found. Invalidating file")
            return False
        if digest != checksum:
            log.warning("Checksum %s did not match actual digest %s", checksum, digest)
            return False
        return True
90789
def json(self):
        """"""
        if self._data_json:
            return self._data_json

        if not self.data or self.content_type != 'application/json':
            return None

        self._data_json = json.loads(self.data)
        return self._data_json
172001
def get_correctness(self, question_id):
        """"""
        response = self.get_response(question_id)
        if response.is_answered():
            item = self._get_item(response.get_item_id())
            return item.get_correctness_for_response(response)
        raise errors.IllegalState()
53290
def get_json_response(self):
        
        self.json_response = self.get_response().json()
        if self.json_response is not None:
            error_code = self.json_response.get("errcode", None)
            self.call_status = True if error_code == 0 else False
        return self.json_response
593662
def get_json_results(self, response):
        '''
        
        '''
        try:
            # return the proper JSON object, or error code if request didn't go through.
            self.most_recent_json = response.json()
            json_results = response.json()
            if response.status_code in [401, 403]: #401 is invalid key, 403 is out of monthly quota.
                raise PyMsCognitiveWebSearchException("CODE {code}: {message}".format(code=response.status_code,message=json_results["message"]) )
            elif response.status_code in [429]: #429 means try again in x seconds.
                message = json_results['message']
                try:
                    # extract time out seconds from response
                    timeout = int(re.search('in (.+?) seconds', message).group(1)) + 1
                    print ("CODE 429, sleeping for {timeout} seconds").format(timeout=str(timeout))
                    time.sleep(timeout)
                except (AttributeError, ValueError) as e:
                    if not self.silent_fail:
                        raise PyMsCognitiveWebSearchException("CODE 429. Failed to auto-sleep: {message}".format(code=response.status_code,message=json_results["message"]) )
                    else:
                        print ("CODE 429. Failed to auto-sleep: {message}. Trying again in 5 seconds.".format(code=response.status_code,message=json_results["message"]))
                        time.sleep(5)
        except ValueError as vE:
            if not self.silent_fail:
                raise PyMsCognitiveWebSearchException("Request returned with code %s, error msg: %s" % (r.status_code, r.text))
            else:
                print ("[ERROR] Request returned with code %s, error msg: %s. \nContinuing in 5 seconds." % (r.status_code, r.text))
                time.sleep(5)
        return json_results
932058
def validate_auto_threaded_json(pjson):
        """"""
        # pjson should be a dict or unicode
        if not type(pjson) is dict:
            raise ParseError("Expected a JSON object/dictionary or a string representing a test. Instead got %s." 
                             % pjson)

        # Make sure that the 'tests' key is present 
        try:
            tests = pjson["tests"]
        except KeyError:
            raise KeyError("Test object requires 'tests' attribute.\nObject: %s" % 
                           json.dumps(pjson))

        # Verify that tests is a list
        if type(tests) is not list:
            raise ParseError(
                "Expected 'tests' to be a list but got object of type %s.\nObject: %s" %
                (type(tests), json.dumps(tests))
            )

        # Verify that 'options' is a dict if present
        options = pjson.get('options', {})
        if type(options) is not dict:
            raise ParseError('"options" attribute must be a dictionary')

        # Verify that 'environments' is a list of dicts if present
        environments = pjson.get('environments', [])
        is_list_of_dicts = lambda ls: len(ls) == len(filter(lambda d: type(d) is dict, ls))
        if type(environments) is not list or not is_list_of_dicts(environments):
            raise ParseError('"environments" attribute must be a list of dictionaries. Instead got %s.' % environments)

        for test in tests:
            if type(test) is unicode:
                # Base case for recursion
                pass
            else:
                # Recur
                ConfigurationValidator.validate_auto_threaded_json(test)
494406
def validate_json(f):
    """"""
    @wraps(f)
    def wrapper(*args, **kw):
        instance = args[0]
        try:
            if request.get_json() is None:
                ret_dict = instance._create_ret_object(instance.FAILURE,
                                                       None, True,
                                                       instance.MUST_JSON)
                instance.logger.error(instance.MUST_JSON)
                return jsonify(ret_dict), 400
        except BadRequest:
            ret_dict = instance._create_ret_object(instance.FAILURE, None,
                                                   True,
                                                   instance.MUST_JSON)
            instance.logger.error(instance.MUST_JSON)
            return jsonify(ret_dict), 400
        instance.logger.debug("JSON is valid")
        return f(*args, **kw)
    return wrapper
992592
def is_correctness_available(self, question_id):
        """"""
        response = self.get_response(question_id)
        if response.is_answered():
            item = self._get_item(response.get_item_id())
            return item.is_correctness_available_for_response(response)
        return False
84590
def get_json_response(self, content, **kwargs):
        """"""

        # Don't care to return a django form or view in the response here.
        # Remove those from the context.
        if isinstance(content, dict):
            response_content = {k: deepcopy(v) for k, v in content.items()
                                if k not in ('form', 'view') or k in ('form', 'view')
                                and not isinstance(v, (Form, View))}
        else:
            response_content = content

        return HttpResponse(content=json.dumps(response_content),
                            content_type='application/json; charset=utf-8',
                            **kwargs)
768190
def get_correctness_for_response(self, response):
        """"""
        for answer in self.my_osid_object.get_answers():
            if self._is_match(response, answer):
                try:
                    return answer.get_score()
                except AttributeError:
                    return 100
        for answer in self.my_osid_object.get_wrong_answers():
            if self._is_match(response, answer):
                try:
                    return answer.get_score()
                except AttributeError:
                    return 0
        return 0
71668
def verify(self, checksum=None, token=None, full_response=False):
        """"""
        payload = {"checksum":checksum, "a":"verify"}
        if token:
            payload.update({"token":token})
        return self.get_shards(Shard(**payload), full_response=True)
204216
def run(self):
        """"""
        try:
            answer = urlopen(self.url + "&mode=queue").read().decode()
        except (HTTPError, URLError) as error:
            self.output = {
                "full_text": str(error.reason),
                "color": "#FF0000"
            }
            return

        answer = json.loads(answer)

        # if answer["status"] exists and is False, an error occured
        if not answer.get("status", True):
            self.output = {
                "full_text": answer["error"],
                "color": "#FF0000"
            }
            return

        queue = answer["queue"]
        self.status = queue["status"]

        if self.is_paused():
            color = self.color_paused
        elif self.is_downloading():
            color = self.color_downloading
        else:
            color = self.color

        if self.is_downloading():
            full_text = self.format.format(**queue)
        else:
            full_text = self.format_paused.format(**queue)

        self.output = {
            "full_text": full_text,
            "color": color
        }