Translates an encapsulated event into a request to the Google Analytics API and sends the
resulting request.
970169
public void send(Event event) throws MetricsException {
    HttpPost request = new HttpPost(MetricsUtils.GA_ENDPOINT_URL);
    request.setEntity(MetricsUtils.buildPostBody(event, analyticsId, random));
    try {
      client.execute(request, RESPONSE_HANDLER);
    } catch (IOException e) {
      // All errors in the request execution, including non-2XX HTTP codes,
      // will throw IOException or one of its subclasses.
      throw new MetricsCommunicationException("Problem sending request to server", e);
    }
  }
200893
async def send_request(self, method, args=()):
        ''''''
        message, event = self.connection.send_request(Request(method, args))
        return await self._send_concurrent(message, event, 1)
507898
def dispatch(self, request, *args, **kwargs):
        
        ajax_kwargs = {'mandatory': self.ajax_mandatory}
        if self.json_encoder:
            ajax_kwargs['cls'] = self.json_encoder

        return ajax(**ajax_kwargs)(super(
            AJAXMixin, self).dispatch)(request, *args, **kwargs)
667566
function sendRequestPreExec(statementContext, onResultAvailable)
{
  // get the request headers
  var headers = statementContext.resultRequestHeaders;

  // build the basic json for the request
  var json =
  {
    disableOfflineChunks : false,
    sqlText              : statementContext.sqlText
  };

  // if binds are specified, build a binds map and include it in the request
  if (Util.exists(statementContext.binds))
  {
    json.bindings = buildBindsMap(statementContext.binds);
  }

  // include statement parameters if a value was specified
  if (Util.exists(statementContext.parameters))
  {
    json.parameters = statementContext.parameters;
  }

  // include the internal flag if a value was specified
  if (Util.exists(statementContext.internal))
  {
    json.isInternal = statementContext.internal;
  }

  // use the snowflake service to issue the request
  sendSfRequest(statementContext,
  {
    method  : 'POST',
    headers : headers,
    url     : Url.format(
    {
      pathname : '/queries/v1/query-request',
      search   : QueryString.stringify(
      {
        requestId: statementContext.requestId
      })
    }),
    json: json,
    callback: buildResultRequestCallback(
        statementContext, headers, onResultAvailable)
  },
  true);
}
1123042
function makeRequest () {
    request = self.request.apply(null, args);
    requestMiddleware.use(request);
    request.on("response", function (response) {
      var contentEncoding, gzipper;

      //Only cache successful responses
      if (response.statusCode >= 200 && response.statusCode < 300) {
        response.on('error', function (error) {
          self.handleError(error);
        });
        fs.writeFile(self.cacheDirectory + key + ".json", JSON.stringify(response.headers), function (error) {
          if (error) self.handleError(error);
        });

        responseWriter = fs.createWriteStream(self.cacheDirectory + key);

        responseWriter.on('error', function (error) {
          self.handleError(error);
        });

        contentEncoding = response.headers['content-encoding'] || '';
        contentEncoding = contentEncoding.trim().toLowerCase();

        if (contentEncoding === 'gzip') {
          response.on('error', function (error) {
            responseWriter.end();
          });
          response.pipe(responseWriter);
        } else {
          gzipper = zlib.createGzip();
          response.on('error', function (error) {
            gzipper.end();
          });
          gzipper.on('error', function (error) {
            self.handleError(error);
            responseWriter.end();
          });
          responseWriter.on('error', function (error) {
            response.unpipe(gzipper);
            gzipper.end();
          });
          response.pipe(gzipper).pipe(responseWriter);
        }
      }
    });
    self.emit("request", args[0]);
  }
