Handle SLO POST profile request.

@param response the response
@param request  the request
@throws Exception the exception
429213
@PostMapping(path = SamlIdPConstants.ENDPOINT_SAML2_SLO_PROFILE_POST)
    protected void handleSaml2ProfileSLOPostRequest(final HttpServletResponse response,
                                                    final HttpServletRequest request) throws Exception {
        val decoder = getSamlProfileHandlerConfigurationContext().getSamlMessageDecoders().get(HttpMethod.POST);
        handleSloProfileRequest(response, request, decoder);
    }
1176148
public void handleResponse(String response) {
        if (messageListener != null) {
            log.debug("Sending Http response");
            messageListener.onOutboundMessage(new RawMessage(response), null);
        } else {
            if (log.isDebugEnabled()) {
                log.debug("Sending Http response:" + NEWLINE + response);
            }
        }
    }
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());
    }
1063880
protected void handleExceptionIfNeeded(HttpResponse response) throws GloboDnsException, IOException {
		int statusCode = response.getStatusCode();
		if (statusCode/100 == 2) {
			// 200 family code
			// Successful return, do nothing
			return;
		} else if (statusCode/100 == 4 || statusCode/100 == 5) {
			// 400 and 500 family codes
			// Something was wrong, produce an error result
			String responseAsString = response.parseAsString();
			if (responseAsString == null || !responseAsString.startsWith("{")) {
				// Response not well formed!
				throw new GloboDnsHttpException("Unknown error in GloboDNS: " + responseAsString, statusCode);
			}
			
			GloboDnsRoot<ErrorMessage> responseObj = this.parse(responseAsString, ErrorMessage.class);
			ErrorMessage errorMsg = responseObj.getFirstObject();
			if (errorMsg != null && errorMsg.getMsg() != null) {
				throw new GloboDnsHttpException(errorMsg.getMsg(), statusCode);
			} else {
				throw new GloboDnsHttpException(responseAsString, statusCode);
			}
		} else {
			// Unknown error code, return generic exception with description
			throw new GloboDnsHttpException(response.parseAsString(), statusCode);
		}
	}
581055
private static void renderException(final Map model, final HttpServletResponse response) {
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        model.put("status", HttpServletResponse.SC_BAD_REQUEST);
        render(model, response);
    }
784810
@PostMapping(path = SamlIdPConstants.ENDPOINT_SAML2_SSO_PROFILE_POST)
    public void handleSaml2ProfileSsoPostRequest(final HttpServletResponse response,
                                                 final HttpServletRequest request) throws Exception {
        val decoder = getSamlProfileHandlerConfigurationContext().getSamlMessageDecoders().getInstance(HttpMethod.POST);
        handleSsoPostProfileRequest(response, request, decoder);
    }
2099
@Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        preProcessRequest(request);

        DefaultServerDolphin serverDolphin = resolveServerDolphin(request);

        String input = readInput(request);
        if (LOG.isLoggable(Level.FINEST)) {
            LOG.finest("received json: " + input);
        }

        List<Command> commands = decodeInput(serverDolphin.getServerConnector().getCodec(), input);

        List<Command> results = handleCommands(serverDolphin.getServerConnector(), commands);

        String output = encodeOutput(serverDolphin.getServerConnector().getCodec(), results);

        writeHeaders(request, response, results);

        if (LOG.isLoggable(Level.FINEST)) {
            LOG.finest("sending json response: " + output);
        }
        writeOutput(response, output);

        postProcessResponse(response);
    }
317394
public static void before(Object request, Object response) {
        /*
         * Use reflection to access the HttpServletRequest/Response as using the
         * true method signature caused ClassLoader issues.
         */
        Class<?> reqClass = request.getClass();
        try {
            /*
             * Retrieve the tracker from the request and increment nesting level
             */
            HttpRequestTracker tracker;
            Method getAttribute = reqClass.getMethod(GET_ATTRIBUTE, String.class);
            tracker = (HttpRequestTracker) (getAttribute.invoke(request, TRACKER_ATTRIBUTE));
            if (tracker == null) {
                tracker = new HttpRequestTracker();
            }
            tracker.increment();
            Method setAttribute = reqClass.getMethod(SET_ATTRIBUTE, String.class, Object.class);
            setAttribute.invoke(request, TRACKER_ATTRIBUTE, tracker);
        } catch (Exception e) {
            // Log any exception caused by our injected code
            System.err.println("Javametrics: Servlet callback exception: " + e.toString());
            e.printStackTrace();
        }
    }
