a method to catch and report http post request connectivity errors
433277
def _post_request(self, url, data=None, json=None, **kwargs):
        
        '''  '''
        
    # construct request kwargs
        request_kwargs = {
            'method': 'POST',
            'url': url,
            'data': data,
            'json': json
        }
        for key, value in kwargs.items():
            request_kwargs[key] = value

    # send request and handle response
        return self._request(**request_kwargs)
718041
public void handleConnect(HttpServletRequest request,
                              HttpServletResponse response)
        throws IOException
    {
        String uri = request.getRequestURI();
        
        context.log("CONNECT: "+uri);
        
        InetAddrPort addrPort=new InetAddrPort(uri);
        
        //if (isForbidden(HttpMessage.__SSL_SCHEME,addrPort.getHost(),addrPort.getPort(),false))
        //{
        //    sendForbid(request,response,uri);
        //}
        //else
        {
            InputStream in=request.getInputStream();
            OutputStream out=response.getOutputStream();
            
            Socket socket = new Socket(addrPort.getInetAddress(),addrPort.getPort());
            context.log("Socket: "+socket);
            
            response.setStatus(200);
            response.setHeader("Connection","close");
            response.flushBuffer();
            
            System.err.println(response);

            context.log("out<-in");
            IO.copyThread(socket.getInputStream(),out);
            context.log("in->out");
            IO.copy(in,socket.getOutputStream());
        }
    }
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);
    }
357958
def do_POST(self):
        

        # Check that the path is legal
        if not self.is_rpc_path_valid():
            self.report_404()
            return

        try:
            # Get arguments by reading body of request.
            # We read this in chunks to avoid straining
            # socket.read(); around the 10 or 15Mb mark, some platforms
            # begin to have problems (bug #792570).
            max_chunk_size = 10*1024*1024
            size_remaining = int(self.headers["content-length"])
            L = []
            while size_remaining:
                chunk_size = min(size_remaining, max_chunk_size)
                chunk = self.rfile.read(chunk_size)
                if not chunk:
                    break
                L.append(chunk)
                size_remaining -= len(L[-1])
            data = b''.join(L)

            data = self.decode_request_content(data)
            if data is None:
                return #response has been sent

            # In previous versions of SimpleXMLRPCServer, _dispatch
            # could be overridden in this class, instead of in
            # SimpleXMLRPCDispatcher. To maintain backwards compatibility,
            # check to see if a subclass implements _dispatch and dispatch
            # using that method if present.
            response = self.server._marshaled_dispatch(
                    data, getattr(self, '_dispatch', None), self.path
                )
        except Exception as e: # This should only happen if the module is buggy
            # internal error, report as HTTP server error
            self.send_response(500)

            # Send information about the exception if requested
            if hasattr(self.server, '_send_traceback_header') and \
                    self.server._send_traceback_header:
                self.send_header("X-exception", str(e))
                trace = traceback.format_exc()
                trace = str(trace.encode('ASCII', 'backslashreplace'), 'ASCII')
                self.send_header("X-traceback", trace)

            self.send_header("Content-length", "0")
            self.end_headers()
        else:
            self.send_response(200)
            self.send_header("Content-type", "text/xml")
            if self.encode_threshold is not None:
                if len(response) > self.encode_threshold:
                    q = self.accept_encodings().get("gzip", 0)
                    if q:
                        try:
                            response = gzip_encode(response)
                            self.send_header("Content-Encoding", "gzip")
                        except NotImplementedError:
                            pass
            self.send_header("Content-length", str(len(response)))
            self.end_headers()
            self.wfile.write(response)
262165
public void queryError(OutputStream os,
                         HeadersAmp headers,
                         String address,
                         long qId,
                         Throwable exn)
    throws IOException
  {
    init(os);

    OutH3 out = _out;

    if (out == null)
      return;

    if (log.isLoggable(_level)) {
      log.log(_level, "query-error " + exn
                 + " (in " + this + ")" + " {to:" + address + ", " + headers + "}");
      
      if (log.isLoggable(Level.FINEST)) {
        log.log(Level.FINEST, exn.toString(), exn);
      }
    }

    try {
      out.writeLong(MessageTypeHamp.QUERY_ERROR.ordinal());
      writeHeaders(out, headers);
      
      writeToAddress(out, address);
      out.writeLong(qId);

      ErrorAmp error = ErrorAmp.create(exn);

      out.writeString(error.getCode().toString());
      out.writeString(error.getMessage());
      out.writeObject(error.getDetail());

      // XXX: out.flushBuffer();
    } catch (Throwable e) {
      log.log(Level.WARNING, e.toString(), e);
      
      throw e;
    }
  }
