/*
See JSDoc for oBatch.deserializeBatchResponse.
Additional parameter bIsChangeSet indicates whether sResponseBody represents a
change set.
349375
function _deserializeBatchResponse(sContentType, sResponseBody, bIsChangeSet) {
		var aBatchParts = sResponseBody.split(getBoundaryRegExp(sContentType)),
			aResponses = [];

		// skip preamble and epilogue
		aBatchParts = aBatchParts.slice(1, -1);

		aBatchParts.forEach(function (sBatchPart) {
			var sChangeSetContentType,
				sCharset,
				iColonIndex,
				sHeader,
				sHeaderName,
				sHeaderValue,
				aHttpHeaders,
				aHttpStatusInfos,
				i,
				sMimeHeaders,
				oResponse = {},
				iResponseIndex,
				aResponseParts;

			// aResponseParts will take 3 elements:
			// 0: general batch part headers
			// 1: HTTP response headers and status line
			// 2: HTTP response body
			aResponseParts = sBatchPart.split("\r\n\r\n");

			sMimeHeaders = aResponseParts[0];
			sChangeSetContentType = getChangeSetContentType(sMimeHeaders);
			if (sChangeSetContentType) {
				aResponses.push(_deserializeBatchResponse(sChangeSetContentType,
					aResponseParts.slice(1).join("\r\n\r\n"), true));
				return;
			}

			aHttpHeaders = aResponseParts[1].split("\r\n");
			// e.g. HTTP/1.1 200 OK
			aHttpStatusInfos = aHttpHeaders[0].split(" ");

			oResponse.status = parseInt(aHttpStatusInfos[1]);
			oResponse.statusText = aHttpStatusInfos.slice(2).join(' ');
			oResponse.headers = {};

			// start with index 1 to skip status line
			for (i = 1; i < aHttpHeaders.length; i += 1) {
				// e.g. Content-Type: application/json;odata.metadata=minimal
				sHeader = aHttpHeaders[i];
				iColonIndex = sHeader.indexOf(':');
				sHeaderName = sHeader.slice(0, iColonIndex).trim();
				sHeaderValue = sHeader.slice(iColonIndex + 1).trim();
				oResponse.headers[sHeaderName] = sHeaderValue;

				if (sHeaderName.toLowerCase() === "content-type") {
					sCharset = getHeaderParameterValue(sHeaderValue, "charset");
					if (sCharset && sCharset.toLowerCase() !== "utf-8") {
						throw new Error('Unsupported "Content-Type" charset: ' + sCharset);
					}
				}
			}

			// remove \r\n sequence from the end of the response body
			oResponse.responseText = aResponseParts[2].slice(0, -2);

			if (bIsChangeSet) {
				iResponseIndex = getChangeSetResponseIndex(sMimeHeaders);
				aResponses[iResponseIndex] = oResponse;
			} else {
				aResponses.push(oResponse);
			}
		});

		return aResponses;
	}
471895
function _setResponseBody(body) {
    verifyRequestSent(this);
    verifyHeadersReceived(this);
    verifyResponseBodyType(body);

    var chunkSize = this.chunkSize || 10;
    var index = 0;
    this.responseText = "";

    do {
      if (this.async) {
        this._readyStateChange(FakeXMLHttpRequest.LOADING);
      }

      this.responseText += body.substring(index, index + chunkSize);
      index += chunkSize;
    } while (index < body.length);

    var type = this.getResponseHeader("Content-Type");

    if (this.responseText && (!type || /(text\/xml)|(application\/xml)|(\+xml)/.test(type))) {
      try {
        this.responseXML = parseXML(this.responseText);
      } catch (e) {
        // Unable to parse XML - no biggie
      }
    }

    if (this.async) {
      this._readyStateChange(FakeXMLHttpRequest.DONE);
    } else {
      this.readyState = FakeXMLHttpRequest.DONE;
    }
  }
823563
@Override
  public final synchronized void handleSeSellerChanged(
    final Map<String, Object> pReqVars,
      final String pName) throws Exception {
    this.sesellers = null;
  }
1282566
function convertData(objectBody, objectChange) {
    const keysChange = Object.keys(objectChange);
    let objectReturn = {};
    keysChange.map(keyChange => {
        let changeOption = objectChange[keyChange];
        let valueKeyReturn = getValueChangeOption(objectBody, keyChange, changeOption, objectReturn);
        if(valueKeyReturn !== undefined && valueKeyReturn !== null){
            objectReturn[keyChange] = valueKeyReturn;
        }
        return keyChange;
    });
    return objectReturn;
}
330554
@Nonnull
  public static EChange setResponseGzipEnabled (final boolean bResponseGzipEnabled)
  {
    return s_aRWLock.writeLocked ( () -> {
      if (s_bResponseGzipEnabled == bResponseGzipEnabled)
        return EChange.UNCHANGED;
      s_bResponseGzipEnabled = bResponseGzipEnabled;
      LOGGER.info ("ResponseHelper responseGzipEnabled=" + bResponseGzipEnabled);
      return EChange.CHANGED;
    });
  }
515981
public static boolean varyMatches(
      Response cachedResponse, Headers cachedRequest, Request newRequest) {
    for (String field : varyFields(cachedResponse)) {
      if (!Objects.equals(cachedRequest.values(field), newRequest.headers(field))) return false;
    }
    return true;
  }
854035
@Nonnull
  public static ESuccess check (@Nonnull @Nonempty final String sServerSideKey,
                                @Nullable final String sReCaptchaResponse)
  {
    ValueEnforcer.notEmpty (sServerSideKey, "ServerSideKey");

    if (StringHelper.hasNoText (sReCaptchaResponse))
      return ESuccess.SUCCESS;

    final HttpClientFactory aHCFactory = new HttpClientFactory ();
    // For proxy etc
    aHCFactory.setUseSystemProperties (true);

    try (HttpClientManager aMgr = new HttpClientManager (aHCFactory))
    {
      final HttpPost aPost = new HttpPost (new SimpleURL ("https://www.google.com/recaptcha/api/siteverify").add ("secret",
                                                                                                                  sServerSideKey)
                                                                                                            .add ("response",
                                                                                                                  sReCaptchaResponse)
                                                                                                            .getAsURI ());
      final ResponseHandlerJson aRH = new ResponseHandlerJson ();
      final IJson aJson = aMgr.execute (aPost, aRH);
      if (aJson != null && aJson.isObject ())
      {
        final boolean bSuccess = aJson.getAsObject ().getAsBoolean ("success", false);

        if (GlobalDebug.isDebugMode ())
          LOGGER.info ("ReCpatcha Response for '" + sReCaptchaResponse + "': " + aJson.getAsJsonString ());

        return ESuccess.valueOf (bSuccess);
      }
    }
    catch (final IOException ex)
    {
      LOGGER.warn ("Error checking ReCaptcha response", ex);
    }
    return ESuccess.FAILURE;
  }
1069110
private boolean hasBody(Response response) {
        int status;

        status = response.getStatusLine().code;
        if ("HEAD".equals(method)) {
            return false;
        } else {
            return status >= StatusCode.OK && status != StatusCode.NO_CONTENT && status != StatusCode.NOT_MODIFIED && status != StatusCode.RESET_CONTENT;
        }
    }
912006
function bodyMinSizeChanged() {
                    var bodyMinSize = {};
                    if (_isBody && _contentArrangeElement) {
                        bodyMinSize.w = parseToZeroOrNumber(_contentArrangeElement.css(_strMinMinus + _strWidth));
                        bodyMinSize.h = parseToZeroOrNumber(_contentArrangeElement.css(_strMinMinus + _strHeight));
                        bodyMinSize.c = checkCacheDouble(bodyMinSize, _bodyMinSizeCache);
                        bodyMinSize.f = true; //flag for "measured at least once"
                    }
                    _bodyMinSizeCache = bodyMinSize;
                    return bodyMinSize.c || false;
                }
1327590
@Override
    public void handle(T result, HttpResponse response) {
        String transitionHeader = response.getHeaders().get(Headers.IBM_TRANSITION);
        if (transitionHeader != null) {
            result.setTransitionDate(parseDate(transitionHeader));
            String transition = parseTransition(transitionHeader);
            if (transition != null) {
                result.setTransition(transition);
            }
        }
    }
534452
function processResponse(err, res, cb){
  if(!err) {
    if(Array.isArray(res.body)){
      res.body.forEach(function (body) {
        castRecordDateFields(body);
      });
    } else if (_.isObject(res.body)) {
      castRecordDateFields(res.body);
    }
  }
  cb();
}
544221
private static boolean hasResponseBody(int requestMethod, int responseCode) {
        return requestMethod != Request.Method.HEAD
            && !(HttpStatus.SC_CONTINUE <= responseCode && responseCode < HttpStatus.SC_OK)
            && responseCode != HttpStatus.SC_NO_CONTENT
            && responseCode != HttpStatus.SC_NOT_MODIFIED;
    }
23362
@Override
  @SuppressWarnings("unchecked")
  public void stateChanged(Enum oldState, Enum newState) {
    logger.info("Diameter ACC SessionFactory :: stateChanged :: oldState[{}], newState[{}]", oldState, newState);
  }
930962
function parseCasResponse(casBody, logger, callback) {
  xml2js(casBody, {
    explicitRoot: false,
    tagNameProcessors: [stripPrefix]
  }, function(err, serviceResponse) {
    /* istanbul ignore if */
    if (err) {
      logger.error('Failed to parse CAS server response when trying to validate ticket.');
      logger.error(err);
      return callback(err, {
        message: 'Failed to parse CAS server response when trying to validate ticket.'
      });
    }

    if (!serviceResponse) {
      logger.error('Invalid CAS server response.');
      return callback(new Error('Invalid CAS server response, serviceResponse empty.'), {
        message: 'Invalid CAS server response, serviceResponse empty.'
      });
    }

    var success = serviceResponse.authenticationSuccess && serviceResponse.authenticationSuccess[0];

    if (!success) {
      logger.error('Receive response from CAS when validating ticket, but the validation is failed.');
      logger.error('Cas response:', serviceResponse);
      return callback(null, {});
    }

    var casResponse = {};
    for (var casProperty in success) {
      casResponse[casProperty] = success[casProperty][0];
    }

    return callback(null, casResponse);
  })
}
1182232
function sendChanges(changes, baseRevision, partial, onChangesAccepted) {
                ++requestId;
                acceptCallbacks[requestId.toString()] = onChangesAccepted;

                // In this example, the server expects the following JSON format of the request:
                //  {
                //      type: "changes"
                //      baseRevision: baseRevision,
                //      changes: changes,
                //      partial: partial,
                //      requestId: id
                //  }
                //  To make the sample simplified, we assume the server has the exact same specification of how changes are structured.
                //  In real world, you would have to pre-process the changes array to fit the server specification.
                //  However, this example shows how to deal with the WebSocket to fullfill the API.

                ws.send(JSON.stringify({
                    type: 'changes',
                    changes: changes,
                    partial: partial,
                    baseRevision: baseRevision,
                    requestId: requestId
                }));
            }
