Deal with streams attached to an operation response from a proxied domain process.

@param context the context of the operation
@param responseNode the DMR response from the proxied process
@param streams the streams associated with the response
173644
public static void handleDomainOperationResponseStreams(final OperationContext context,
                                                            final ModelNode responseNode,
                                                            final List<OperationResponse.StreamEntry> streams) {

        if (responseNode.hasDefined(RESPONSE_HEADERS)) {
            ModelNode responseHeaders = responseNode.get(RESPONSE_HEADERS);
            // Strip out any stream header as the header created by this process is what counts
            responseHeaders.remove(ATTACHED_STREAMS);
            if (responseHeaders.asInt() == 0) {
                responseNode.remove(RESPONSE_HEADERS);
            }
        }

        for (OperationResponse.StreamEntry streamEntry : streams) {
            context.attachResultStream(streamEntry.getUUID(), streamEntry.getMimeType(), streamEntry.getStream());
        }
    }
1243046
private void handleResponse(ByteBuf response, ChannelHandlerContext context) {
    NettyConnection connection = getConnection(context.channel());
    if (connection != null) {
      connection.handleResponse(response);
    }
  }
125351
@Override
	public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) throws IOException {
		Object response = responseContext.getEntity();
		if (response == null) {
			return;
		}
		
		// only modify responses which contain a single or a list of Katharsis resources
		if (isResourceResponse(response)) {
			KatharsisBoot boot = feature.getBoot();
			ResourceRegistry resourceRegistry = boot.getResourceRegistry();
			DocumentMapper documentMapper = boot.getDocumentMapper();
			
			ServiceUrlProvider serviceUrlProvider = resourceRegistry.getServiceUrlProvider();
			try {
				UriInfo uriInfo = requestContext.getUriInfo();
				if (serviceUrlProvider instanceof UriInfoServiceUrlProvider) {
					((UriInfoServiceUrlProvider) serviceUrlProvider).onRequestStarted(uriInfo);
				}

				JsonApiResponse jsonApiResponse = new JsonApiResponse();
				jsonApiResponse.setEntity(response);
				// use the Katharsis document mapper to create a JSON API response
				responseContext.setEntity(documentMapper.toDocument(jsonApiResponse, null));
				responseContext.getHeaders().put("Content-Type", Arrays.asList((Object)JsonApiMediaType.APPLICATION_JSON_API));
				
			}
			finally {
				if (serviceUrlProvider instanceof UriInfoServiceUrlProvider) {
					((UriInfoServiceUrlProvider) serviceUrlProvider).onRequestFinished();
				}
			}
		}
	}
79295
public void service(HttpServletRequest req, HttpServletResponse res) 
        throws ServletException, IOException
    {
    	if ((proxyURLPrefix == null) || (proxyURLPrefix.length() == 0))
    	{	// No proxy specified
        	super.service(req, res);
    		return;
    	}
		ServletOutputStream streamOut = res.getOutputStream();
    	try {
    		String proxyURLString = getProxyURLString(req);
    		HttpRequestBase httpRequest = getHttpRequest(req, proxyURLString);
    		addHeaders(req, httpRequest);
    		this.getDataFromClient(httpRequest, streamOut);
		} catch (Exception e) {
			displayErrorInHtml(streamOut, e);
		}
    }
416242
JsonNode requestResponse(final JsonNode request) {
        try {

            // write request
            String str = request.toString();
            this.stdin.write(str + "\n");
            this.stdin.flush();

            // read response
            JsonNode resp = readNextResponse();

            // throw if this is an error response
            if (resp.has("error")) {
                return processErrorResponse(resp);
            }

            // process synchronous callbacks (which 'interrupt' the response flow).
            if (resp.has("callback")) {
                return processCallbackResponse(resp);
            }

            // null "ok" means undefined result (or void).
            return resp.get("ok");

        } catch (IOException e) {
            throw new JsiiException("Unable to send request to jsii-runtime: " + e.toString(), e);
        }
    }