1168172
function sendEvents() {

    logger.logEnter('sendEvents with eventCount ' + eventCount);

    if (eventCount > 0) {

      // If there are fewer than 10 events, we wait for more to arrive
      // before sending them.  Only delay sending them once so they
      // don't get too old.
      if (eventCount < 10 && canDelaySend) {

        // Wait for more events.
        canDelaySend = false;

        logger.logExit('sendEvents, wait for more events');
        return;
      }

      // Post the events.
      canDelaySend = true;

      // Ensure they're valid.
      validate();

      if (eventCount === 0) {

        // All events were invalid.  We're done.
        logger.logExit('sendEvents, all events were invalid');
        return;
      }

      try {
        // Use one of the three APIs: there's one for a single
        // event, one for multiple events of the same type, and
        // one for a mix of types.
        var path,
          request,
          eventData,
          failureCallback,
          retryEventCount, retryEventData, retryBuffer;

        if (buffer.length === 1) {
          // They're all the same type.
          eventData = buffer[0];

          if(runningInPublicEnv) {
            path = '/imfmobileanalytics/proxy/v1/apps/' + settings.AZFilterAppId + '/' + eventData[0];
          } else {
            path = '/' + eventData[0];
          }

          if (eventCount > 1) {
            path += '/_bulk';
          }
                    
          if(runningInPublicEnv) {
            // Deal with expiration of access token by refreshing token and retry the request.
            retryEventCount = eventCount;
            retryEventData = eventData;
            
            failureCallback = function(failureResponse, failureMessage) {
              emitter.emit('error', failureMessage);
              
              if(failureResponse.statusCode === 401) {
                logger.log('Received 401 Unathorized response while posting event(s) of same type.  Refresh access token and retry the post.');
                
                environment.refreshProxyAccessToken();
                var retryRequest = createLogRequest(logger, utils, path, environment, emitter, null);
                
                if (retryEventCount > 1) {
                  for (var i = 1; i < retryEventData.length; i++) {
                    retryRequest.write('{"create":{}}\n');
                    retryRequest.write(JSON.stringify(retryEventData[i]) + '\n');
                  }
                  retryRequest.end();
                } else {
                  retryRequest.end(JSON.stringify(retryEventData[1]));
                }
              }
            };
          }
          
          request = createLogRequest(logger, utils, path, environment, emitter, failureCallback);

          // If this request processing logic is changed, then retryRequest processing above should also be changed.
          if (eventCount > 1) {
            for (var i = 1; i < eventData.length; i++) {
              request.write('{"create":{}}\n');
              request.write(JSON.stringify(eventData[i]) + '\n');
            }
            request.end();
          } else {
            request.end(JSON.stringify(eventData[1]));
          }

        } else {

          // There's more than one type of event.
          if(runningInPublicEnv) {
            path = '/imfmobileanalytics/proxy/v1/apps/' + settings.AZFilterAppId + '/_bulk';
          } else {
            path = '/_bulk';
          }
          
          if(runningInPublicEnv) {
            // Deal with expiration of access token by refreshing token and retry the request.
            retryBuffer = buffer.slice(0);
            
            failureCallback = function(failureResponse, failureMessage) {
              emitter.emit('error', failureMessage);
              
              if(failureResponse.statusCode === 401) {
                logger.log('Received 401 Unathorized response while posting event(s) of different types.  Refresh access token and retry the post.');
                
                environment.refreshProxyAccessToken();
                var retryRequest = createLogRequest(logger, utils, path, environment, emitter, null);
                
                for (var x = 0; x < retryBuffer.length; x++) {
                  retryEventData = retryBuffer[x];
                  var createObject = '{"create":{"_type":"' + retryEventData[0] + '"}}\n';
                  for (var j = 1; j < retryEventData.length; j++) {
                    retryRequest.write(createObject);
                    retryRequest.write(JSON.stringify(retryEventData[j]) + '\n');
                  }
                }

                retryRequest.end();
              }
            };
          }
          
          request = createLogRequest(logger, utils, path, environment, emitter, failureCallback);

          // If this request processing logic is changed, then retryRequest processing above should also be changed.
          for (var x = 0; x < buffer.length; x++) {
            eventData = buffer[x];
            var createObject = '{"create":{"_type":"' + eventData[0] + '"}}\n';
            for (var j = 1; j < eventData.length; j++) {
              request.write(createObject);
              request.write(JSON.stringify(eventData[j]) + '\n');
            }
          }

          request.end();
        }
      } catch (thrown) {
        emitter.emit('error', 'While reporting events, caught ' + thrown);
      }

      buffer.clear();
    }

    logger.logExit('sendEvents');
  }
281354
function _sendRequest(method, uri, options, callback) {

        method(uri, options)
            .on('success', function(data, response) {
                if (data.result) {
                    callback(null, data.result);
                } else {
                    callback(null, data);
                }
            })
            .on('fail', function(err, response) {
                if (err) {
                    callback(err);
                } else {
                    callback(new Error('Request failed'));
                }
            })
            .on('error', function(err, response) {
                if (err) {
                    callback(err);
                } else {
                    callback(new Error('Request error'));
                }
            })
            .on('timeout', function(ms) {
                callback(new Error('Request timed out (' + ms + ')'));
            });
    }