662835
def http_error(self, url, fp, errcode, errmsg, headers, data=None):
        """"""
        # First check if there's a specific handler for this error
        name = 'http_error_%d' % errcode
        if hasattr(self, name):
            method = getattr(self, name)
            if data is None:
                result = method(url, fp, errcode, errmsg, headers)
            else:
                result = method(url, fp, errcode, errmsg, headers, data)
            if result: return result
        return self.http_error_default(url, fp, errcode, errmsg, headers)
673362
@Override
    public void sendError(HttpError error) throws MessageSentException {
        if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
            Tr.debug(tc, "Called sendError with: " + error);
        }
        if (!headersParsed()) {
            // request message must have the headers parsed prior to sending
            // any data out (this is a completely invalid state in the channel
            // above)
            // In this case, the app should not be re-using this so just close it
            IOException ioe = new IOException("Request not read yet");
            FFDCFilter.processException(ioe, CLASS_NAME + ".sendError", "1116");
            if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                Tr.debug(tc, "Attempt to send response without a request msg");
            }
            finishSendError(ioe);
            return;
        }

        // bail if the headers have already been sent
        if (headersSent()) {
            throw new MessageSentException("Message already sent");
        }

        // ensure error is legal
        if (null == error) {
            if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                Tr.debug(tc, "Reset null error to Internal Server Error");
            }
            error = StatusCodes.INTERNAL_ERROR.getHttpError();
        }

        // set up the response message and then send it out
        getResponse().setStatusCode(error.getErrorCode());
        if (getResponse().getStatusCode().isErrorCode()) {
            // PK30169 - some "error" status codes do not disable persistence
            setPersistent(false);
        }
        getVC().getStateMap().put(HTTP_ERROR_IDENTIFIER, error);
        if (getHttpConfig().getDebugLog().isEnabled(DebugLog.Level.ERROR)) {
            getHttpConfig().getDebugLog().log(DebugLog.Level.ERROR, HttpMessages.MSG_CONN_SENDERROR + error.getErrorCode(), this);
        }
        // now figure out what buffers, if any, to send as the response body
        WsByteBuffer[] body = loadErrorBody(error, getMyRequest(), getResponse());
        VirtualConnection rc = finishResponseMessage(body, HttpISCWriteErrorCallback.getRef(), false);
        if (null != rc) {
            finishSendError(error.getClosingException());
        }
    }
326304
private static void checkHttpResponseCodeValid(URLConnection connection) throws RepositoryHttpException, IOException {
        // if HTTP URL not File URL
        if (connection instanceof HttpURLConnection) {
            HttpURLConnection conn = (HttpURLConnection) connection;
            conn.setRequestMethod("GET");
            int respCode = conn.getResponseCode();
            if (respCode < 200 || respCode >= 300) {
                throw new RepositoryHttpException("HTTP connection returned error code " + respCode, respCode, null);
            }
        }
    }
1649
private void writeJsonDataRequest(HttpURLConnection connection, Request request) {
        try (OutputStreamWriter wr = new OutputStreamWriter(connection.getOutputStream())) {
            wr.write(request.getJsonPayload().toString());
            wr.flush();
        } catch (IOException e) {
            log.error(e);
        }
    }
58735
function checkPostOrPutOrPatchRequest(req, res, cb) {
            if (req.body) {
                for(var i in req.body) {
                    for(var j in _patternSql){
                        if (_patternSql[j].test(req.body[i]) && _blocker.blockHost) {
                            _config.attack.handle(req, res);
                            cb = undefined;
                            break;
                        }
                    }
                    if(!cb){
                        break;
                    }
                }
            }
            if (cb) {
                cb();
            }
        }
1016727
function HTTPError(statusCode, data) {
  Error.call(this);
  Error.captureStackTrace(this, this.constructor);

  /**
   * Human-readable error name.
   *
   * @type {String}
   */
  this.name = http.STATUS_CODES[statusCode];

  /**
   * HTTP status code.
   *
   * @type {Number}
   */
  this.statusCode = statusCode;

  /**
   * Any additional data.
   *
   * @type {*}
   */
  this.data = data;

  if (data) {
    // Property of Error.
    this.message = JSON.stringify(data);
  }
}
40721
private void handleRequestFailure(long requestId, Throwable error, ThreadContext context) {
    ByteBuf buffer = channel.alloc().buffer(10)
      .writeByte(RESPONSE)
      .writeLong(requestId)
      .writeByte(FAILURE);

    try {
      writeError(buffer, error, context);
    } catch (SerializationException e) {
      return;
    }

    channel.writeAndFlush(buffer, channel.voidPromise());
  }
