Pause your app stream by app name and stream name

@param request The request object containing all parameters for pausing app session.
@return the response
354640
public PauseAppStreamResponse pauseAppStream(PauseAppStreamRequest request) {
        checkNotNull(request, "The parameter request should NOT be null.");
        checkStringNotEmpty(request.getApp(), "The parameter app should NOT be null or empty string.");
        checkStringNotEmpty(request.getStream(), "The parameter stream should NOT be null or empty string.");
        InternalRequest internalRequest = createRequest(HttpMethodName.PUT, request, LIVE_APP,
                request.getApp(), LIVE_SESSION, request.getStream());
        internalRequest.addParameter(PAUSE, null);
        return invokeHttpClient(internalRequest, PauseAppStreamResponse.class);
    }
640515
public GetSessionResponse getSession(GetSessionRequest request) {
        checkNotNull(request, "The parameter request should NOT be null.");
        checkStringNotEmpty(request.getSessionId(), "The parameter sessionId should NOT be null or empty string.");
        InternalRequest internalRequest = createRequest(HttpMethodName.GET, request, LIVE_SESSION,
                request.getSessionId());
        return invokeHttpClient(internalRequest, GetSessionResponse.class);
    }
65939
protected Optional<MutableHttpResponse<?>> handleRequest(HttpRequest request) {
        HttpHeaders headers = request.getHeaders();
        Optional<String> originHeader = headers.getOrigin();
        if (originHeader.isPresent()) {

            String requestOrigin = originHeader.get();
            boolean preflight = CorsUtil.isPreflightRequest(request);

            Optional<CorsOriginConfiguration> optionalConfig = getConfiguration(requestOrigin);

            if (optionalConfig.isPresent()) {
                CorsOriginConfiguration config = optionalConfig.get();

                HttpMethod requestMethod = request.getMethod();

                List<HttpMethod> allowedMethods = config.getAllowedMethods();

                if (!isAnyMethod(allowedMethods)) {
                    HttpMethod methodToMatch = preflight ? headers.getFirst(ACCESS_CONTROL_REQUEST_METHOD, HttpMethod.class).orElse(requestMethod) : requestMethod;
                    if (allowedMethods.stream().noneMatch(method -> method.equals(methodToMatch))) {
                        return Optional.of(HttpResponse.status(HttpStatus.FORBIDDEN));
                    }
                }

                if (preflight) {
                    Optional<List> accessControlHeaders = headers.get(ACCESS_CONTROL_REQUEST_HEADERS, Argument.of(List.class, String.class));

                    List<String> allowedHeaders = config.getAllowedHeaders();

                    if (!isAny(allowedHeaders) && accessControlHeaders.isPresent()) {
                        if (!accessControlHeaders.get().stream()
                            .allMatch(header -> allowedHeaders.stream()
                                .anyMatch(allowedHeader -> allowedHeader.equals(header.toString().trim())))) {
                            return Optional.of(HttpResponse.status(HttpStatus.FORBIDDEN));
                        }
                    }

                    MutableHttpResponse<Object> ok = HttpResponse.ok();
                    handleResponse(request, ok);
                    return Optional.of(ok);
                }
            }
        }

        return Optional.empty();
    }