1318691
public CompletableFuture<StreamCutRecord> generateStreamCut(final String scope, final String stream, final StreamCutRecord previous,
                                                                final OperationContext contextOpt, String delegationToken) {
        final OperationContext context = contextOpt == null ? streamMetadataStore.createContext(scope, stream) : contextOpt;

        return streamMetadataStore.getActiveSegments(scope, stream, context, executor)
                .thenCompose(activeSegments -> Futures.allOfWithResults(activeSegments
                        .stream()
                        .parallel()
                        .collect(Collectors.toMap(x -> x, x -> getSegmentOffset(scope, stream, x.segmentId(), delegationToken)))))
                .thenCompose(map -> {
                    final long generationTime = System.currentTimeMillis();
                    ImmutableMap.Builder<Long, Long> builder = ImmutableMap.builder();
                    map.forEach((key, value) -> builder.put(key.segmentId(), value));
                    ImmutableMap<Long, Long> streamCutMap = builder.build();
                    return streamMetadataStore.getSizeTillStreamCut(scope, stream, streamCutMap, Optional.ofNullable(previous), context, executor)
                                              .thenApply(sizeTill -> new StreamCutRecord(generationTime, sizeTill, streamCutMap));
                });
    }
317260
private static ModelNode responseNodeOnly(OperationResponse or) {
        ModelNode result = or.getResponseNode();
        try {
            or.close();
        } catch (IOException e) {
            ControllerClientLogger.ROOT_LOGGER.debugf(e, "Caught exception closing %s whose associated streams, " +
                    "if any, were not wanted", or);
        }
        return result;
    }
697630
@Override
    public void record( final Context context,
                        final InputStream inputStream,
                        final long length,
                        final String encoding,
                        final Node outputNode ) throws Exception {
            JavaMetadata javaMetadata = JavaMetadata.instance(inputStream, length, encoding);
            record(context, outputNode, javaMetadata);
    }
765064
@Override
    public Object render(Map<String, Object> context, LNode... nodes) {

        String id = super.asString(nodes[0].render(context));

        LNode block = nodes[1];

        context.put(id, block.render(context));

        return null;
    }
950237
public void processResponse(ResponseEvent responseEvent) {
		final ResponseEventExt responseEventExt = (ResponseEventExt) responseEvent;
		final Response response = responseEventExt.getResponse();

		if(logger.isDebugEnabled()) {
			logger.debug("Response " + response.toString());
		}

		final CSeqHeader cSeqHeader = (CSeqHeader)response.getHeader(CSeqHeader.NAME);
		//if this is a response to a cancel, the response is dropped
		if(Request.CANCEL.equalsIgnoreCase(cSeqHeader.getMethod())) {
			if(logger.isDebugEnabled()) {
				logger.debug("the response is dropped accordingly to JSR 289 " +
						"since this a response to a CANCEL");
			}
			return;
		}
		// self routing makes the application data cloned, so we make sure to nullify it
		((MessageExt)response).setApplicationData(null);

		updateResponseStatistics(response, true);
		ClientTransaction clientTransaction = responseEventExt.getClientTransaction();
		final Dialog dialog = responseEventExt.getDialog();
		final boolean isForkedResponse = responseEventExt.isForkedResponse();
		final boolean isRetransmission = responseEventExt.isRetransmission();
		final ClientTransactionExt originalTransaction = responseEventExt.getOriginalTransaction();
		if(logger.isDebugEnabled()) {
			logger.debug("is Forked Response " + isForkedResponse);
			logger.debug("is Retransmission " + isRetransmission);
			logger.debug("Client Transaction " + clientTransaction);
			logger.debug("Original Transaction " + originalTransaction);
			logger.debug("Dialog " + dialog);
			if(dialog != null) {
				logger.debug("Dialog State " + dialog.getState());
			}
		}
		// Issue 1468 : Handling forking
		if(isForkedResponse && originalTransaction != null && !responseEventExt.isRetransmission()) {
			final Dialog defaultDialog = originalTransaction.getDefaultDialog();
			final Dialog orginalTransactionDialog = originalTransaction.getDialog();
			if(logger.isDebugEnabled()) {
				logger.debug("Original Transaction Dialog " + orginalTransactionDialog);
				logger.debug("Original Transaction Default Dialog " + defaultDialog);
			}
			clientTransaction = originalTransaction;
		}

		// Transate the response to SipServletResponse
		final SipServletResponseImpl sipServletResponse = (SipServletResponseImpl) sipFactoryImpl.getMobicentsSipServletMessageFactory().createSipServletResponse(
				response,
				clientTransaction,
				null,
				dialog,
				true,
				isRetransmission);
		try {
			messageDispatcherFactory.getResponseDispatcher(sipServletResponse, this).
				dispatchMessage(((SipProvider)responseEvent.getSource()), sipServletResponse);
		} catch (Throwable e) {
			logger.error("An unexpected exception happened while routing the response " +  sipServletResponse, e);
			return;
		}
	}
