Finalize saml response.

@param request      the request
@param response     the response
@param serviceId    the service id
@param samlResponse the saml response
@throws Exception the exception
510742
protected void finalizeSamlResponse(final HttpServletRequest request, final HttpServletResponse response,
                                        final String serviceId, final Response samlResponse) throws Exception {
        if (request != null && response != null) {
            LOGGER.debug("Starting to encode SAML response for service [{}]", serviceId);
            this.samlResponseBuilder.encodeSamlResponse(samlResponse, request, response);
        }
    }
746109
@SneakyThrows
    protected SAMLObject encryptAssertion(final Assertion assertion,
                                          final HttpServletRequest request,
                                          final HttpServletResponse response,
                                          final SamlRegisteredService service,
                                          final SamlRegisteredServiceServiceProviderMetadataFacade adaptor) throws SamlException {

        if (service.isEncryptAssertions()) {
            LOGGER.debug("SAML service [{}] requires assertions to be encrypted", adaptor.getEntityId());
            return samlResponseBuilderConfigurationContext.getSamlObjectEncrypter().encode(assertion, service, adaptor);
        }
        LOGGER.debug("SAML registered service [{}] does not require assertions to be encrypted", adaptor.getEntityId());
        return assertion;

    }
253191
public synchronized void create( HttpServletRequest request, HttpServletResponse response, ServletContext servletContext )
        throws Exception
    {
        reinitialize( request, response, servletContext );
        JavaControlUtils.initJavaControls( request, response, servletContext, this );
        onCreate();
    }
269731
protected void service(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		try {
			jawrController.handleRequest(request, response);
		} catch (Exception e) {
			if (logger.isDebugEnabled()) {
				logger.debug("Error in JawrSpringController", e);
			}
			throw new ServletException(e);
		}
	}
783733
public void encodeSamlResponse(final Response samlResponse, final HttpServletRequest request, final HttpServletResponse response) throws Exception {
        this.samlObjectBuilder.encodeSamlResponse(response, request, samlResponse);
    }
495586
public void service(ServletRequest request, ServletResponse response)
        throws IOException, ServletException
    {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse res = (HttpServletResponse) response;

        if (!req.getMethod().equals("POST")) {
            res.setStatus(500); // , "Hessian Requires POST");
            PrintWriter out = res.getWriter();

            res.setContentType("text/html");
            out.println("<h1>Hessian Requires POST</h1>");

            return;
        }

        String serviceId = req.getPathInfo();
        String objectId = req.getParameter("id");
        if (objectId == null)
            objectId = req.getParameter("ejbid");

        ServiceContext.begin(req, res, serviceId, objectId);

        try {
            InputStream is = request.getInputStream();
            OutputStream os = response.getOutputStream();

            response.setContentType("x-application/hessian");

            SerializerFactory serializerFactory = getSerializerFactory();

            invoke(is, os, objectId, serializerFactory);
        } catch (RuntimeException e) {
            throw e;
        } catch (ServletException e) {
            throw e;
        } catch (Throwable e) {
            throw new ServletException(e);
        } finally {
            ServiceContext.end();
        }
    }
716809
protected void handleSloProfileRequest(final HttpServletResponse response,
                                           final HttpServletRequest request,
                                           final BaseHttpServletRequestXMLMessageDecoder decoder) throws Exception {
        val logout = getSamlProfileHandlerConfigurationContext().getCasProperties().getAuthn().getSamlIdp().getLogout();
        if (logout.isSingleLogoutCallbacksDisabled()) {
            LOGGER.info("Processing SAML2 IdP SLO requests is disabled");
            return;
        }

        val pair = getSamlProfileHandlerConfigurationContext().getSamlHttpRequestExtractor().extract(request, decoder, LogoutRequest.class);
        val logoutRequest = (LogoutRequest) pair.getKey();
        val ctx = pair.getValue();

        if (logout.isForceSignedLogoutRequests() && !SAMLBindingSupport.isMessageSigned(ctx)) {
            throw new SAMLException("Logout request is not signed but should be.");
        }

        if (SAMLBindingSupport.isMessageSigned(ctx)) {
            val entityId = SamlIdPUtils.getIssuerFromSamlObject(logoutRequest);
            LOGGER.trace("SAML logout request from entity id [{}] is signed", entityId);
            val registeredService = getSamlProfileHandlerConfigurationContext().getServicesManager().findServiceBy(entityId, SamlRegisteredService.class);
            LOGGER.trace("SAML registered service tied to [{}] is [{}]", entityId, registeredService);
            val facade = SamlRegisteredServiceServiceProviderMetadataFacade.get(
                getSamlProfileHandlerConfigurationContext().getSamlRegisteredServiceCachingMetadataResolver(), registeredService, entityId).get();
            LOGGER.trace("Verifying signature on the SAML logout request for [{}]", entityId);
            getSamlProfileHandlerConfigurationContext().getSamlObjectSignatureValidator()
                .verifySamlProfileRequestIfNeeded(logoutRequest, facade, request, ctx);
        }
        SamlUtils.logSamlObject(getSamlProfileHandlerConfigurationContext().getOpenSamlConfigBean(), logoutRequest);
        response.sendRedirect(getSamlProfileHandlerConfigurationContext().getCasProperties().getServer().getLogoutUrl());
    }
