Handle JSONRPC notification.
503065
def handle_notification(self, data):
        """"""
        if data.get('method') in self._callbacks:
            self._callbacks.get(data.get('method'))(data.get('params'))
1170767
function handleNotificationPush(event) {
  logger.log('Push notification received');

  if ($Log.notificationReceived) {
    event.waitUntil(logNotificationReceived(event));
  }

  // Show notification or fallback
  if (event.data && event.data.title) {
    event.waitUntil(showNotification(event.data));
  } else if ($Notifications.fallbackURL) {
    event.waitUntil(
      self.registration.pushManager.getSubscription()
        .then(fetchNotification)
        .then(convertResponseToJson)
        .then(showNotification)
        .catch(showNotification)
    );
  } else {
    logger.warn('No notification.data and no fallbackURL.');
    event.waitUntil(showNotification());
  }
}
822523
def jsonify_error(message_or_exception, status_code=400):
    """"""
    if isinstance(message_or_exception, Exception):
        message = '%s: %s' % (
            message_or_exception.__class__.__name__, message_or_exception)
    else:
        message = message_or_exception

    logging.debug('Returning status=%s, error message: %s',
                  status_code, message)
    response = jsonify(error=message)
    response.status_code = status_code
    return response
558369
def _handle_cancel_notification(self, msg_id):
        """"""
        request_future = self._client_request_futures.pop(msg_id, None)

        if not request_future:
            log.warn("Received cancel notification for unknown message id %s", msg_id)
            return

        # Will only work if the request hasn't started executing
        if request_future.cancel():
            log.debug("Cancelled request with id %s", msg_id)
373621
def on_message(self, ws, reply, *args):
        
        log.debug("Received message: %s" % str(reply))
        data = {}
        try:
            data = json.loads(reply, strict=False)
        except ValueError:
            raise ValueError("API node returned invalid format. Expected JSON!")

        if data.get("method") == "notice":
            id = data["params"][0]

            if id >= len(self.__events__):
                log.critical("Received an id that is out of range\n\n" + str(data))
                return

            # This is a "general" object change notification
            if id == self.__events__.index("on_object"):
                # Let's see if a specific object has changed
                for notice in data["params"][1]:
                    try:
                        if "id" in notice:
                            self.process_notice(notice)
                        else:
                            for obj in notice:
                                if "id" in obj:
                                    self.process_notice(obj)
                    except Exception as e:
                        log.critical(
                            "Error in process_notice: {}\n\n{}".format(
                                str(e), traceback.format_exc
                            )
                        )
            else:
                try:
                    callbackname = self.__events__[id]
                    log.info("Patching through to call %s" % callbackname)
                    [getattr(self.events, callbackname)(x) for x in data["params"][1]]
                except Exception as e:
                    log.critical(
                        "Error in {}: {}\n\n{}".format(
                            callbackname, str(e), traceback.format_exc()
                        )
                    )
327330
def process_notifications(self, messages):
        """"""
        for object_id, object_size, metadata_size in messages:
            if object_size > 0 and object_id in self._waiting_dict:
                linked_list = self._waiting_dict[object_id]
                self._complete_future(linked_list)
244128
def _Notify(username, notification_type, message, object_reference):
  """"""

  # Do not try to notify system users (e.g. Cron).
  if username in aff4_users.GRRUser.SYSTEM_USERS:
    return

  if object_reference:
    uc = object_reference.UnionCast()
    if hasattr(uc, "client_id"):
      message = _HostPrefix(uc.client_id) + message

  n = rdf_objects.UserNotification(
      username=username,
      notification_type=notification_type,
      state=rdf_objects.UserNotification.State.STATE_PENDING,
      message=message,
      reference=object_reference)
  data_store.REL_DB.WriteUserNotification(n)
149386
private void requestNotification() {
        AndPermission.with(this)
            .notification()
            .permission()
            .rationale(new NotifyRationale())
            .onGranted(new Action<Void>() {
                @Override
                public void onAction(Void data) {
                    toast(R.string.successfully);
                }
            })
            .onDenied(new Action<Void>() {
                @Override
                public void onAction(Void data) {
                    toast(R.string.failure);
                }
            })
            .start();
    }
1046509
def notification_message(cls, item):
        ''''''
        assert isinstance(item, Notification)
        return cls.encode_payload(cls.request_payload(item, None))
438776
def jsonrpc_request(method, identifier, params=None):
    """"""
    return '{}\r\n'.format(json.dumps({
        'id': identifier,
        'method': method,
        'params': params or {},
        'jsonrpc': '2.0'
    })).encode()