858106
public static AipResponse post(AipRequest request) {
        String url;
        String charset = request.getContentEncoding();
        String content = request.getBodyStr();
        HashMap<String, String> header = request.getHeaders();
        AipResponse response = new AipResponse();

        DataOutputStream out = null;
        InputStream is = null;
        try {
            if (request.getParams().isEmpty()) {
                url = request.getUri().toString();
            }
            else {
                url = String.format("%s?%s", request.getUri().toString(), request.getParamStr());
            }

            URL console = new URL(url);
            Proxy proxy = request.getConfig() == null ? Proxy.NO_PROXY : request.getConfig().getProxy();
            HttpURLConnection conn = (HttpURLConnection) console.openConnection(proxy);

            // set timeout
            if (request.getConfig() != null) {
                conn.setConnectTimeout(request.getConfig().getConnectionTimeoutMillis());
                conn.setReadTimeout(request.getConfig().getSocketTimeoutMillis());
            }
            conn.setDoOutput(true);
            // 添加header
            for (Map.Entry<String, String> entry : header.entrySet()) {
                conn.setRequestProperty(entry.getKey(), entry.getValue());
            }

            conn.connect();
            out = new DataOutputStream(conn.getOutputStream());
            out.write(content.getBytes(charset));
            out.flush();
            int statusCode = conn.getResponseCode();
            response.setHeader(conn.getHeaderFields());
            response.setStatus(statusCode);
            response.setCharset(charset);
            if (statusCode != 200) {
                return response;
            }

            is = conn.getInputStream();
            if (is != null) {
                ByteArrayOutputStream outStream = new ByteArrayOutputStream();
                byte[] buffer = new byte[1024];
                int len = 0;
                while ((len = is.read(buffer)) != -1) {
                    outStream.write(buffer, 0, len);
                }
                response.setBody(outStream.toByteArray());
            }
            return response;
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return response;
    }
1041913
public static String getRequestURI(final HttpServletRequest request) {
		return (String) request.getSession(true).getAttribute(STORE_URI_KEY);
	}
1072337
def pause(self):
        """"""
        self._response['shouldEndSession'] = True
        self._response['action']['audio']['interface'] = 'pause'
        self._response['action']['audio']['sources'] = []
        return self
910937
@Override
  public void onNext(CreateLocalBlockRequest request) {
    final String methodName = request.getOnlyReserveSpace() ? "ReserveSpace" : "CreateBlock";
    RpcUtils.streamingRPCAndLog(LOG, new RpcUtils.StreamingRpcCallable<CreateLocalBlockResponse>() {
      @Override
      public CreateLocalBlockResponse call() throws Exception {
        if (request.getOnlyReserveSpace()) {
          mBlockWorker.requestSpace(mSessionId, request.getBlockId(), request.getSpaceToReserve());
          return CreateLocalBlockResponse.newBuilder().build();
        } else {
          Preconditions.checkState(mRequest == null);
          mRequest = request;
          if (mSessionId == INVALID_SESSION_ID) {
            mSessionId = IdUtils.createSessionId();
            String path = mBlockWorker.createBlock(mSessionId, request.getBlockId(),
                mStorageTierAssoc.getAlias(request.getTier()), request.getSpaceToReserve());
            CreateLocalBlockResponse response =
                CreateLocalBlockResponse.newBuilder().setPath(path).build();
            return response;
          } else {
            LOG.warn("Create block {} without closing the previous session {}.",
                request.getBlockId(), mSessionId);
            throw new InvalidWorkerStateException(
                ExceptionMessage.SESSION_NOT_CLOSED.getMessage(mSessionId));
          }
        }
      }

      @Override
      public void exceptionCaught(Throwable throwable) {
        if (mSessionId != INVALID_SESSION_ID) {
          // In case the client is a UfsFallbackDataWriter, DO NOT clean the temp blocks.
          if (throwable instanceof alluxio.exception.WorkerOutOfSpaceException
              && request.hasCleanupOnFailure() && !request.getCleanupOnFailure()) {
            mResponseObserver.onError(GrpcExceptionUtils.fromThrowable(throwable));
            return;
          }
          mBlockWorker.cleanupSession(mSessionId);
          mSessionId = INVALID_SESSION_ID;
        }
        mResponseObserver.onError(GrpcExceptionUtils.fromThrowable(throwable));
      }
    }, methodName, true, false, mResponseObserver, "Session=%d, Request=%s", mSessionId, request);
  }
359833
public Response api(Request request) throws IOException {
    Request req = new Request();
    req.setMethod(request.getMethod());
    req.setBaseUri(this.host);
    req.setEndpoint("/" + version + "/" + request.getEndpoint());
    req.setBody(request.getBody());
    for (Map.Entry<String, String> header : this.requestHeaders.entrySet()) {
      req.addHeader(header.getKey(), header.getValue());
    }
    for (Map.Entry<String, String> queryParam : request.getQueryParams().entrySet()) {
      req.addQueryParam(queryParam.getKey(), queryParam.getValue());
    }

    return makeCall(req);
  }
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);
    }
