/*
(non-Javadoc)
@see org.jdiameter.api.cxdx.ClientCxDxSession#sendMultimediaAuthRequest(org.jdiameter.api.cxdx.events.JMultimediaAuthRequest)
544292
@Override
  public void sendMultimediaAuthRequest(JMultimediaAuthRequest request)
      throws InternalException, IllegalDiameterStateException, RouteException, OverloadException {
    send(Event.Type.SEND_MESSAGE, request, null);
  }
985829
public static MultipartFormData getMultipart(ServletRequest request, UploadSetting uploadSetting) throws IORuntimeException {
		final MultipartFormData formData = new MultipartFormData(uploadSetting);
		try {
			formData.parseRequest(request);
		} catch (IOException e) {
			throw new IORuntimeException(e);
		}

		return formData;
	}
1293682
@Override
  public void doMultimediaAuthAnswer(ClientCxDxSession appSession, JMultimediaAuthRequest request, JMultimediaAuthAnswer answer)
      throws InternalException, IllegalDiameterStateException, RouteException, OverloadException {
    logger.info("Diameter Cx/Dx Session Factory :: doMultimediaAuthAnswer :: appSession[{}], Request[{}], Answer[{}]",
        new Object[]{appSession, request, answer});
  }
508283
public SetRequestAuthResponse setRequestAuth(SetRequestAuthRequest request) {
        checkNotNull(request, "The parameter request should NOT be null.");
        InternalRequest internalRequest = 
                createRequest(request, HttpMethodName.PUT, DOMAIN, request.getDomain(), "config");
        internalRequest.addParameter("requestAuth", "");
        this.attachRequestToBody(request, internalRequest);
        return invokeHttpClient(internalRequest, SetRequestAuthResponse.class);
    }
1044605
public static MultiMetaDataRequest of(final String... quandlCodes) {
    ArgumentChecker.notNullOrEmpty(quandlCodes, "quandlCodes");
    return new MultiMetaDataRequest(Arrays.asList(quandlCodes));
  }
1057509
protected <T extends RaftRequest, U extends RaftResponse> void sendRequest(T request, BiFunction<MemberId, T, CompletableFuture<U>> sender, CompletableFuture<U> future) {
    sendRequest(request, sender, 0, future);
  }
1174881
@Override
	public void serviceRequest(final Request request) {
		// Get expected step count
		UIContext uic = UIContextHolder.getCurrent();
		int expected = uic.getEnvironment().getStep();

		// Step should already be set on the session
		if (expected == 0) {
			throw new SystemException(
					"Step count should already be set on the session before content request.");
		}

		// Get step count on the request
		int got = StepCountUtil.getRequestStep(request);

		// Check tokens match (both must be provided)
		if (expected == got) {
			// Process Service Request
			getBackingComponent().serviceRequest(request);
		} else if (!StepCountUtil.isStepOnRequest(request) && StepCountUtil.isCachedContentRequest(request)) {  // cached content (no step on request)
			// Process Service Request
			getBackingComponent().serviceRequest(request);
		} else {  // Invalid token
			// Set an error code
			LOG.warn(
					"Wrong step detected for content request. Expected step [" + expected + "] but got step [" + got
					+ "].");
			handleError();
		}

	}
207049
public void doWithRequest(
                    final ClientHttpRequest request
                    )
    throws IOException
    {
        HttpHeaders  headers = request.getHeaders();
        headers.setContentType( _mediaType );

        long  size = IoUtil.copy( new StringReader( _string.toString() ),
                        new OutputStreamWriter( request.getBody() ) );
        headers.setContentLength( size );
    }
628468
public Mono<HttpResponse> send(HttpRequest request, ContextData contextData) {
        return httpPipeline.send(httpPipeline.newContext(request, contextData));
    }
605353
public void sendRequest(ClientTransaction ct) throws TransactionDoesNotExistException, SipException {
		final Request request = ct.getRequest();
		ensureCorrectDialogLocalTag(request);
		if (tracer.isInfoEnabled()) {
			tracer.info(String.valueOf(ct)+" sending request:\n"+request);
		}
		wrappedDialog.sendRequest(((ClientTransactionWrapper)ct).getWrappedClientTransaction());		
	}
403061
public void sendComponent(Component componentRequest) throws TCAPSendException {

        if (this.previewMode)
            return;

        if (this.provider.getStack().getStatisticsEnabled()) {
            switch (componentRequest.getType()) {
                case Invoke:
                    this.provider.getStack().getCounterProviderImpl().updateInvokeSentCount(this, (Invoke) componentRequest);

                    Invoke inv = (Invoke) componentRequest;
                    OperationCodeImpl oc = (OperationCodeImpl) inv.getOperationCode();
                    if (oc != null) {
                        this.provider.getStack().getCounterProviderImpl()
                                .updateOutgoingInvokesPerOperationCode(oc.getStringValue());
                    }
                    break;
                case ReturnResult:
                    this.provider.getStack().getCounterProviderImpl().updateReturnResultSentCount(this);
                    break;
                case ReturnResultLast:
                    this.provider.getStack().getCounterProviderImpl().updateReturnResultLastSentCount(this);
                    break;
                case ReturnError:
                    this.provider.getStack().getCounterProviderImpl().updateReturnErrorSentCount(this);

                    ReturnError re = (ReturnError) componentRequest;
                    ErrorCodeImpl ec = (ErrorCodeImpl) re.getErrorCode();
                    if (ec != null) {
                        this.provider.getStack().getCounterProviderImpl().updateOutgoingErrorsPerErrorCode(ec.getStringValue());
                    }
                    break;
                case Reject:
                    this.provider.getStack().getCounterProviderImpl().updateRejectSentCount(this);

                    Reject rej = (Reject) componentRequest;
                    ProblemImpl prob = (ProblemImpl) rej.getProblem();
                    if (prob != null) {
                        this.provider.getStack().getCounterProviderImpl().updateOutgoingRejectPerProblem(prob.getStringValue());
                    }
                    break;
            }
        }

        try {
            this.dialogLock.lock();
            if (componentRequest.getType() == ComponentType.Invoke) {
                InvokeImpl invoke = (InvokeImpl) componentRequest;

                // check if its taken!
                int invokeIndex = DialogImpl.getIndexFromInvokeId(invoke.getInvokeId());
                if (this.operationsSent[invokeIndex] != null) {
                    throw new TCAPSendException("There is already operation with such invoke id!");
                }

                invoke.setState(OperationState.Pending);
                invoke.setDialog(this);

                // if the Invoke timeout value has not be reset by TCAP-User
                // for this invocation we are setting it to the the TCAP stack
                // default value
                if (invoke.getTimeout() == TCAPStackImpl._EMPTY_INVOKE_TIMEOUT)
                    invoke.setTimeout(this.provider.getStack().getInvokeTimeout());
            } else {
                if (componentRequest.getType() != ComponentType.ReturnResult) {
                    // we are sending a response and removing invokeId from
                    // incomingInvokeList
                    this.removeIncomingInvokeId(componentRequest.getInvokeId());
                }
            }
            this.scheduledComponentList.add(componentRequest);
        } finally {
            this.dialogLock.unlock();
        }
    }
1330768
private void sendAsyncAuthenticationRequest(final int appId, final String bridgeId,
      final CallStatsHttp2Client httpClient) {
    synchronized (isAuthenticationInProgress) {
      if (isAuthenticationInProgress)
        return;
      isAuthenticationInProgress = true;

    }
    List<NameValuePair> params = new ArrayList<NameValuePair>();
    params.add(new NameValuePair("client_id", bridgeId + "@" + appId));
    params.add(new NameValuePair("code", tokenGenerator.generateToken(forcenewtoken)));
    params.add(new NameValuePair("grant_type", "authorization_code"));

    httpClient.sendAuthRequest(authenticateUrl, params, new CallStatsHttp2ResponseListener() {
      public void onResponse(Response response) {
        isAuthenticationInProgress = false;
        int responseStatus = response.code();
        if (responseStatus == CallStatsResponseStatus.RESPONSE_STATUS_SUCCESS) {
          AuthenticateResponse authResponseMessage;
          String responseString;
          try {
            responseString = response.body().string();
            authResponseMessage = gson.fromJson(responseString, AuthenticateResponse.class);
          } catch (Exception e) {
            e.printStackTrace();
            listener.onError(CallStatsErrors.HTTP_ERROR, e.getMessage());
            scheduleAuthentication(appId, bridgeId, httpClient);
            return;
          }
          logger.info(
              "Authentication response " + responseStatus + " " + authResponseMessage.getToken());
          // expires = authResponseMessage.getAuthenticateBody().getExpires();
          token = authResponseMessage.getToken();
          CallStatsConfigProvider.setURLs(authResponseMessage.getMetadata().getEventsUrl(),
              authResponseMessage.getMetadata().getStatsUrl());
          listener.onInitialized(authSuccessString);
        } else if (responseStatus == CallStatsResponseStatus.INVALID_REQUEST) {
          AuthenticateResponseError authResponseMessageError;
          String responseString;
          try {
            responseString = response.body().string();
            authResponseMessageError =
                gson.fromJson(responseString, AuthenticateResponseError.class);
          } catch (Exception e) {
            e.printStackTrace();
            listener.onError(CallStatsErrors.HTTP_ERROR, e.getMessage());
            scheduleAuthentication(appId, bridgeId, httpClient);
            return;
          }
          for (AuthenticateErrorAction action : authResponseMessageError.getErrorActions()) {
            if (action.getAction() == AuthenticateErrorActionType.GET_NEW_TOKEN) {
              forcenewtoken = true;
            } else if (action.getAction() == AuthenticateErrorActionType.RETRY) {
              authenticationRetryTimeout =
                  ((AuthenticateRetryActionParams) action.getParams()).getTimeout();
              scheduleAuthentication(appId, bridgeId, httpClient);
            }
          }
          listener.onError(CallStatsErrors.AUTH_ERROR, authErrString);
        } else if (responseStatus == CallStatsResponseStatus.GATEWAY_ERROR) {
          scheduleAuthentication(appId, bridgeId, httpClient);
          listener.onError(CallStatsErrors.APP_CONNECTIVITY_ERROR, authErrString);
        } else {
          scheduleAuthentication(appId, bridgeId, httpClient);
          listener.onError(CallStatsErrors.HTTP_ERROR, authErrString);
        }

      }


      public void onFailure(Exception e) {
        isAuthenticationInProgress = false;
        listener.onError(CallStatsErrors.HTTP_ERROR, e.getMessage());
      }

    });
  }
80154
public SignatureRequest sendSignatureRequest(SignatureRequest req) throws HelloSignException {
        if (req.hasId()) {
            throw new HelloSignException("Sending an existing signature request is not supported");
        }
        return new SignatureRequest(httpClient.withAuth(auth).withPostFields(req.getPostFields())
                .post(BASE_URI + SIGNATURE_REQUEST_SEND_URI).asJson());
    }
454797
protected <T extends RaftRequest, U extends RaftResponse> void sendRequest(T request, BiFunction<MemberId, T, CompletableFuture<U>> sender, int count, CompletableFuture<U> future) {
    MemberId node = next();
    if (node != null) {
      log.trace("Sending {} to {}", request, node);
      int selectionId = this.selectionId;
      sender.apply(node, request).whenCompleteAsync((r, e) -> {
        if (e != null || r != null) {
          handleResponse(request, sender, count, selectionId, node, r, e, future);
        } else {
          future.complete(null);
        }
      }, context);
    } else {
      future.completeExceptionally(new ConnectException("Failed to connect to the cluster"));
    }
  }
264535
protected HttpServletRequest processMultipart( HttpServletRequest request )
    {
        if ( ! "POST".equalsIgnoreCase( request.getMethod() ) ) return request;

        String contentType = request.getContentType();
        if ( contentType != null && contentType.startsWith( "multipart/form-data" ) )
        {
            PageFlowRequestWrapper pageFlowRequestWrapper = PageFlowRequestWrapper.get( request );

            //
            // We may have already gotten a multipart wrapper during process().  If so, use that.
            //
            MultipartRequestWrapper cachedWrapper = pageFlowRequestWrapper.getMultipartRequestWrapper();

            if ( cachedWrapper != null && cachedWrapper.getRequest() == request ) return cachedWrapper;

            try
            {
                //
                // First, pre-handle the multipart request.  This parses the stream and caches a single
                // MultipartRequestHandler in the outer request, so we can create new wrappers around it at will.
                //
                MultipartRequestUtils.preHandleMultipartRequest( request );
            }
            catch ( ServletException e )
            {
                LOG.error( "Could not parse multipart request.", e.getRootCause() );
                return request;
            }

            MultipartRequestWrapper ret = new RehydratedMultipartRequestWrapper( request );
            pageFlowRequestWrapper.setMultipartRequestWrapper( ret );
            return ret;
        }
        else
        {
            return request;
        }

    }
750424
public static boolean isMultipart(HttpRequest request) {
        if (request.headers().contains(HttpHeaderNames.CONTENT_TYPE)) {
            return getMultipartDataBoundary(request.headers().get(HttpHeaderNames.CONTENT_TYPE)) != null;
        } else {
            return false;
        }
    }
361540
public static boolean isMultipart(HttpServletRequest request) {
		if (false == isPostMethod(request)) {
			return false;
		}

		String contentType = request.getContentType();
		if (StrUtil.isBlank(contentType)) {
			return false;
		}
		if (contentType.toLowerCase().startsWith("multipart/")) {
			return true;
		}

		return false;
	}