/*
@see com.ibm.ws.tcpchannel.internal.ChannelSelector#performRequest()
764197
@Override
    protected boolean performRequest() {
        VirtualConnection vci = null;
        boolean completeOperation = true;
        TCPBaseRequestContext req = null;
        SelectionKey selectedKey = null;

        // If we were woken up because we have work to do, do it.
        Set<SelectionKey> keySet = selector.selectedKeys();
        Iterator<SelectionKey> selectedIterator = keySet.iterator();
        if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
            Tr.debug(this, tc, "performRequest - processing " + keySet.size() + " items");
        }
        while (selectedIterator.hasNext()) {
            selectedKey = selectedIterator.next();
            // safely remove from set while looping
            selectedIterator.remove();
            req = (TCPBaseRequestContext) selectedKey.attachment();
            vci = req.getTCPConnLink().getVirtualConnection();
            completeOperation = true;

            // looking at the vci is messy here, but we're doing the try, catch
            // to save synchronization logic. vci could be null if connection
            // is closing before we can asked to request permission to finish
            // the read.
            if (vci == null) {
                completeOperation = false;
            } else {
                // only check if operation was an async read/write request
                if (vci.isInputStateTrackingOperational() && !req.blockedThread) {
                    completeOperation = false;
                    if (req.isRequestTypeRead()) {
                        if (vci.requestPermissionToFinishRead()) {
                            completeOperation = true;
                        }
                    } else {
                        if (vci.requestPermissionToFinishWrite()) {
                            completeOperation = true;
                        }
                    }
                }
            }

            if (completeOperation) {
                // try to dispatch request. if it fails, just leave key alone,
                // and it should get selected and tried again the next time through
                // the selector.
                if (wqm.dispatch(req, null)) {
                    // Dispatch worked, so set key's interest set to empty, so it isn't
                    // re-selected
                    // until the user asks us to do more work.
                    try {
                        selectedKey.interestOps(0);
                    } catch (CancelledKeyException cke) {
                        // ignore, since we already got the key and the data
                    }
                }
            } else {
                // permission denied, assume close has been processed on this VC
                // therefore disregard this read.
                if (TraceComponent.isAnyTracingEnabled() && tc.isEventEnabled()) {
                    Tr.event(this, tc, "IO cancelled on closed key " + selectedKey);
                }
                try {
                    selectedKey.interestOps(0);
                } catch (CancelledKeyException cke) {
                    // ignore, since the vc is closed/ing
                }
            }
        }

        return false;
    }
387612
protected void sendRequests() {
        if ( ! requestUnderway ) {
            requestUnderway = true;
            delayed( new Runnable() {
                @Override
                public void run() {
                    synchronized (requests) {
                        Object req[];
                        if ( openFutureRequests.get() > 0 && requests.size() == 0 ) {
                            req = new Object[] { "SP", lastSeenSeq };
                        } else {
                            req = new Object[requests.size() + 1];
                            for (int i = 0; i < requests.size(); i++) {
                                req[i] = requests.get(i);
                            }
                            req[req.length - 1] = lastSeenSeq;
                            requests.clear();
                        }

                        sendCallArray(req).then(new Callback<Integer>() {
                            @Override
                            public void receive(Integer result, Object error) {
                                synchronized (requests ) {
                                    requestUnderway = false;
                                    if ( requests.size() > 0 || (result != null && result > 0 && openFutureRequests.get() > 0 ) ) {
                                        myExec.execute(new Runnable() {
                                            @Override
                                            public void run() {
                                            sendRequests();
                                            }
                                        });
                                    }
                                }
                            }
                        });
                    }
                }
            }, 1);
        }
    }
1066341
public Task<Void> execute(@Nonnull final AwsRequest request) {
    return dispatcher.dispatchTask(new Callable<Void>() {
      @Override
      public Void call() {
        proxy.execute(request);
        return null;
      }
    });
  }
357358
protected String doRequest(HttpRequestBase request) throws IOException {
        for (Map.Entry<Header, String> header : headers.entrySet()) {
            request.setHeader("X-RallyIntegration" + header.getKey().name(), header.getValue());
        }

        return this.executeRequest(request);
    }
268442
@Override
    public Object invoke(Object conn, Object requestData)
        throws AdapterException, ConnectionException
    {
        try {
            Object result;

            if (jmsSenderReceiver != null) {

                final String responseQueueName = this.getAttributeValueSmart(RESPONSE_QUEUE_NAME);
                final String requestDataForMessage = (String) requestData;
                final Queue replyQueue;
                final String correlationId = getCorrelationId();

                boolean replyIsTemporaryQueue = false;
                if (responseQueueName != null && responseQueueName.length() > 0) {
                    replyQueue = (Queue) ApplicationContext.getNamingProvider().lookup(null,
                            responseQueueName, Queue.class);
                    // msg.setJMSReplyTo(replyQueue);
                }
                else if (this.isSynchronous()) {
                    replyQueue = qSession.createTemporaryQueue();
                    // msg.setJMSReplyTo(replyQueue) ;
                    replyIsTemporaryQueue = true;
                }
                else
                    replyQueue = null;

                jmsSenderReceiver.send(getQueueName(), new MessageCreator() {

                    @Override
                    public Message createMessage(Session session) throws JMSException {
                        Message message = session.createTextMessage(requestDataForMessage);
                        if (correlationId != null)
                            message.setJMSCorrelationID(correlationId);
                        if (replyQueue != null) {
                            message.setJMSReplyTo(replyQueue);
                        }
                        return message;
                    }

                });
                if (this.isSynchronous()) {
                    Message message = null;
                    jmsSenderReceiver.setReceiveTimeout(getTimeoutForResponse() * 1000);
                    if (replyIsTemporaryQueue) {
                        message = jmsSenderReceiver.receive(replyQueue);
                    }
                    else {
                        String messageSelector = "JMSCorrelationID = '" + correlationId + "'";
                        message = jmsSenderReceiver.receiveSelected(replyQueue, messageSelector);
                    }
                    if (message == null) {
                        throw new ActivityException(
                                "Synchronous JMS call times out while waiting for response");
                    }
                    else {
                        result = ((TextMessage)message).getText();
                    }
                }
                else
                    result = null;
            }
            else {
                QueueSession qSession = (QueueSession)conn;
                Queue replyQueue;
                boolean replyIsTemporaryQueue = false;
                QueueSender qSender = qSession.createSender(queue);
                TextMessage msg = qSession.createTextMessage((String)requestData);
                String responseQueueName = this.getAttributeValueSmart(RESPONSE_QUEUE_NAME);
                if (responseQueueName!=null && responseQueueName.length()>0) {
                    replyQueue = (Queue)ApplicationContext.getNamingProvider().lookup(null,responseQueueName,Queue.class);
                    msg.setJMSReplyTo(replyQueue);
                } else if (this.isSynchronous()) {
                    replyQueue = qSession.createTemporaryQueue();
                    msg.setJMSReplyTo(replyQueue);
                    replyIsTemporaryQueue = true;
                } else replyQueue = null;
                String correlationId = getCorrelationId();
                if (correlationId!=null) msg.setJMSCorrelationID(correlationId);
                qSender.send(msg);
                if (this.isSynchronous()) {
                    MessageConsumer consumer;
                    if (replyIsTemporaryQueue) {
                        consumer = qSession.createConsumer(replyQueue);
                    } else {
                        String messageSelector = "JMSCorrelationID = '" + correlationId + "'";
                        consumer = qSession.createConsumer(replyQueue, messageSelector);
                    }
                    msg = (TextMessage)consumer.receive(getTimeoutForResponse()*1000);
                    if (msg==null) {
                        throw new ActivityException("Synchronous JMS call times out while waiting for response");
                    } else {
                        result = msg.getText();
                    }
                } else result = null;
            }
            return result;
        } catch (Exception e) {
//            logger.severeException("Exception in JmsAdapter.invoke()" , e);
            throw new AdapterException(-1, "Exception in invoking JmsAdapter" , e);
        }
    }
177903
protected String executeRequest(HttpRequestBase request) throws IOException {
        HttpResponse response = client.execute(request);
        HttpEntity entity = response.getEntity();
        if (response.getStatusLine().getStatusCode() == 200) {
            return EntityUtils.toString(entity, "utf-8");
        } else {
            EntityUtils.consumeQuietly(entity);
            throw new IOException(response.getStatusLine().toString());
        }
    }
284878
protected Response executeRequest(Request request)
    {
        try
        {
            com.squareup.okhttp.Request httpRequest = buildHttpRequest(request);

            if(logger.isInfoEnabled())
                logger.info("Sending request: {} {}",httpRequest.method(),httpRequest.urlString());

            if(logger.isDebugEnabled() && request.getRequestMethod().isBodyRequest())
            {
                Buffer buffer = new Buffer();
                httpRequest.body().writeTo(buffer);
                if(maxLoggedBodySize == -1 || buffer.size() <= maxLoggedBodySize )
                    logger.debug("Request body: {}", buffer.readUtf8());
                else
                    logger.debug("Request body not captured: too large. ");
            }

            if(logger.isTraceEnabled())
                logger.trace("Request headers: {}",httpRequest.headers().toString());

            Response response = client.newCall(httpRequest).execute();

            if(response.code() == HttpURLConnection.HTTP_UNAUTHORIZED && authorizationFactory != null
                    && authorizationFactory.retryOnAuthenticationError())
            {
                if(authorizationFactory instanceof ResettableAuthorizationFactory)
                    ((ResettableAuthorizationFactory) authorizationFactory).reset();

                response = client.newCall(httpRequest).execute();
            }

            logger.info("Response code: {}",response.code());

            if(logger.isTraceEnabled())
                logger.trace("Response headers: {}",response.headers().toString());

            if(logger.isDebugEnabled())
            {
                ByteArrayOutputStream copy = new ByteArrayOutputStream();
                copy(response.body().byteStream(),copy);
                response = response.newBuilder().body(ResponseBody.create(response.body().contentType(),copy.toByteArray())).build();

                if(maxLoggedBodySize == -1 || copy.size() <= maxLoggedBodySize)
                    logger.debug("Response body: {}",copy.toString());
                else
                    logger.debug("Response body not captured: too large.");
            }
            if (response.code() >= HttpURLConnection.HTTP_BAD_REQUEST)
            {
                throw readException(response);
            }

            return response;
        }
        catch (IOException e)
        {
            throw new ClientConnectionException("Error calling service.",e);
        }

    }
416408
@Override
    public void perform() throws PortalException {
        Element plfNode = HandlerUtils.getPLFNode(ilfNode, person, false, false);

        if (plfNode == null) return;

        changeRestriction(Constants.ATT_MOVE_ALLOWED, plfNode, moveAllowed);
        changeRestriction(Constants.ATT_MOVE_ALLOWED, ilfNode, moveAllowed);
        changeRestriction(Constants.ATT_DELETE_ALLOWED, plfNode, deleteAllowed);
        changeRestriction(Constants.ATT_DELETE_ALLOWED, ilfNode, deleteAllowed);
        changeRestriction(Constants.ATT_EDIT_ALLOWED, plfNode, editAllowed);
        changeRestriction(Constants.ATT_EDIT_ALLOWED, ilfNode, editAllowed);

        if (plfNode.getAttribute(Constants.ATT_CHANNEL_ID).equals("")) {
            // if channel id is empty then this is not a channel.
            // childAllowed is always true for channel ad-hoc parameters.
            changeRestriction(Constants.ATT_ADD_CHILD_ALLOWED, plfNode, addChildAllowed);
            changeRestriction(Constants.ATT_ADD_CHILD_ALLOWED, ilfNode, addChildAllowed);
        }
    }
670254
@Override
	public void handleRequest(final Request request) {
		super.handleRequest(request);

		WComponent visibleDialog = getVisible();

		if (visibleDialog != null) {
			visibleDialog.serviceRequest(request);
		}
	}
877054
@Override
  public void requestWake()
  {
    try {
      _state = _state.toWake();

      requestLoop();
    } catch (Exception e) {
      log.log(Level.WARNING, e.toString(), e);
    }

    /*
    if (_stateRef.get().toWake(_stateRef)) {
      offer(getConnectionTask());
    }
    */
  }