47298
private void handle(final Request request, final Response response, final List<Middleware> middlewares) throws Exception {
		if (middlewares.isEmpty()) {
			throw new NotFoundException();
		}
		
		Middleware current = middlewares.remove(0);
		current.handle(request, response, new MiddlewareChain() {
			@Override
			public void next() throws Exception {
				// recursive call
				handle(request, response, middlewares);
			}
		});
	}
780690
public void handle(HttpServletRequest request, HttpServletResponse response) throws IOException {
		logger.debug("Handling HttpServletRequest {}", request);
		response.setContentType(contentType);
		OutputStream output = response.getOutputStream();
		InputStream input = getRequestStream(request);
		int result = ErrorResolver.JsonError.PARSE_ERROR.code;
		int contentLength = 0;
		ByteArrayOutputStream byteOutput = new ByteArrayOutputStream();
		try {
			String acceptEncoding = request.getHeader(ACCEPT_ENCODING);
			result = handleRequest0(input, output, acceptEncoding, response, byteOutput);

			contentLength = byteOutput.size();
		} catch (Throwable t) {
			if (StreamEndedException.class.isInstance(t)) {
				logger.debug("Bad request: empty contents!");
			} else {
				logger.error(t.getMessage(), t);
			}
		}
		int httpStatusCode = httpStatusCodeProvider == null ? DefaultHttpStatusCodeProvider.INSTANCE.getHttpStatusCode(result)
				: httpStatusCodeProvider.getHttpStatusCode(result);
		response.setStatus(httpStatusCode);
		response.setContentLength(contentLength);
		byteOutput.writeTo(output);
		output.flush();
	}
885719
public void doPost(HttpServletRequest request,
                        HttpServletResponse response) 
        throws ServletException, IOException
    {
        String target=null;
        response.sendRedirect(request.getContextPath()+
                              request.getServletPath()+"/"+
                              Long.toString(System.currentTimeMillis(),36)+
                              (target!=null?("#"+target):""));
    }
1359423
public void doHello( StaplerRequest request, StaplerResponse response ) throws IOException, ServletException {
        System.out.println("Hello operation");
        request.setAttribute("systemTime",new Long(System.currentTimeMillis()));

        // it can generate the response by itself, just like
        // servlets can do so. Or you can redirect the client.
        // Basically, you can do anything that a servlet can do.

        // the following code shows how you can forward it to
        // another object. It's almost like a relative URL where '.'
        // corresponds to 'this' object.
        response.forward(this,"helloJSP",request);
    }
188882
public void handle(String pathInContext, String pathParams, HttpRequest request,
            HttpResponse response) throws HttpException, IOException
    {

        // exempt error pages
        // TODO This probably should be more general?
        if (request.getAttribute("javax.servlet.error.status_code") != null) return;

        try
        {

            String ip = request.getRemoteAddr();
            boolean authorized = checkIP(ip);

            if (!authorized)
            {
                // The IP is NOT allowed
                response.sendError(HttpResponse.__403_Forbidden);
                request.setHandled(true);
                return;
            }
            else
            {
                // The IP is allowed
                return;
            }
        }
        catch (Exception ex)
        {
            System.out.println(ex);
            response.sendError(HttpResponse.__500_Internal_Server_Error);
            request.setHandled(true);
        }
    }
1338896
private HttpResponse executeCurrentRequestWithoutGZip(HttpRequest request) throws IOException {
    // method override for non-POST verbs
    new MethodOverride().intercept(request);
    // don't throw an exception so we can let a custom Google exception be thrown
    request.setThrowExceptionOnExecuteError(false);
    // execute the request
    HttpResponse response = request.execute();
    return response;
  }