1018048
@Override
    public void pause(String targets) throws PauseableComponentControllerRequestFailedException {

        Tr.info(tc, "info.server.pause.request.received", targets);

        Set<String> foundTargets = new HashSet<String>();

        Set<String> targetList = createTargetList(targets);

        if (targetList.isEmpty()) {
            Tr.warning(tc, "warning.server.pause.invalid.targets");
            throw new PauseableComponentControllerRequestFailedException(Tr.formatMessage(tc, "warning.server.pause.invalid.targets"));
        }

        Set<String> failed = new HashSet<String>();

        //Add each pauseable component to this list. If the tracked values get modified
        //while we are iterating and we start over, skip anyone already in this list
        Set<PauseableComponent> processedList = new HashSet<PauseableComponent>();

        // Sync with other methods changing/querying states for PauseableComponents
        synchronized (this) {
            while (true) {
                try {
                    for (PauseableComponent pauseableComponent : tracker.getTracked().values()) {

                        if (processedList.add(pauseableComponent)) {

                            if (targetList.contains(pauseableComponent.getName())) {
                                foundTargets.add(pauseableComponent.getName());

                                try {
                                    pauseableComponent.pause();

                                } catch (Throwable t) {
                                    // Catch anything and mark a failed Add it to the failed list.
                                    failed.add(pauseableComponent.getName());
                                }
                            }
                        }
                    }

                    break;
                } catch (Throwable t) {
                    // Someone modified our list of services. Retry.
                }
            }
        }

        //Check which (if any) targets were not found
        boolean targetsNotFound = false;
        targetList.removeAll(foundTargets);
        if (!targetList.isEmpty()) {
            targetsNotFound = true;
            Tr.warning(tc, "warning.server.pause.missing.targets", Arrays.toString(targetList.toArray()));
        }

        //Check if we had any failures and throw an exception back with a list of failed pauseable components.
        if (!failed.isEmpty()) {

            Tr.error(tc, "error.server.pause.failed", Arrays.toString(failed.toArray()));

            throw new PauseableComponentControllerRequestFailedException(Tr.formatMessage(tc, "error.server.pause.failed", Arrays.toString(failed.toArray())));

        } else {
            Tr.info(tc, "info.server.pause.request.completed");

            if (targetsNotFound) {
                throw new PauseableComponentControllerRequestFailedException(Tr.formatMessage(tc, "warning.server.pause.missing.targets", Arrays.toString(targetList.toArray())));
            }
        }

    }
875201
@Override
    public PersistableUpload pause() throws PauseException {
        PauseResult<PersistableUpload> pauseResult = pause(true);
        if (pauseResult.getPauseStatus() != PauseStatus.SUCCESS) {
            throw new PauseException(pauseResult.getPauseStatus());
        }
        return pauseResult.getInfoToResume();
    }