222561
@Override
    protected String doRequest(HttpRequestBase request) throws IOException {
        request.setHeader(API_KEY_HEADER, this.apiKey);
        return super.doRequest(request);
    }
412870
public <T> T send(Request<T> request) {

		if (request == null) {
			throw new CommunicationErrorException("Request cannot be null.");
		}
		RequestUtil.validate(request);

		@SuppressWarnings("unchecked")
		T response = (T) dispatchByMethod(request);

		return response;
	}
331212
public final void request(Result<I> result)
  {
    I instance = _instance;
    
    if (instance != null && _lifecycle.isActive() && ! isModified()) {
      result.ok(instance);
    }
    else if (_lifecycle.isDestroyed()) {
      result.ok(null);
    }
    else {
      _strategy.request(this, result);
    }
  }
534549
@Override
  public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    try {
      if (exceptionRaised.get()) {
        return;
      }

      if (!(msg instanceof HttpRequest)) {
        // If there is no methodInfo, it means the request was already rejected.
        // What we received here is just residue of the request, which can be ignored.
        if (methodInfo != null) {
          ReferenceCountUtil.retain(msg);
          ctx.fireChannelRead(msg);
        }
        return;
      }
      HttpRequest request = (HttpRequest) msg;
      BasicHttpResponder responder = new BasicHttpResponder(ctx.channel(), sslEnabled);

      // Reset the methodInfo for the incoming request error handling
      methodInfo = null;
      methodInfo = prepareHandleMethod(request, responder, ctx);

      if (methodInfo != null) {
        ReferenceCountUtil.retain(msg);
        ctx.fireChannelRead(msg);
      } else {
        if (!responder.isResponded()) {
          // If not yet responded, just respond with a not found and close the connection
          HttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.NOT_FOUND);
          HttpUtil.setContentLength(response, 0);
          HttpUtil.setKeepAlive(response, false);
          ctx.channel().writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
        } else {
          // If already responded, just close the connection
          ctx.channel().close();
        }
      }
    } finally {
      ReferenceCountUtil.release(msg);
    }
  }