1091491
public void doPost (HttpServletRequest request, HttpServletResponse response)
    		throws ServletException, IOException {
        String alertId = request.getParameter("alertId");
        String tel = request.getParameter("tel");
        String alertText = request.getParameter("alertText");        
        if(alertText == null || alertText.length() < 1) {
	        // Get the content of the request as the text to parse
	        byte[] content = new byte[request.getContentLength()];
	        request.getInputStream().read(content,0, request.getContentLength());        
	        alertText = new String(content);
	        // Fix from Rafael Soares http://groups.google.com/group/mobicents-public/browse_thread/thread/16015a2e2c034806
	        // remove '\n' and ',' chars to avoid problems with TTS
	        alertText = alertText.replace('\n', ' ').replace(',', ' ');
	        if(logger.isInfoEnabled()) {
	        	logger.info("Got an alert : \n alertID : " + alertId + " \n tel : " + tel + " \n text : " +alertText);
	        }
        }
        alertText = "Hello Admin; the server 0.0.0.0:2999 you're monitoring is running out of memory";
		// Create app session and request
        SipApplicationSession appSession = 
        	((ConvergedHttpSession)request.getSession()).getApplicationSession();
        URI fromURI = sipFactory.createAddress(FROM).getURI();
        URI toURI = sipFactory.createAddress(tel).getURI();
        SipServletRequest sipServletRequest = sipFactory.createRequest(appSession, INVITE, fromURI, toURI);        
        sipServletRequest.setRequestURI(toURI);
		
        sipServletRequest.getSession().setAttribute("speechUri",
				java.net.URI.create("data:" + URLEncoder.encode("ts("+ alertText +")", "UTF-8")));
		try {
			// Media Server Control Creation
			MediaSession mediaSession = MMSUtil.getMsControl().createMediaSession();
			NetworkConnection connection = mediaSession
			.createNetworkConnection(NetworkConnection.BASIC);

			SdpPortManager sdpManag = connection.getSdpPortManager();
			sdpManag.generateSdpOffer();
			
			byte[] sdpOffer = null;
			int numTimes = 0;
			while(sdpOffer == null && numTimes<10) {
				sdpOffer = sdpManag.getMediaServerSessionDescription();
				Thread.sleep(500);
				numTimes++;
			}
			
			sipServletRequest.setContentLength(sdpOffer.length);
			sipServletRequest.setContent(sdpOffer, "application/sdp");	
			
			MediaGroup mg = mediaSession.createMediaGroup(MediaGroup.PLAYER_SIGNALDETECTOR);
			
			// storing helpful info for later during the call
			SipSession sipSession = sipServletRequest.getSession();
			sipSession.setAttribute("connection", connection);
			sipSession.setAttribute("alertId", alertId);
			sipSession.setAttribute("tel", tel);
			sipSession.setAttribute("alertText", alertText);
			sipSession.setAttribute("connection", connection);
			sipSession.setAttribute("mediaGroup", mg);
			sipSession.setAttribute("mediaSession", mediaSession);
			sipSession.setAttribute("feedbackUrl", (String)getServletContext().getAttribute("alert.feedback.url"));
			sipServletRequest.send();
			mg.getSignalDetector().addListener(new DTMFListener(alertId, (String)getServletContext().getAttribute("alert.feedback.url")));
			connection.join(Direction.DUPLEX, mg);
		} catch (Exception e) {
			// Should not happen
			logger.error("Unexpected exception while trying to send the SIP Request", e);
			response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
			String errorBody = "<HTML><BODY>Phone Alert not Sent, could not find Media Libraries !</BODY></HTML>";
			sendHttpResponse(response, errorBody);
			return;
		}
				
        sendHttpResponse(response, OK_BODY);
    }