307914
public void onRequest(HttpServletRequest request, HttpServletResponse response) {
        AbstractHttpServletActivity activity = null;

        final HttpServletRequestWrapper requestWrapper = new HttpServletRequestWrapper(request);
        final HttpSessionWrapper sessionWrapper = (HttpSessionWrapper) requestWrapper.getSession(false);
        final HttpServletRequestEvent requestEvent = new HttpServletRequestEventImpl(requestWrapper, response, this);
        final FireableEventType eventType = eventIdCache.getEventType(eventLookup, requestEvent, sessionWrapper);

        response.setStatus(HttpServletResponse.SC_NOT_IMPLEMENTED);

        if (eventIDFilter.filterEvent(eventType)) {
            if (tracer.isInfoEnabled()) {
                tracer.info("Request event filtered: " + requestEvent);
            }
            // dude, get out of here
            return;
        }

        boolean createActivity = true;
        if (sessionWrapper == null) {
            // create request activity
            activity = new HttpServletRequestActivityImpl();
        } else {
            activity = new HttpSessionActivityImpl(sessionWrapper);
            if (sessionWrapper.getResourceEntryPoint() != null) {
                createActivity = false;
            }
        }

        if (createActivity) {
            // we have a session but its not activity yet, add it
            try {
                if (sessionWrapper != null) {
                    sessionWrapper.setResourceEntryPoint(this.name);
                }
                sleeEndpoint.startActivity(activity, activity);
            } catch (ActivityAlreadyExistsException e) {
                if (tracer.isFineEnabled()) {
                    tracer.fine("Failed to add activity " + activity, e);
                }
                // proceed, may be due to fail over
            } catch (Throwable e) {
                tracer.severe("Failed to add activity " + activity, e);
                return;
            }
        }

        if (tracer.isFineEnabled()) {
            tracer.fine("Firing event " + requestEvent + " in activity " + activity);
        }

        final Object lock = requestLock.getLock(requestEvent);
        synchronized (lock) {
            try {
                sleeEndpoint.fireEvent(activity, eventType, requestEvent, null, null, EventFlags.REQUEST_EVENT_UNREFERENCED_CALLBACK);
                // block thread until event has been processed
                lock.wait(httpRequestTimeout);
                // the event was unreferenced or 15s timeout, if the activity is the request then end it
                if (sessionWrapper == null) {
                    endActivity(activity);
                }
            } catch (Throwable e) {
                tracer.severe("Failure while firing event " + requestEvent + " on activity " + activity, e);
            }
        }
    }
708909
@Override
	public void handleRequest(final Request request) {
		if (isDisabled()) {
			// Protect against client-side tampering of disabled/read-only fields.
			return;
		}

		// Remember which client side tab we were on.
		String[] indicesStr = request.getParameterValues(getId());

		if (indicesStr != null && indicesStr.length > 0) {
			List<Integer> oldIndices = getActiveIndices();
			List<Integer> changes = new ArrayList<>(1);
			int[] indices = new int[indicesStr.length];

			if (Util.empty(indicesStr[0])) {
				// Special case - no tab selected
				if (getType() == TYPE_ACCORDION) {
					indices = null;
				} else {
					int idx = findFirstVisibleTab();
					indices = new int[idx];
				}
			} else {
				// Normal case - one or more tabs selected
				for (int i = 0; i < indices.length; i++) {
					int clientIndex = Integer.parseInt(indicesStr[i]);
					int idx = clientIndexToTabIndex(clientIndex);
					indices[i] = idx;

					if (!oldIndices.contains(idx)) {
						// Check for a server mode tab and set focus
						WTab tab = getTab(idx);
						if (TabMode.SERVER.equals(tab.getMode()) && UIContextHolder.getCurrent().getFocussed() == null) {
							tab.setFocussed();
						}
						changes.add(idx);
					}
				}
			}

			setActiveIndices(indices);

			// Invoke action if tab selection has changed
			final Action action = getActionOnChange();

			if (action != null && !changes.isEmpty()) {
				final ActionEvent event = new ActionEvent(this, changes.toString(), null);

				Runnable later = new Runnable() {
					@Override
					public void run() {
						action.execute(event);
					}
				};

				invokeLater(later);
			}
		}

		String showHeadOnlyStr = request.getParameter(getId() + ".showHeadOnly");

		if (showHeadOnlyStr != null) {
			boolean showHeadOnly = "true".equals(showHeadOnlyStr);
			setShowHeadOnly(showHeadOnly);
		}
	}
1085611
public ListAppStreamsResponse listAppStreams(ListAppStreamsRequest request) {
        checkNotNull(request, "The parameter request should NOT be null.");
        checkStringNotEmpty(request.getApp(), "The parameter app should NOT be null or empty string.");
        InternalRequest internalRequest = createRequest(HttpMethodName.GET, request, LIVE_APP,
                request.getApp(), LIVE_SESSION);
        if (request.getStatus() != null) {
            internalRequest.addParameter("status", request.getStatus());
        }
        return invokeHttpClient(internalRequest, ListAppStreamsResponse.class);
    }