1034107
@PostMapping(path = SamlProtocolConstants.ENDPOINT_SAML_VALIDATE)
    @Override
    public ModelAndView handleRequestInternal(final HttpServletRequest request,
                                              final HttpServletResponse response) throws Exception {
        return super.handleRequestInternal(request, response);
    }
1069592
private void handleResponseFailure(long requestId, Throwable t) {
    ContextualFuture future = responseFutures.remove(requestId);
    if (future != null) {
      future.context.executor().execute(() -> future.completeExceptionally(t));
    }
  }
570370
@PostMapping(path = SamlIdPConstants.ENDPOINT_SAML2_SOAP_ATTRIBUTE_QUERY)
    protected void handlePostRequest(final HttpServletResponse response,
                                     final HttpServletRequest request) {

        val ctx = decodeSoapRequest(request);
        val query = (AttributeQuery) ctx.getMessage();
        try {
            val issuer = query.getIssuer().getValue();
            val service = verifySamlRegisteredService(issuer);
            val adaptor = getSamlMetadataFacadeFor(service, query);
            if (adaptor.isEmpty()) {
                throw new UnauthorizedServiceException(UnauthorizedServiceException.CODE_UNAUTHZ_SERVICE, "Cannot find metadata linked to " + issuer);
            }

            val facade = adaptor.get();
            verifyAuthenticationContextSignature(ctx, request, query, facade);

            val attrs = new LinkedHashMap<String, Object>();
            if (query.getAttributes().isEmpty()) {
                val id = getSamlProfileHandlerConfigurationContext().getSamlAttributeQueryTicketFactory().createTicketIdFor(query.getSubject().getNameID().getValue());
                val ticket = getSamlProfileHandlerConfigurationContext().getTicketRegistry().getTicket(id, SamlAttributeQueryTicket.class);

                val authentication = ticket.getTicketGrantingTicket().getAuthentication();
                val principal = authentication.getPrincipal();

                val authnAttrs = authentication.getAttributes();
                val principalAttrs = principal.getAttributes();

                query.getAttributes().forEach(a -> {
                    if (authnAttrs.containsKey(a.getName())) {
                        attrs.put(a.getName(), authnAttrs.get(a.getName()));
                    } else if (principalAttrs.containsKey(a.getName())) {
                        attrs.put(a.getName(), principalAttrs.get(a.getName()));
                    }
                });
            }

            val casAssertion = buildCasAssertion(issuer, service, attrs);
            getSamlProfileHandlerConfigurationContext().getResponseBuilder().build(query, request, response, casAssertion, service, facade, SAMLConstants.SAML2_SOAP11_BINDING_URI, ctx);
        } catch (final Exception e) {
            LOGGER.error(e.getMessage(), e);
            request.setAttribute(SamlIdPConstants.REQUEST_ATTRIBUTE_ERROR, e.getMessage());
            getSamlProfileHandlerConfigurationContext().getSamlFaultResponseBuilder().build(query, request, response,
                null, null, null, SAMLConstants.SAML2_SOAP11_BINDING_URI, ctx);
        }
    }
78441
public final void service(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
        _jspService(request, response);
    }