925464
@SuppressWarnings("unchecked")
    public static void after(Object request, Object response) {

        HttpData data = new HttpData();

        /*
         * Use reflection to access the HttpServletRequest/Response as using the
         * true method signature caused ClassLoader issues.
         */
        Class<?> reqClass = request.getClass();
        Class<?> respClass = response.getClass();
        try {
            /*
             * Retrieve the request tracker
             */
            Method getAttribute = reqClass.getMethod(GET_ATTRIBUTE, String.class);
            Method setAttribute = reqClass.getMethod(SET_ATTRIBUTE, String.class, Object.class);
            HttpRequestTracker tracker = (HttpRequestTracker) (getAttribute.invoke(request, TRACKER_ATTRIBUTE));
            if (tracker == null) {
                /*
                 * should never happen
                 */
                throw new JavametricsException("Unable to find request tracker");
            }

            /*
             * Decrement the nesting level and return if still nested
             */
            if (tracker.decrement()) {
                setAttribute.invoke(request, TRACKER_ATTRIBUTE, tracker);
                return;
            }

            /*
             * Clear the tracker
             */
            setAttribute.invoke(request, TRACKER_ATTRIBUTE, null);

            data.setRequestTime(tracker.getRequestTime());

            Method getRequestURL = reqClass.getMethod(GET_REQUEST_URL);
            data.setUrl(((StringBuffer) getRequestURL.invoke(request)).toString());

            Method getMethod = reqClass.getMethod(GET_METHOD);
            data.setMethod((String) getMethod.invoke(request));

            Method getStatus = respClass.getMethod(GET_STATUS);
            data.setStatus((Integer) getStatus.invoke(response));

            if (detailed) {
                Method getContentType = respClass.getMethod(GET_CONTENT_TYPE);
                data.setContentType((String) getContentType.invoke(response));

                Method getHeaders = respClass.getMethod(GET_HEADER_NAMES);
                Method getHeader = respClass.getMethod(GET_HEADER, String.class);
                Collection<String> headers = (Collection<String>) getHeaders.invoke(response);
                if (headers != null) {
                    for (String headerName : headers) {
                        String header = (String) getHeader.invoke(response, headerName);
                        if (header != null) {
                            data.addHeader(headerName, header);
                        }
                    }
                }

                Method getReqHeaders = reqClass.getMethod(GET_HEADER_NAMES);
                Method getReqHeader = reqClass.getMethod(GET_HEADER, String.class);
                Enumeration<String> reqHeaders = (Enumeration<String>) getReqHeaders.invoke(request);
                if (reqHeaders != null) {
                    while (reqHeaders.hasMoreElements()) {
                        String headerName = reqHeaders.nextElement();
                        String header = (String) getReqHeader.invoke(request, headerName);
                        if (header != null) {
                            data.addRequestHeader(headerName, header);
                        }
                    }
                }
            }
            
            data.setDuration(System.currentTimeMillis() - tracker.getRequestTime());

            if (Agent.debug) {
                System.err.println("Javametrics: Sending {\"http\":" + data.toJsonString() + "}");
            }

            /*
             * Send the http request data to the Javametrics agent
             */
            Javametrics.getInstance().sendJSON(HTTP_TOPIC, data.toJsonString());

        } catch (Exception e) {
            // Log any exception caused by our injected code
            System.err.println("Javametrics: Servlet callback exception: " + e.toString());
            e.printStackTrace();
        }

    }
884038
public void doPost(HttpServletRequest request,
                        HttpServletResponse response) 
        throws ServletException, IOException
    {
        String target=null;

        Log l = LogFactory.getLog(Debug.class);
        
        if (!(l instanceof LogImpl))
            return;
        LogImpl log = (LogImpl) l;
        String action=request.getParameter("Action");
        
        if ("Set Options".equals(action))
        {
            log.setDebug("on".equals(request.getParameter("D")));
            log.setSuppressWarnings("on".equals(request.getParameter("W")));
            String v=request.getParameter("V");
            if (v!=null && v.length()>0)
                log.setVerbose(Integer.parseInt(v));
            else
                log.setVerbose(0);
            log.setDebugPatterns(request.getParameter("P"));


            LogSink[] sinks = log.getLogSinks();
            for (int s=0;sinks!=null && s<sinks.length;s++)
            {
                if (sinks[s]==null)
                    continue;
                
                if ("on".equals(request.getParameter("LSS"+s)))
                {
                    if(!sinks[s].isStarted())
                        try{sinks[s].start();}catch(Exception e){log.warn(e);}
                }
                else
                {
                    if(sinks[s].isStarted())
                        try{sinks[s].stop();}catch(InterruptedException e){}
                }

                String options=request.getParameter("LO"+s);
                if (options==null)
                    options="";
                
                if (sinks[s] instanceof OutputStreamLogSink)
                {
                    OutputStreamLogSink sink=(OutputStreamLogSink)sinks[s];
                    
                    sink.setLogTags("on".equals(request.getParameter("LT"+s)));
                    sink.setLogLabels ("on".equals(request.getParameter("LL"+s)));
                    sink.setLogStackSize("on".equals(request.getParameter("Ls"+s)));
                    sink.setLogStackTrace("on".equals(request.getParameter("LS"+s)));
                    sink.setSuppressStack("on".equals(request.getParameter("SS"+s)));
                    sink.setLogOneLine("on".equals(request.getParameter("SL"+s)));

                    sink.setFilename(request.getParameter("LF"+s));
                }
                
            }
        }
        else if ("Add LogSink".equals(action))
        {
            System.err.println("add log sink "+request.getParameter("LSC"));
            try
            {
                log.add(request.getParameter("LSC"));
            }
            catch(Exception e)
            {
                log.warn(e);
            }
        }
        else if ("Delete Stopped Sinks".equals(action))
        {
            log.deleteStoppedLogSinks();
        }
        
        response.sendRedirect(request.getContextPath()+
                              request.getServletPath()+"/"+
                              Long.toString(System.currentTimeMillis(),36)+
                              (target!=null?("#"+target):""));
    }