243305
private <T> T deserializeResult(Response response, @Nullable String envelopeFieldName, TypeRef returnType) throws WebApplicationException {
        String contentType = readContentType(response);
        String body = readBody(response);

        if (contentType.startsWith("application/json")) {
            try {
                if (envelopeFieldName!=null) {
                    return jsonMarshaller.deserializeEnveloped(body, envelopeFieldName, returnType);
                } else {
                    return jsonMarshaller.deserialize(body, returnType);
                }
            } catch (JsonMarshallingException e) {
                String msg = "Failed unmarshalling JSON data from server to object: "+e.getMessage();
//                throw new ClientErrorException(Response.Status.BAD_REQUEST, e);

                Retry retry;
                if (response.getStatusInfo().getFamily() == Response.Status.Family.SERVER_ERROR) {
                    //it is likely that the server can handle it next time, and there won't be an error at all.
                    //then there won't be a problem unmarshalling the error info either.
                    retry = Retry.now();
                } else {
                    //success:      no, because it's unlikely the server sends a different response next time.
                    //client error: no, because the client's data is wrong anyway, we just can't understand the detail
                    //              why it's wrong, but it's still wrong next time.
                    //              this could happen when the client uses an outdated protocol. server rejects it, and
                    //              the client can't even understand (the detail of) the response.
                    retry = Retry.no();
                }
                throw new ClientServiceException(
                        new RestFaultInfo(
                                "Protocol", Blame.CLIENT,
                                msg, ""+ErrorCodes.Client.UNMARSHALLING_FAILED.getCode(),
                                null,
                                retry, retry,
                                response.getStatusInfo().getStatusCode(),
                                response.getStatusInfo().getReasonPhrase()
                        ), e
                );
            }
        } else if (returnType.getType().equals(String.class)) {
            // Expecting string, return the raw response body.
            return (T) body;
        } else {
            String msg = "Client requested content type >>>"+ACCEPT+"<<< but server sent >>>\"" + contentType + "\"<<< and that is not supported for type: " + returnType.getType();
//            throw new NotSupportedException(msg);
            throw new BadResponseServiceException(
                    new RestFaultInfo("BadResponse", Blame.SERVER,
                            msg, ""+ErrorCodes.Server.BAD_RESPONSE.getCode(),
                            null,
                            Retry.no(), Retry.no(),
                            response.getStatusInfo().getStatusCode(),
                            response.getStatusInfo().getReasonPhrase()
                    )
            );
        }
    }