731458
def dispatch_event(event):
    

    try:
      if event.http_verb == enums.HTTPVerbs.GET:
        requests.get(event.url, params=event.params, timeout=REQUEST_TIMEOUT).raise_for_status()
      elif event.http_verb == enums.HTTPVerbs.POST:
        requests.post(
          event.url, data=json.dumps(event.params), headers=event.headers, timeout=REQUEST_TIMEOUT
        ).raise_for_status()

    except request_exception.RequestException as error:
      logging.error('Dispatch event failed. Error: %s' % str(error))
841016
def request_message(cls, item, request_id):
        ''''''
        assert isinstance(item, Request)
        return cls.encode_payload(cls.request_payload(item, request_id))
1173323
@RequestHandler(dynamic = true)
    public void onRequest(Request.In event) {
        if (event.associated(Session.class).isPresent()) {
            return;
        }
        final HttpRequest request = event.httpRequest();
        Optional<String> requestedSessionId = request.findValue(
            HttpField.COOKIE, Converters.COOKIE_LIST)
            .flatMap(cookies -> cookies.stream().filter(
                cookie -> cookie.getName().equals(idName()))
                .findFirst().map(HttpCookie::getValue));
        if (requestedSessionId.isPresent()) {
            String sessionId = requestedSessionId.get();
            synchronized (this) {
                Optional<Session> session = lookupSession(sessionId);
                if (session.isPresent()) {
                    Instant now = Instant.now();
                    if ((absoluteTimeout <= 0
                        || Duration.between(session.get().createdAt(),
                            now).toMillis() < absoluteTimeout)
                        && (idleTimeout <= 0
                            || Duration.between(session.get().lastUsedAt(),
                                now).toMillis() < idleTimeout)) {
                        event.setAssociated(Session.class, session.get());
                        session.get().updateLastUsedAt();
                        return;
                    }
                    // Invalidate, too old
                    removeSession(sessionId);
                }
            }
        }
        String sessionId = createSessionId(request.response().get());
        Session session = createSession(sessionId);
        event.setAssociated(Session.class, session);
    }
1083918
def _send_event(self, title, text, tags, event_type, aggregation_key, severity='info'):
        """"""
        event_dict = {
            'timestamp': int(time()),
            'source_type_name': self.SOURCE_TYPE_NAME,
            'msg_title': title,
            'event_type': event_type,
            'alert_type': severity,
            'msg_text': text,
            'tags': tags,
            'aggregation_key': aggregation_key,
        }
        self.event(event_dict)
613727
def _send_event_task(args):
    
    endpoint = args['endpoint']
    json_message = args['json_message']
    _consumer_impl.send(endpoint, json_message)
745223
def capture(self, *args, **kwargs):
        
        if not self.is_enabled():
            return

        data = self.build_msg(*args, **kwargs)

        future = self.send(callback=kwargs.get('callback', None), **data)

        return (data['event_id'], future)
203423
def result_to_event(result)
      { :type => "Result",
        :from => result.from,
        :data => {
          :result => result.results,
          :duration => result.duration,
          :request_uuid => result.token,
          :request_from => result.request_from } }
    end
1291152
function Request(method, args, callback) {
		this.handle.send('layer', [method, args], function (content) {
			callback.apply({}, content);
		});
	}
339969
def request(self, msgtype, msgid, method, params=[]):
        """"""
        result = None
        error = None
        exception = None

        try:
            result = self.dispatch.call(method, params)
        except Exception as e:
            error = (e.__class__.__name__, str(e))
            exception = e

        if isinstance(result, Deferred):
            result.add_callback(self._result, msgid)
            result.add_errback(self._error, msgid)
        else:
            self.send_response(msgid, error, result)
118819
function makeRequest(apiKey, path, opts, callback) {
    var 
        key,
        req,
        dataStr = '';
        
    if(callback === undefined) {
        throw 'No callback defined';
        return;
    }

    path = '/plus/v1/' + path + '?key=' + apiKey;
    for(key in opts) {
        path += '&' + key + '=' + opts[key];
    }

    req = https.request({
        host: 'www.googleapis.com',
        port: 443,
        path: path,
        method: 'GET'
    }, function(res) {
        res.on('data', function(data) {
            dataStr += data;
        });
        
        res.on('end', function() {
            if(opts.alt === undefined || opts.alt.toLowerCase() == 'json') {
                try {
                    callback(null, JSON.parse(dataStr));
                } catch(err) {
                    callback(null, dataStr);
                }
            }
            else {
                callback(null, dataStr);
            }
        });
        
        res.on('close', function () {
            res.emit('end');
        });
    });
    req.end();
    
    req.on('error', function(err) {
        callback(err);
    });

    return req;
}