165776
function throwStatusError(resp) {
  let err = new Error(resp.statusText || 'http error: ' + resp.status);
  err.type = resp.status;
  err.response = resp;
  err.url = resp.url;
  throw err;
}
708328
def HandleExceptionsAndRebuildHttpConnections(retry_args):
    
    # If the server indicates how long to wait, use that value.  Otherwise,
    # calculate the wait time on our own.
    retry_after = None

    # Transport failures
    if isinstance(retry_args.exc, (http_client.BadStatusLine,
                                   http_client.IncompleteRead,
                                   http_client.ResponseNotReady)):
        logging.debug('Caught HTTP error %s, retrying: %s',
                      type(retry_args.exc).__name__, retry_args.exc)
    elif isinstance(retry_args.exc, socket.error):
        logging.debug('Caught socket error, retrying: %s', retry_args.exc)
    elif isinstance(retry_args.exc, socket.gaierror):
        logging.debug(
            'Caught socket address error, retrying: %s', retry_args.exc)
    elif isinstance(retry_args.exc, socket.timeout):
        logging.debug(
            'Caught socket timeout error, retrying: %s', retry_args.exc)
    elif isinstance(retry_args.exc, httplib2.ServerNotFoundError):
        logging.debug(
            'Caught server not found error, retrying: %s', retry_args.exc)
    elif isinstance(retry_args.exc, ValueError):
        # oauth2client tries to JSON-decode the response, which can result
        # in a ValueError if the response was invalid. Until that is fixed in
        # oauth2client, need to handle it here.
        logging.debug('Response content was invalid (%s), retrying',
                      retry_args.exc)
    elif (isinstance(retry_args.exc, TokenRefreshError) and
          hasattr(retry_args.exc, 'status') and
          (retry_args.exc.status == TOO_MANY_REQUESTS or
           retry_args.exc.status >= 500)):
        logging.debug(
            'Caught transient credential refresh error (%s), retrying',
            retry_args.exc)
    elif isinstance(retry_args.exc, exceptions.RequestError):
        logging.debug('Request returned no response, retrying')
    # API-level failures
    elif isinstance(retry_args.exc, exceptions.BadStatusCodeError):
        logging.debug('Response returned status %s, retrying',
                      retry_args.exc.status_code)
    elif isinstance(retry_args.exc, exceptions.RetryAfterError):
        logging.debug('Response returned a retry-after header, retrying')
        retry_after = retry_args.exc.retry_after
    else:
        raise retry_args.exc
    RebuildHttpConnections(retry_args.http)
    logging.debug('Retrying request to url %s after exception %s',
                  retry_args.http_request.url, retry_args.exc)
    time.sleep(
        retry_after or util.CalculateWaitForRetry(
            retry_args.num_retries, max_wait=retry_args.max_retry_wait))
944179
private void parseThrowIOEForInboundConnections(Map<?, ?> props) {
        //PI57542
        Object value = props.get(HttpConfigConstants.PROPNAME_THROW_IOE_FOR_INBOUND_CONNECTIONS);
        if (null != value) {
            this.throwIOEForInboundConnections = convertBoolean(value);
            if ((TraceComponent.isAnyTracingEnabled()) && (tc.isEventEnabled())) {
                Tr.event(tc, "Config: ThrowIOEForInboundConnections is " + throwIOEForInboundConnections());
            }
        }
    }
1185474
@Override
    public void onError(ChannelHandlerContext ctx, boolean outbound, Throwable cause) {
        Http2Exception embedded = getEmbeddedHttp2Exception(cause);
        if (isStreamError(embedded)) {
            onStreamError(ctx, outbound, cause, (StreamException) embedded);
        } else if (embedded instanceof CompositeStreamException) {
            CompositeStreamException compositException = (CompositeStreamException) embedded;
            for (StreamException streamException : compositException) {
                onStreamError(ctx, outbound, cause, streamException);
            }
        } else {
            onConnectionError(ctx, outbound, cause, embedded);
        }
        ctx.flush();
    }
290701
def _connection_failed(self, link_uri, msg):
        """"""
        print('Connection to %s failed: %s' % (link_uri, msg))
        self.is_connected = False