309880
@SuppressWarnings("unchecked")
  private void handleResponseSuccess(long requestId, Object response) {
    ContextualFuture future = responseFutures.remove(requestId);
    if (future != null) {
      future.context.executor().execute(() -> future.complete(response));
    }
  }
230868
Stream<TreeNode> getFiltered(Stream<TreeNode> delegateNodes)
    {
        return delegateNodes
            .filter(delegateNode -> filter.acceptNode(this, delegateNode))
            .map(delegateNode -> delegateToThis.get(delegateNode))
            .filter(filteredNode -> filteredNode != null);
    }
1026227
void processNodeCommand(final HttpServerExchange exchange, final RequestData requestData, final MCMPAction action) throws IOException {
        final String jvmRoute = requestData.getFirst(JVMROUTE);
        if (jvmRoute == null) {
            processError(TYPESYNTAX, SMISFLD, exchange);
            return;
        }
        if (processNodeCommand(jvmRoute, action)) {
            processOK(exchange);
        } else {
            processError(MCMPErrorCode.CANT_UPDATE_NODE, exchange);
        }
    }
423723
@Override
   void processModelNode(OperationContext context, ModelNode counter,
         CounterConfiguration.Builder builder) throws OperationFailedException {
      super.processModelNode(context, counter, builder);

      ModelNode upperBoundModel = counter.get(ModelKeys.UPPER_BOUND);
      ModelNode lowerBoundModel = counter.get(ModelKeys.LOWER_BOUND);
      if (lowerBoundModel.isDefined()) {
          Long lowerBound = StrongCounterResource.LOWER_BOUND.resolveModelAttribute(context, counter).asLong();
          builder.lowerBound(lowerBound);
      }
      if (upperBoundModel.isDefined()) {
          Long upperBound = StrongCounterResource.UPPER_BOUND.resolveModelAttribute(context, counter).asLong();
          builder.upperBound(upperBound);
      }
   }
753550
public void copyToResponse(HttpServletResponse response, byte[] alteredResponse) throws IOException {
        // character encoding
        if(this.characterEncoding != null) {
            response.setCharacterEncoding(this.characterEncoding);
        }

        // charset
        if(this.charset != null) {
            response.setCharacterEncoding(charset);
        }

        // content type
        if(this.contentType != null) {
            response.setContentType(this.contentType);
        }

        // set the status
        if(this.statusCode > 0) {
            response.setStatus(this.statusCode);
        }

        // set the locale
        if(this.locale != null) {
            response.setLocale(this.locale);
        }

        // copy and add all cookies
        if(this.cookies != null) {
            for(Cookie cookie : this.cookies) {
                response.addCookie(cookie);
            }
        }

        // copy the byte array stream and also set its length
        final OutputStream finalOut = response.getOutputStream();
        if(alteredResponse == null) {
            int length = this.outputStream.getLength();
            response.setContentLength(length);

            // write the entire byte chunk
            this.outputStream.getByteArrayOutputStream().writeTo(finalOut);
        } else {
            response.setContentLength(alteredResponse.length);
            finalOut.write(alteredResponse);
        }

        finalOut.flush();
    }
1171718
public static void asyncUnimplementedUnaryCall(
      MethodDescriptor<?, ?> methodDescriptor, StreamObserver<?> responseObserver) {
    checkNotNull(methodDescriptor, "methodDescriptor");
    checkNotNull(responseObserver, "responseObserver");
    responseObserver.onError(Status.UNIMPLEMENTED
        .withDescription(String.format("Method %s is unimplemented",
            methodDescriptor.getFullMethodName()))
        .asRuntimeException());
  }
703752
void performStreamingRepair()
    {
        InetAddress local = FBUtilities.getBroadcastAddress();
        // We can take anyone of the node as source or destination, however if one is localhost, we put at source to avoid a forwarding
        InetAddress src = r2.endpoint.equals(local) ? r2.endpoint : r1.endpoint;
        InetAddress dst = r2.endpoint.equals(local) ? r1.endpoint : r2.endpoint;

        SyncRequest request = new SyncRequest(desc, local, src, dst, differences);
        StreamingRepairTask task = new StreamingRepairTask(desc, request);
        task.run();
    }