391263
@SuppressWarnings("unchecked")
    protected <R> R service(ServiceRequest<R> request) throws WssServiceException {
        R result;
        String response = "";
        try {
            HttpRequestBase httpRequest = createHttpRequest(request);
            RequestConfig requestConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD).build();
            httpRequest.setConfig(requestConfig);

            logger.trace("Calling White Source service: " + request);
            response = httpClient.execute(httpRequest, new BasicResponseHandler());

            String data = extractResultData(response);
            logger.trace("Result data is: " + data);

            switch (request.type()) {
                case UPDATE:
                    result = (R) gson.fromJson(data, UpdateInventoryResult.class);
                    break;
                case CHECK_POLICIES:
                    result = (R) gson.fromJson(data, CheckPoliciesResult.class);
                    break;
                case CHECK_POLICY_COMPLIANCE:
                    result = (R) gson.fromJson(data, CheckPolicyComplianceResult.class);
                    break;
                case CHECK_VULNERABILITIES:
                    result = (R) gson.fromJson(data, CheckVulnerabilitiesResult.class);
                    break;
                case GET_DEPENDENCY_DATA:
                    result = (R) gson.fromJson(data, GetDependencyDataResult.class);
                    break;
                case SUMMARY_SCAN:
                    result = (R) gson.fromJson(data, SummaryScanResult.class);
                    break;
                case GET_CONFIGURATION:
                    result = (R) gson.fromJson(data, ConfigurationResult.class);
                    break;
                default:
                    throw new IllegalStateException("Unsupported request type.");
            }
        } catch (JsonSyntaxException e) {
            throw new WssServiceException("JsonSyntax exception. Response data is:  " + response + e.getMessage(), e);
        } catch (IOException e) {
            throw new WssServiceException("Unexpected error. Response data is: " + response + e.getMessage(), e);
        }

        return result;
    }
275999
@GetMapping(produces = MediaType.APPLICATION_XML_VALUE)
    @ResponseBody
    public ResponseEntity<Object> produce(final HttpServletRequest request, final HttpServletResponse response) {
        val username = request.getParameter("username");
        val password = request.getParameter("password");
        val entityId = request.getParameter(SamlProtocolConstants.PARAMETER_ENTITY_ID);

        try {
            val selectedService = this.serviceFactory.createService(entityId);
            val registeredService = this.servicesManager.findServiceBy(selectedService, SamlRegisteredService.class);
            RegisteredServiceAccessStrategyUtils.ensureServiceAccessIsAllowed(registeredService);

            val assertion = getAssertion(username, password, entityId);
            val authnRequest = new AuthnRequestBuilder().buildObject();
            authnRequest.setIssuer(saml20ObjectBuilder.newIssuer(entityId));

            val adaptorResult = SamlRegisteredServiceServiceProviderMetadataFacade.get(defaultSamlRegisteredServiceCachingMetadataResolver,
                registeredService, entityId);
            if (adaptorResult.isPresent()) {
                val adaptor = adaptorResult.get();
                val messageContext = new MessageContext<>();
                val scratch = messageContext.getSubcontext(ScratchContext.class, true);
                scratch.getMap().put(SamlProtocolConstants.PARAMETER_ENCODE_RESPONSE, Boolean.FALSE);

                val object = this.responseBuilder.build(authnRequest, request, response, assertion,
                    registeredService, adaptor, SAMLConstants.SAML2_POST_BINDING_URI, messageContext);
                val encoded = SamlUtils.transformSamlObject(saml20ObjectBuilder.getOpenSamlConfigBean(), object).toString();
                return new ResponseEntity<>(encoded, HttpStatus.OK);
            }
        } catch (final Exception e) {
            LOGGER.error(e.getMessage(), e);
            return new ResponseEntity<>(e.getMessage(), HttpStatus.BAD_REQUEST);
        }
        return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
    }
757627
protected void buildSamlResponse(final HttpServletResponse response,
                                     final HttpServletRequest request,
                                     final Pair<AuthnRequest, MessageContext> authenticationContext,
                                     final Assertion casAssertion,
                                     final String binding) {

        val authnRequest = authenticationContext.getKey();
        val pair = getRegisteredServiceAndFacade(authnRequest);

        val entityId = pair.getValue().getEntityId();
        LOGGER.debug("Preparing SAML response for [{}]", entityId);
        samlProfileHandlerConfigurationContext.getResponseBuilder().build(authnRequest, request, response, casAssertion,
            pair.getKey(), pair.getValue(), binding, authenticationContext.getValue());
        LOGGER.info("Built the SAML response for [{}]", entityId);
    }
581665
public void deleteService(String serviceId) {

        DeleteServiceRequest deleteServiceRequest = new DeleteServiceRequest().withId(serviceId);
        getDiscoveryClient().deleteService(deleteServiceRequest);

    }