1154328
protected <T> T performCustomRequest(String url, Object requestPayLoad, Class<T> returnType, Map<String, String> uriVariables,
                                       HttpMethod httpMethod, HttpHeaders headers) {

        if (headers == null) {
            headers = new HttpHeaders();
        }

        HttpEntity<Object> requestEntity = new HttpEntity<Object>(requestPayLoad, headers);

        int tryNumber = 1;
        while(tryNumber <= API_RETRY) {
            try {
                ResponseEntity<T> responseEntity = restTemplate.exchange(url, httpMethod, requestEntity, returnType, uriVariables);
                return responseEntity.getBody();
            } catch (HttpStatusCodeException error) {
                boolean isTooManyRequestsError = handleHttpStatusCodeError(uriVariables, tryNumber, error);
                if (isTooManyRequestsError) {
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        log.error("Error in performCustomRequest", e);
                    }
                } else {
                    tryNumber++;
                }
            } catch (RuntimeException e) {
                handleApiError(tryNumber, e);
                tryNumber++;
            }
        }

        throw new RestApiException("Error posting " + returnType.getSimpleName() + " url variables " + uriVariables.toString());
    }
816910
@Override
	public void channelRead0(ChannelHandlerContext ctx, RoutedRequest routedRequest) throws Exception {
		String requestPath = routedRequest.getPath();

		respondWithFile(ctx, routedRequest.getRequest(), requestPath);
	}
1037429
private void executeGetOperation(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ClassNotFoundException {
        if (request.getContentLength() > 0) {
            response.setStatus(HttpServletResponse.SC_NO_CONTENT);
            ObjectInputStream input = new ObjectInputStream(new BufferedInputStream(request.getInputStream()));
            CommandPayload paylod = (CommandPayload) input.readObject();
            events.put(currentCall, paylod);
        } else {
            if (events.containsKey(currentCall) && !events.get(currentCall).isExecuted()) {
                response.setStatus(HttpServletResponse.SC_OK);
                ObjectOutputStream output = new ObjectOutputStream(response.getOutputStream());
                output.writeObject(events.remove(currentCall));
                output.flush();
                output.close();
            } else {
                response.setStatus(HttpServletResponse.SC_NO_CONTENT);
            }
        }
    }