17542
function handleNotifyNext(e) {
  if (notifyOfNextSubs[e.type].length === 0) return;
  e.persist = blankFunction;
  const reNotifyOfNext = [];
  const reNotifyOfNextIDs = {};
  notifyOfNextSubs[e.type].forEach(sub => {
    if (sub.callback(e) === 'reNotifyOfNext') {
      reNotifyOfNextIDs[sub.id] = reNotifyOfNext.push(sub) - 1;
    }
  });
  notifyOfNextSubs[e.type] = reNotifyOfNext;
  subsIDs[e.type] = reNotifyOfNextIDs;
}
1011857
def request(self, method, params):
        """"""
        identifier = random.randint(1, 1000)
        self._transport.write(jsonrpc_request(method, identifier, params))
        self._buffer[identifier] = {'flag': asyncio.Event()}
        yield from self._buffer[identifier]['flag'].wait()
        result = self._buffer[identifier]['data']
        del self._buffer[identifier]['data']
        return result
318234
public synchronized void handleNotification(Notification notification, Object handback) {
        String type = notification.getType();
        if (REGISTRATION_NOTIFICATION.equals(type)) {
            jolokiaMBeanServer = lookupJolokiaMBeanServer();
            // We need to add the listener provided during construction time to add the Jolokia MBeanServer
            // so that it is kept updated, too.
            if (jolokiaMBeanServerListener != null) {
                JmxUtil.addMBeanRegistrationListener(jolokiaMBeanServer, jolokiaMBeanServerListener, null);
            }
        } else if (UNREGISTRATION_NOTIFICATION.equals(type)) {
            jolokiaMBeanServer = null;
        }

        allMBeanServers.clear();
        if (jolokiaMBeanServer != null) {
            allMBeanServers.add(jolokiaMBeanServer);
        }
        allMBeanServers.addAll(detectedMBeanServers);
    }
825156
def main(
    context: click.core.Context, method: str, request_type: str, id: Any, send: str
) -> None:
    
    exit_status = 0
    # Extract the jsonrpc arguments
    positional = [a for a in context.args if "=" not in a]
    named = {a.split("=")[0]: a.split("=")[1] for a in context.args if "=" in a}
    # Create the request
    if request_type == "notify":
        req = Notification(method, *positional, **named)
    else:
        req = Request(method, *positional, request_id=id, **named)  # type: ignore
    # Sending?
    if send:
        client = HTTPClient(send)
        try:
            response = client.send(req)
        except JsonRpcClientError as e:
            click.echo(str(e), err=True)
            exit_status = 1
        else:
            click.echo(response.text)
    # Otherwise, simply output the JSON-RPC request.
    else:
        click.echo(str(req))
    sys.exit(exit_status)
506166
def jsonrpc(self, request):
        
        if request.method != "POST":
            return HttpResponseNotAllowed(["POST"])

        request_str = request.body.decode('utf8')
        try:
            jsonrpc_request = JSONRPCRequest.from_json(request_str)
        except (TypeError, ValueError, JSONRPCInvalidRequestException):
            response = JSONRPCResponseManager.handle(
                request_str, self.dispatcher)
        else:
            jsonrpc_request.params = jsonrpc_request.params or {}
            jsonrpc_request_params = copy.copy(jsonrpc_request.params)
            if isinstance(jsonrpc_request.params, dict):
                jsonrpc_request.params.update(request=request)

            t1 = time.time()
            response = JSONRPCResponseManager.handle_request(
                jsonrpc_request, self.dispatcher)
            t2 = time.time()
            logger.info('{0}({1}) {2:.2f} sec'.format(
                jsonrpc_request.method, jsonrpc_request_params, t2 - t1))

        if response:
            def serialize(s):
                return json.dumps(s, cls=DatetimeDecimalEncoder)

            response.serialize = serialize
            response = response.json

        return HttpResponse(response, content_type="application/json")
641924
protected void handleJSONMessageAsDummy(JSONObject obj) throws Exception {
        hostLog.info("Generating dummy response for ops request " + obj);
        sendOpsResponse(null, obj, OPS_DUMMY);
    }
1219442
def send_payload(self, params):
        """"""
        data = dumps({
            'jsonrpc': self.version,
            'method': self.service_name,
            'params': params,
            'id': str(uuid.uuid1())
        }).encode('utf-8')
        headers = {
            'Content-Type': 'application/json-rpc',
            'Accept': 'application/json-rpc',
            'Content-Length': len(data)
        }
        try:
            req = urllib_request.Request(self.service_url, data, headers)
            resp = urllib_request.urlopen(req)
        except IOError as e:
            if isinstance(e, urllib_error.HTTPError):
                if e.code not in (
                        401, 403
                ) and e.headers['Content-Type'] == 'application/json-rpc':
                    return e.read().decode('utf-8')  # we got a jsonrpc-formatted respnose
                raise ServiceProxyException(e.code, e.headers, req)
            else:
                raise e
        return resp.read().decode('utf-8')