1192735
private JApiJavaObjectSerializationCompatibility.JApiJavaObjectSerializationChangeStatus checkChanges(JApiClass jApiClass) {
		JApiJavaObjectSerializationCompatibility.JApiJavaObjectSerializationChangeStatus state = JApiJavaObjectSerializationCompatibility.JApiJavaObjectSerializationChangeStatus.SERIALIZABLE_COMPATIBLE;
		if (jApiClass.getChangeStatus() == JApiChangeStatus.REMOVED) {
			return JApiJavaObjectSerializationCompatibility.JApiJavaObjectSerializationChangeStatus.SERIALIZABLE_INCOMPATIBLE_CLASS_REMOVED;
		}
		state = checkChangesForClassType(jApiClass, state);
		if (state != JApiJavaObjectSerializationCompatibility.JApiJavaObjectSerializationChangeStatus.SERIALIZABLE_COMPATIBLE) {
			return state;
		}
		state = checkChangesForSuperclass(jApiClass, state);
		if (state != JApiJavaObjectSerializationCompatibility.JApiJavaObjectSerializationChangeStatus.SERIALIZABLE_COMPATIBLE) {
			return state;
		}
		state = checkChangesForFields(jApiClass, state);
		if (state != JApiJavaObjectSerializationCompatibility.JApiJavaObjectSerializationChangeStatus.SERIALIZABLE_COMPATIBLE) {
			return state;
		}
		state = checkChangesForInterfaces(jApiClass, state);
		return state;
	}