439706
public GetAppStreamResponse queryAppStream(GetAppStreamRequest request) {
        checkNotNull(request, "The parameter request should NOT be null.");
        checkStringNotEmpty(request.getApp(), "The parameter app should NOT be null or empty string.");
        checkStringNotEmpty(request.getStream(), "The parameter stream should NOT be null or empty string.");
        InternalRequest internalRequest = createRequest(HttpMethodName.GET, request, LIVE_APP,
                request.getApp(), LIVE_SESSION, request.getStream());
        return invokeHttpClient(internalRequest, GetAppStreamResponse.class);
    }
1316291
public RequestFuture<T> setRequest(Request<T> request) {
        this.request = request;
        this.request.addErrorListener(this);
        this.request.addResponseListener(this);
        return this;
    }
565895
public void queueRequest(RestRequest<?> request) {
        final RatelimitBucket bucket;
        final boolean alreadyInQueue;
        synchronized (buckets) {
            // Search for a bucket that fits to this request
            bucket = buckets.stream()
                    .filter(b -> b.equals(request.getEndpoint(), request.getMajorUrlParameter().orElse(null)))
                    .findAny()
                    .orElseGet(() -> new RatelimitBucket(
                            api, request.getEndpoint(), request.getMajorUrlParameter().orElse(null)));

            // Must be executed BEFORE adding the request to the queue
            alreadyInQueue = bucket.peekRequestFromQueue() != null;

            // Add the bucket to the set of buckets (does nothing if it's already in the set)
            buckets.add(bucket);

            // Add the request to the bucket's queue
            bucket.addRequestToQueue(request);
        }

        // If the bucket is already in the queue, there's nothing more to do
        if (alreadyInQueue) {
            return;
        }

        // Start working of the queue
        api.getThreadPool().getExecutorService().submit(() -> {
            RestRequest<?> currentRequest = bucket.peekRequestFromQueue();
            RestRequestResult result = null;
            long responseTimestamp = System.currentTimeMillis();
            while (currentRequest != null) {
                try {
                    int sleepTime = bucket.getTimeTillSpaceGetsAvailable();
                    if (sleepTime > 0) {
                        logger.debug("Delaying requests to {} for {}ms to prevent hitting ratelimits",
                                bucket, sleepTime);
                    }

                    // Sleep until space is available
                    while (sleepTime > 0) {
                        try {
                            Thread.sleep(sleepTime);
                        } catch (InterruptedException e) {
                            logger.warn("We got interrupted while waiting for a rate limit!", e);
                        }
                        // Update in case something changed (e.g. because we hit a global ratelimit)
                        sleepTime = bucket.getTimeTillSpaceGetsAvailable();
                    }

                    // Execute the request
                    result = currentRequest.executeBlocking();

                    // Calculate the time offset, if it wasn't done before
                    responseTimestamp = System.currentTimeMillis();
                } catch (Throwable t) {
                    responseTimestamp = System.currentTimeMillis();
                    if (currentRequest.getResult().isDone()) {
                        logger.warn("Received exception for a request that is already done. "
                                + "This should not be able to happen!", t);
                    }
                    // Try to get the response from the exception if it exists
                    if (t instanceof DiscordException) {
                        result = ((DiscordException) t).getResponse()
                                .map(RestRequestResponseInformationImpl.class::cast)
                                .map(RestRequestResponseInformationImpl::getRestRequestResult)
                                .orElse(null);
                    }
                    // Complete the request
                    currentRequest.getResult().completeExceptionally(t);
                } finally {
                    try {
                        // Calculate offset
                        calculateOffset(responseTimestamp, result);
                        // Handle the response
                        handleResponse(currentRequest, result, bucket, responseTimestamp);
                    } catch (Throwable t) {
                        logger.warn("Encountered unexpected exception.", t);
                    }

                    // The request didn't finish, so let's try again
                    if (!currentRequest.getResult().isDone()) {
                        continue;
                    }

                    // Poll a new quest
                    synchronized (buckets) {
                        bucket.pollRequestFromQueue();
                        currentRequest = bucket.peekRequestFromQueue();
                        if (currentRequest == null) {
                            buckets.remove(bucket);
                        }
                    }
                }
            }
        });
    }