1006768
public void doGeneric(String method, HttpServletRequest request, HttpServletResponse response) {
    try {
      ServletUtils.startTransaction(request.getHeader("User-Agent"));

      // Note that getServletPath does an un-escape so that the %24 of job id's are turned into $ characters.
      String uri = request.getServletPath();

      Properties headers = new Properties();
      Enumeration<String> en = request.getHeaderNames();
      while (en.hasMoreElements()) {
        String key = en.nextElement();
        String value = request.getHeader(key);
        headers.put(key, value);
      }

      final String contentType = request.getContentType();
      Properties parms = new Properties();
      String postBody = null;
      if (System.getProperty(H2O.OptArgs.SYSTEM_PROP_PREFIX + "debug.cors") != null) {
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Headers", "Content-Type");
      }

      if (contentType != null && contentType.startsWith(MIME_JSON)) {
        StringBuffer jb = new StringBuffer();
        String line = null;
        try {
          BufferedReader reader = request.getReader();
          while ((line = reader.readLine()) != null)
            jb.append(line);
        } catch (Exception e) {
          throw new H2OIllegalArgumentException("Exception reading POST body JSON for URL: " + uri);
        }
        postBody = jb.toString();
      } else {
        // application/x-www-form-urlencoded
        Map<String, String[]> parameterMap;
        parameterMap = request.getParameterMap();
        for (Map.Entry<String, String[]> entry : parameterMap.entrySet()) {
          String key = entry.getKey();
          String[] values = entry.getValue();

          if (values.length == 1) {
            parms.put(key, values[0]);
          } else if (values.length > 1) {
            StringBuilder sb = new StringBuilder();
            sb.append("[");
            boolean first = true;
            for (String value : values) {
              if (!first) sb.append(",");
              sb.append("\"").append(value).append("\"");
              first = false;
            }
            sb.append("]");
            parms.put(key, sb.toString());
          }
        }
      }

      // Make serve() call.
      NanoResponse resp = serve(uri, method, headers, parms, postBody);

      // Un-marshal Nano response back to Jetty.
      String choppedNanoStatus = resp.status.substring(0, 3);
      assert (choppedNanoStatus.length() == 3);
      int sc = Integer.parseInt(choppedNanoStatus);
      ServletUtils.setResponseStatus(response, sc);

      response.setContentType(resp.mimeType);

      Properties header = resp.header;
      Enumeration<Object> en2 = header.keys();
      while (en2.hasMoreElements()) {
        String key = (String) en2.nextElement();
        String value = header.getProperty(key);
        response.setHeader(key, value);
      }

      resp.writeTo(response.getOutputStream());

    } catch (IOException e) {
      e.printStackTrace();
      ServletUtils.setResponseStatus(response, 500);
      Log.err(e);
      // Trying to send an error message or stack trace will produce another IOException...
    } finally {
      ServletUtils.logRequest(method, request, response);
      // Handle shutdown if it was requested.
      if (H2O.getShutdownRequested()) {
        (new Thread() {
          public void run() {
            boolean [] confirmations = new boolean[H2O.CLOUD.size()];
            if (H2O.SELF.index() >= 0) {
              confirmations[H2O.SELF.index()] = true;
            }
            for(H2ONode n:H2O.CLOUD._memary) {
              if(n != H2O.SELF)
                new RPC<>(n, new UDPRebooted.ShutdownTsk(H2O.SELF,n.index(), 1000, confirmations, 0)).call();
            }
            try { Thread.sleep(2000); }
            catch (Exception ignore) {}
            int failedToShutdown = 0;
            // shutdown failed
            for(boolean b:confirmations)
              if(!b) failedToShutdown++;
            Log.info("Orderly shutdown: " + (failedToShutdown > 0? failedToShutdown + " nodes failed to shut down! ":"") + " Shutting down now.");
            H2O.closeAll();
            H2O.exit(failedToShutdown);
          }
        }).start();
      }
      ServletUtils.endTransaction();
    }
  }
217591
public void markSerialized(final HttpResponseStatus response, 
      final Throwable exception) {
    this.exception = exception;
    this.response = response;
    
    query_completed_ts = DateTime.currentTimeMillis();
    overall_stats.put(QueryStat.PROCESSING_PRE_WRITE_TIME, DateTime.nanoTime() - query_start_ns);
    synchronized (running_queries) {
      if (!running_queries.containsKey(this.hashCode())) {
        if (!ENABLE_DUPLICATES) {
          LOG.warn("Query was already marked as complete: " + this);
        }
      }
      running_queries.remove(hashCode());
      if (LOG.isDebugEnabled()) {
        LOG.debug("Removed completed query " + remote_address + " with hash " + 
            hashCode() + " on thread " + Thread.currentThread().getId());
      }
    }
    
    aggQueryStats();
    
    final int cache_hash = this.hashCode() ^ response.toString().hashCode();
    synchronized (completed_queries) {
      final QueryStats old_query = completed_queries.getIfPresent(cache_hash);
      if (old_query == null) {
        completed_queries.put(cache_hash, this);
      } else {
        old_query.executed++;
      }
    }
  }