GVKun编程网logo

开始-JSON-RPC-“冒号太多”

29

如果您想了解开始-JSON-RPC-“冒号太多”的相关知识,那么本文是一篇不可错过的文章,我们将为您提供关于(译)JSON-RPC2.0规范(中文版)、com.facebook.stetho.insp

如果您想了解开始-JSON-RPC-“冒号太多”的相关知识,那么本文是一篇不可错过的文章,我们将为您提供关于(译) JSON-RPC 2.0 规范(中文版)、com.facebook.stetho.inspector.jsonrpc.JsonRpcPeer的实例源码、com.facebook.stetho.inspector.jsonrpc.JsonRpcResult的实例源码、Django JSON-RPC的有价值的信息。

本文目录一览:

开始-JSON-RPC-“冒号太多”

开始-JSON-RPC-“冒号太多”

我正在尝试使用Go(不在GAE上)为Bitcoin调用HTTP JSON-RPC服务器,但是出现错误

dial tcp http://user:pass@127.0.0.1:8332: too many colons in address

要么

dial ip http://user:pass@127.0.0.1:8332: lookup http://user:pass@127.0.0.1:8332: no such host

我尝试了各种网络配置,但无济于事。当我在浏览器中键入地址时,服务器收到了响应:

{"result":null,"error":{"code":-32700,"message":"Parse error"},"id":null}

对于空电话,这看起来像是正确的响应。

如何在Go中正确调用该HTTP JSON-RPC服务器?

答案1

小编典典

在主机周围使用方括号,如下所示:

[user:pass@127.0.0.1]:8332

参考:

http://golang.org/src/pkg/net/ipsock.go?s=2247:2304#L68

(译) JSON-RPC 2.0 规范(中文版)

(译) JSON-RPC 2.0 规范(中文版)

本文博客wiki地址:http://wiki.geekdream.com/Specification/json-rpc_2.0.html

  • 起源时间: 2010-03-26(基于2009-05-24版本)
  • 更新: 2013-01-04
  • 作者: JSON-RPC工作组< json-rpc@googlegroups.com >
  • 原文链接: http://www.jsonrpc.org/specification
  • 翻译: leozvc < xxfs91@gmail.com >

1.概述

JSON-RPC是一个无状态且轻量级的远程过程调用(RPC)协议。 本规范主要定义了一些数据结构及其相关的处理规则。它允许运行在基于socket,http等诸多不同消息传输环境的同一进程中。其使用JSON(RFC 4627)作为数据格式。

它为简单而生!

2.约定

文档中关键字"MUST"、"MUST NOT"、"REQUIRED"、"SHALL"、"SHALL NOT"、"SHOULD"、"SHOULD NOT"、"RECOMMENDED"、"MAY"和 "OPTIONAL" 将在RFC 2119 中得到详细的解释及描述。

由于JSON-RPC使用JSON,它具有与其相同的类型系统(见http://www.json.org或RFC 4627)。JSON可以表示四个基本类型(String、Numbers、Booleans和Null)和两个结构化类型(Objects和Arrays)。 规范中,术语“Primitive”标记那4种原始类型,“Structured”标记两种结构化类型。任何时候文档涉及JSON数据类型,第一个字母都必须大写:Object,Array,String,Number,Boolean,Null。包括True和False也要大写。

在客户端与任何被匹配到的服务端之间交换的所有成员名字应是区分大小写的。 函数、方法、过程都可以认为是可以互换的。

客户端被定义为请求对象的来源及响应对象的处理程序。

服务端被定义为响应对象的起源和请求对象的处理程序。

该规范的一种实现为可以轻而易举的填补这两个角色,即使是在同一时间,同一客户端或其他不相同的客户端。 该规范不涉及复杂层。

3.兼容性

JSON-RPC 2.0 的请求对象和响应对象可能无法在现用的JSON-RPC 1.0 客户端或服务端工作,然而我们可以很容易在两个版本间区分出2.0,总会包含一个成员命名为 “jsonrpc” 且值为“2.0”, 而1.0版本是不包含的。大部分的2.0实现应该考虑尝试处理1.0的对象,即使不是对等的也应给其相关提示。

4.请求对象

发送一个请求对象至服务端代表一个rpc调用, 一个请求对象包含下列成员:

jsonrpc

指定JSON-RPC协议版本的字符串,必须准确写为“2.0”

method

包含所要调用方法名称的字符串,以rpc开头的方法名,用英文句号(U+002E or ASCII 46)连接的为预留给rpc内部的方法名及扩展名,且不能在其他地方使用。

params

调用方法所需要的结构化参数值,该成员参数可以被省略。

id

已建立客户端的唯一标识id,值必须包含一个字符串、数值或NULL空值。如果不包含该成员则被认定为是一个通知。该值一般不为NULL[1],若为数值则不应该包含小数[2]。

服务端必须回答相同的值如果包含在响应对象。 这个成员用来两个对象之间的关联上下文。

1
在请求对象中不建议使用NULL作为id值,因为该规范将使用空值认定为未知id的请求。另外,由于JSON-RPC 1.0 的通知使用了空值,这可能引起处理上的混淆。

[2]
使用小数是不确定性的,因为许多十进制小数不能精准的表达为二进制小数。

4.1通知

没有包含“id”成员的请求对象为通知,
作为通知的请求对象表明客户端对相应的响应对象并不感兴趣,本身也没有响应对象需要返回给科幻的。服务端必须不回复一个通知,包含那些批量请求中的。

由于通知没有返回的响应对象,所以通知不确定是否被定义。同样,客户端不会意识到任何错误(例如参数缺省,内部错误)。

4.2参数结构

rpc调用如果存在参数则必须为基本类型或结构化类型的参数值,要么为索引数组,要么为关联数组对象。

  • 索引:参数必须为数组,并包含与服务端预期顺序一致的参数值。

  • 关联名称:参数必须为对象,并包含与服务端相匹配的参数成员名称。没有在预期中的成员名称可能会引起错误。名称必须完全匹配,包括方法的预期参数名以及大小写。

5.响应对象

当发起一个rpc调用时,除通知之外,服务端都必须回复响应。响应表示为一个JSON对象,使用以下成员:

jsonrpc

指定JSON-RPC协议版本的字符串,必须准确写为“2.0”

result

该成员在成功时必须包含。

当调用方法引起错误时必须不包含该成员。

服务端中的被调用方法决定了该成员的值。

error

该成员在失败是必须包含。

当没有引起错误的时必须不包含该成员。

该成员参数值必须为5.1中定义的对象。

id

该成员必须包含。

该成员值必须于请求对象中的id成员值一致。

若在检查请求对象id时错误(例如参数错误或无效请求),则该值必须为空值。

响应对象必须包含result或error成员,但两个成员必须不能同时包含。

5.1错误对象

当一个rpc调用遇到错误时,返回的响应对象必须包含错误成员参数,并且为带有下列成员参数的对象:

code

使用数值表示该异常的错误类型。
必须为整数。

message

对该错误的简单描述字符串。
该描述应尽量限定在简短的一句话。

data

包含关于错误附加信息的基本类型或结构化类型。该成员可忽略。
该成员值由服务端定义(例如详细的错误信息,嵌套的错误等)。

-32768至-32000为保留的预定义错误代码。在该范围内的错误代码不能被明确定义,保留下列以供将来使用。错误代码基本与XML-RPC建议的一样,url:
http://xmlrpc-epi.sourceforge.net/specs/rfc.fault_codes.php

code message meaning
-32700 Parse error语法解析错误 服务端接收到无效的json。该错误发送于服务器尝试解析json文本
-32600 Invalid Request无效请求 发送的json不是一个有效的请求对象。
-32601 Method not found找不到方法 该方法不存在或无效
-32602 Invalid params无效的参数 无效的方法参数。
-32603 Internal error内部错误 JSON-RPC内部错误。
-32000 to -32099 Server error服务端错误 预留用于自定义的服务器错误。

除此之外剩余的错误类型代码可供应用程序作为自定义错误。

6.批量调用

当需要同时发送多个请求对象时,客户端可以发送一个包含所有请求对象的数组。

当批量调用的所有请求对象处理完成时,服务端则需要返回一个包含相对应的响应对象数组。每个响应对象都应对应每个请求对象,除非是通知的请求对象。服务端可以并发的,以任意顺序和任意宽度的并行性来处理这些批量调用。

这些相应的响应对象可以任意顺序的包含在返回的数组中,而客户端应该是基于各个响应对象中的id成员来匹配对应的请求对象。

若批量调用的rpc操作本身非一个有效json或一个至少包含一个值的数组,则服务端返回的将单单是一个响应对象而非数组。若批量调用没有需要返回的响应对象,则服务端不需要返回任何结果且必须不能返回一个空数组给客户端。

7.示例

Syntax:

--> data sent to Server
<-- data sent to Client

带索引数组参数的rpc调用:

--> {"jsonrpc": "2.0", "method": "subtract", "params": [42, 23], "id": 1}
<-- {"jsonrpc": "2.0", "result": 19, "id": 1}

--> {"jsonrpc": "2.0", "method": "subtract", "params": [23, 42], "id": 2}
<-- {"jsonrpc": "2.0", "result": -19, "id": 2}

带关联数组参数的rpc调用:

--> {"jsonrpc": "2.0", "method": "subtract", "params": {"subtrahend": 23, "minuend": 42}, "id": 3}
<-- {"jsonrpc": "2.0", "result": 19, "id": 3}

--> {"jsonrpc": "2.0", "method": "subtract", "params": {"minuend": 42, "subtrahend": 23}, "id": 4}
<-- {"jsonrpc": "2.0", "result": 19, "id": 4}

通知:

--> {"jsonrpc": "2.0", "method": "update", "params": [1,2,3,4,5]}
--> {"jsonrpc": "2.0", "method": "foobar"}

不包含调用方法的rpc调用:

--> {"jsonrpc": "2.0", "method": "foobar", "id": "1"}
<-- {"jsonrpc": "2.0", "error": {"code": -32601, "message": "Method not found"}, "id": "1"}

包含无效json的rpc调用:

--> {"jsonrpc": "2.0", "method": "foobar, "params": "bar", "baz]
<-- {"jsonrpc": "2.0", "error": {"code": -32700, "message": "Parse error"}, "id": null}

包含无效请求对象的rpc调用:

--> {"jsonrpc": "2.0", "method": 1, "params": "bar"}
<-- {"jsonrpc": "2.0", "error": {"code": -32600, "message": "Invalid Request"}, "id": null}

包含无效json的rpc批量调用:

--> [
        {"jsonrpc": "2.0", "method": "sum", "params": [1,2,4], "id": "1"},
        {"jsonrpc": "2.0", "method"
    ]
<-- {"jsonrpc": "2.0", "error": {"code": -32700, "message": "Parse error"}, "id": null}

包含空数组的rpc调用:

--> []
<-- {"jsonrpc": "2.0", "error": {"code": -32600, "message": "Invalid Request"}, "id": null}

非空且无效的rpc批量调用:

--> [1]
<-- [
    {"jsonrpc": "2.0", "error": {"code": -32600, "message": "Invalid Request"}, "id": null}
    ]

无效的rpc批量调用:

--> [1,2,3]
<-- [
    {"jsonrpc": "2.0", "error": {"code": -32600, "message": "Invalid Request"}, "id": null},
    {"jsonrpc": "2.0", "error": {"code": -32600, "message": "Invalid Request"}, "id": null},
    {"jsonrpc": "2.0", "error": {"code": -32600, "message": "Invalid Request"}, "id": null}
    ]

rpc批量调用:

--> [
    {"jsonrpc": "2.0", "method": "sum", "params": [1,2,4], "id": "1"},
    {"jsonrpc": "2.0", "method": "notify_hello", "params": [7]},
    {"jsonrpc": "2.0", "method": "subtract", "params": [42,23], "id": "2"},
    {"foo": "boo"},
    {"jsonrpc": "2.0", "method": "foo.get", "params": {"name": "myself"}, "id": "5"},
    {"jsonrpc": "2.0", "method": "get_data", "id": "9"} 
    ]
<-- [
    {"jsonrpc": "2.0", "result": 7, "id": "1"},
    {"jsonrpc": "2.0", "result": 19, "id": "2"},
    {"jsonrpc": "2.0", "error": {"code": -32600, "message": "Invalid Request"}, "id": null},
    {"jsonrpc": "2.0", "error": {"code": -32601, "message": "Method not found"}, "id": "5"},
    {"jsonrpc": "2.0", "result": ["hello", 5], "id": "9"}
    ]

所有都为通知的rpc批量调用:

--> [
    {"jsonrpc": "2.0", "method": "notify_sum", "params": [1,2,4]},
    {"jsonrpc": "2.0", "method": "notify_hello", "params": [7]}
]

<-- //Nothing is returned for all notification batches

7.扩展

以rpc开头的方法名预留作为系统扩展,且必须不能用于其他地方。每个系统扩展都应该有相关规范文档,所有系统扩展都应是可选的。


Copyright (C) 2007-2010 by the JSON-RPC Working Group

This document and translations of it may be used to implement JSON-RPC, it may be copied and furnished to others, and derivative works that comment on or otherwise explain it or assist in its implementation may be prepared, copied, published and distributed, in whole or in part, without restriction of any kind, provided that the above copyright notice and this paragraph are included on all such copies and derivative works. However, this document itself may not bemodified in any way.

com.facebook.stetho.inspector.jsonrpc.JsonRpcPeer的实例源码

com.facebook.stetho.inspector.jsonrpc.JsonRpcPeer的实例源码

项目:stetho-realm    文件:Database.java   
@Override
public void onPeerRegistered(JsonRpcPeer jsonRpcPeer) {
    for (File dir : dirs) {
        if (!dir.isDirectory() || !dir.canRead()) {
            continue;
        }
        for (File file : dir.listFiles()) {
            if (!file.isFile() || !file.canRead() || !namePattern.matcher(file.getName())
                .matches()) {
                continue;
            }
            final DatabaSEObject databaseParams = new DatabaSEObject();
            databaseParams.id = file.getAbsolutePath();
            databaseParams.name = file.getName();
            databaseParams.domain = packageName;
            databaseParams.version = "N/A";
            final AddDatabaseEvent eventParams = new AddDatabaseEvent();
            eventParams.database = databaseParams;
            jsonRpcPeer.invokeMethod("Database.addDatabase",eventParams,null);
        }
    }
}
项目:Stetho-Couchbase    文件:Database.java   
@ChromeDevtoolsMethod
@SuppressWarnings("unused")
public JsonRpcResult executesql(JsonRpcPeer peer,JSONObject params) {
    Timber.d("executesql: %s",String.valueOf(params));

    ExecutesqlResponse response = new ExecutesqlResponse();
    try {
        ExecutesqlRequest request = mObjectMapper.convertValue(params,ExecutesqlRequest.class);
        return mCouchbasePeerManager.executesql(request.databaseId,request.query);
    } catch (Exception e) {
        Timber.e(e.toString());
        Error error = new Error();
        error.code = 0;
        error.message = e.getMessage();
        response.sqlError = error;
        return response;
    }
}
项目:stetho    文件:Page.java   
private void sendWelcomeMessage(JsonRpcPeer peer) {
    Console.ConsoleMessage message = new Console.ConsoleMessage();
    message.source = Console.MessageSource.JAVASCRIPT;
    message.level = Console.MessageLevel.LOG;
    message.text =
// Note: not using Android resources so we can maintain .jar distribution for Now.
"_____/\\\\\\\\\\\\\\\\\\\\\\_______________________________________________/\\\\\\_______________________\n" +
" ___/\\\\\\/////////\\\\\\____________________________________________\\/\\\\\\_______________________\n" +
"  __\\//\\\\\\______\\///______/\\\\\\_________________________/\\\\\\______\\/\\\\\\_______________________\n" +
"   ___\\////\\\\\\__________/\\\\\\\\\\\\\\\\\\\\\\_____/\\\\\\\\\\\\\\\\___/\\\\\\\\\\\\\\\\\\\\\\_\\/\\\\\\_____________/\\\\\\\\\\____\n" +
"    ______\\////\\\\\\______\\////\\\\\\////____/\\\\\\/////\\\\\\_\\////\\\\\\////__\\/\\\\\\\\\\\\\\\\\\\\____/\\\\\\///\\\\\\__\n" +
"     _________\\////\\\\\\______\\/\\\\\\_______/\\\\\\\\\\\\\\\\\\\\\\_____\\/\\\\\\______\\/\\\\\\/////\\\\\\__/\\\\\\__\\//\\\\\\_\n" +
"      __/\\\\\\______\\//\\\\\\_____\\/\\\\\\_/\\\\__\\//\\\\///////______\\/\\\\\\_/\\\\__\\/\\\\\\___\\/\\\\\\_\\//\\\\\\__/\\\\\\__\n" +
"       _\\///\\\\\\\\\\\\\\\\\\\\\\/______\\//\\\\\\\\\\____\\//\\\\\\\\\\\\\\\\\\\\____\\//\\\\\\\\\\___\\/\\\\\\___\\/\\\\\\__\\///\\\\\\\\\\/___\n" +
"        ___\\///////////_________\\/////______\\//////////______\\/////____\\///____\\///_____\\/////_____\n" +
"         Welcome to Stetho\n" +
"          Attached to " + ProcessUtil.getProcessName() + "\n";
    Console.MessageAddedRequest messageAddedRequest = new Console.MessageAddedRequest();
    messageAddedRequest.message = message;
    peer.invokeMethod("Console.messageAdded",messageAddedRequest,null /* callback */);
  }
项目:stetho    文件:DOM.java   
@ChromeDevtoolsMethod
public void highlightNode(JsonRpcPeer peer,JSONObject params) {
  final HighlightNodeRequest request =
    mObjectMapper.convertValue(params,HighlightNodeRequest.class);
  if (request.nodeId == null) {
    LogUtil.w("DOM.highlightNode was not given a nodeId; JS objectId is not supported");
    return;
  }

  final RGBAColor contentColor = request.highlightConfig.contentColor;
  if (contentColor == null) {
    LogUtil.w("DOM.highlightNode was not given a color to highlight with");
    return;
  }

  mDocument.postAndWait(new Runnable() {
    @Override
    public void run() {
      Object element = mDocument.getElementForNodeId(request.nodeId);
      if (element != null) {
        mDocument.highlightElement(element,contentColor.getColor());
      }
    }
  });
}
项目:stetho    文件:DOM.java   
@ChromeDevtoolsMethod
public void setAttributesAsText(JsonRpcPeer peer,JSONObject params) {
  final SetAttributesAsTextRequest request = mObjectMapper.convertValue(
      params,SetAttributesAsTextRequest.class);

  mDocument.postAndWait(new Runnable() {
    @Override
    public void run() {
      Object element = mDocument.getElementForNodeId(request.nodeId);
      if (element != null) {
        mDocument.setAttributesAsText(element,request.text);
      }
    }
  });
}
项目:stetho    文件:DOM.java   
@ChromeDevtoolsMethod
public GetSearchResultsResponse getSearchResults(JsonRpcPeer peer,JSONObject params) {
  final GetSearchResultsRequest request = mObjectMapper.convertValue(
      params,GetSearchResultsRequest.class);

  if (request.searchId == null) {
    LogUtil.w("searchId may not be null");
    return null;
  }

  final List<Integer> results = mSearchResults.get(request.searchId);

  if (results == null) {
    LogUtil.w("\"" + request.searchId + "\" is not a valid reference to a search result");
    return null;
  }

  final List<Integer> resultsRange = results.subList(request.fromIndex,request.toIndex);

  final GetSearchResultsResponse response = new GetSearchResultsResponse();
  response.nodeIds = resultsRange;

  return response;
}
项目:stetho    文件:Database.java   
@ChromeDevtoolsMethod
public JsonRpcResult getDatabaseTableNames(JsonRpcPeer peer,JSONObject params)
    throws JsonRpcException {
  GetDatabaseTableNamesRequest request = mObjectMapper.convertValue(params,GetDatabaseTableNamesRequest.class);

  String databaseId = request.databaseId;
  DatabaseDescriptorHolder holder =
      mPeerListener.getDatabaseDescriptorHolder(databaseId);

  try {
    GetDatabaseTableNamesResponse response = new GetDatabaseTableNamesResponse();
    response.tableNames = holder.driver.getTableNames(holder.descriptor);
    return response;
  } catch (sqliteException e) {
    throw new JsonRpcException(
        new JsonRpcError(
            JsonRpcError.ErrorCode.INVALID_REQUEST,e.toString(),null /* data */));
  }
}
项目:stetho    文件:Database.java   
@Override
protected synchronized void onPeerAdded(JsonRpcPeer peer) {
  for (int i = 0,N = mDatabaseHolders.size(); i < N; i++) {
    int id = mDatabaseHolders.keyAt(i);
    DatabaseDescriptorHolder holder = mDatabaseHolders.valueAt(i);

    Database.DatabaSEObject databaseParams = new Database.DatabaSEObject();
    databaseParams.id = String.valueOf(id);
    databaseParams.name = holder.descriptor.name();
    databaseParams.domain = holder.driver.getContext().getPackageName();
    databaseParams.version = "N/A";
    Database.AddDatabaseEvent eventParams = new Database.AddDatabaseEvent();
    eventParams.database = databaseParams;
    peer.invokeMethod("Database.addDatabase",null /* callback */);
  }
}
项目:stetho    文件:DOMStorage.java   
@ChromeDevtoolsMethod
public JsonRpcResult getDOMStorageItems(JsonRpcPeer peer,JSONObject params)
    throws JSONException {
  StorageId storage = mObjectMapper.convertValue(
      params.getJSONObject("storageId"),StorageId.class);

  ArrayList<List<String>> entries = new ArrayList<List<String>>();
  String prefTag = storage.securityOrigin;
  if (storage.isLocalStorage) {
    SharedPreferences prefs = mContext.getSharedPreferences(prefTag,Context.MODE_PRIVATE);
    for (Map.Entry<String,?> prefsEntry : prefs.getAll().entrySet()) {
      ArrayList<String> entry = new ArrayList<String>(2);
      entry.add(prefsEntry.getKey());
      entry.add(SharedPreferencesHelper.valuetoString(prefsEntry.getValue()));
      entries.add(entry);
    }
  }

  GetDOMStorageItemsResult result = new GetDOMStorageItemsResult();
  result.entries = entries;
  return result;
}
项目:stetho-realm    文件:Database.java   
@ChromeDevtoolsMethod
public JsonRpcResult getDatabaseTableNames(JsonRpcPeer peer,JSONObject params) {
    final SharedRealm realm = getRealm(
        objectMapper.convertValue(params,GetDatabaseTableNamesRequest.class).databaseId);
    final int size = (int) realm.size();
    final List<String> tableNames = new ArrayList<>(size);
    for (int i = 0; i < size; ++i) {
        tableNames.add(realm.getTableName(i));
    }

    final GetDatabaseTableNamesResponse response = new GetDatabaseTableNamesResponse();
    response.tableNames = tableNames;
    return response;
}
项目:stetho-realm    文件:Database.java   
@Override
public void onPeerUnregistered(JsonRpcPeer jsonRpcPeer) {
    for (Map.Entry<String,SharedRealm> entry : realms.entrySet()) {
        entry.getValue().close();
    }
    realms.clear();
}
项目:StethoRealm    文件:RealmPeerManager.java   
private void bootstrapNewPeer(JsonRpcPeer peer) {
    List<File> potentialDatabaseFiles = realmFilesProvider.getDatabaseFiles();
    Iterable<File> tidiedList = tidyDatabaseList(potentialDatabaseFiles);
    for (File database : tidiedList) {
        Database.DatabaSEObject databaseParams = new Database.DatabaSEObject();
        databaseParams.id = database.getPath();
        databaseParams.name = database.getName();
        databaseParams.domain = packageName;
        databaseParams.version = "N/A";
        Database.AddDatabaseEvent eventParams = new Database.AddDatabaseEvent();
        eventParams.database = databaseParams;

        peer.invokeMethod("Database.addDatabase",null /* callback */);
    }
}
项目:StethoRealm    文件:Database.java   
@ChromeDevtoolsMethod
@SuppressWarnings("unused")
public JsonRpcResult getDatabaseTableNames(JsonRpcPeer peer,JSONObject params) {
    GetDatabaseTableNamesRequest request = objectMapper.convertValue(params,GetDatabaseTableNamesRequest.class);
    GetDatabaseTableNamesResponse response = new GetDatabaseTableNamesResponse();
    response.tableNames = realmPeerManager.getDatabaseTableNames(request.databaseId,withMetaTables);
    return response;
}
项目:Stetho-Couchbase    文件:CouchbasePeerManager.java   
private void setupPeer(JsonRpcPeer peer) {
    List<String> potentialDatabases = mManager.getAllDatabaseNames();
    for (String database : potentialDatabases) {
        Timber.d("Datebase Name: %s",database);
        Database.DatabaSEObject databaseParams = new Database.DatabaSEObject();
        databaseParams.id = database;
        databaseParams.name = database;
        databaseParams.domain = mPackageName;
        databaseParams.version = "N/A";
        Database.AddDatabaseEvent eventParams = new Database.AddDatabaseEvent();
        eventParams.database = databaseParams;

        peer.invokeMethod("Database.addDatabase",null /* callback */);
    }
}
项目:Stetho-Couchbase    文件:Database.java   
@ChromeDevtoolsMethod
@SuppressWarnings("unused")
public JsonRpcResult getDatabaseTableNames(JsonRpcPeer peer,JSONObject params) {
    Timber.d("getAllDocumentIds: %s",String.valueOf(params));
    GetDatabaseTableNamesRequest request = mObjectMapper.convertValue(params,GetDatabaseTableNamesRequest.class);
    GetDatabaseTableNamesResponse response = new GetDatabaseTableNamesResponse();
    response.tableNames = mCouchbasePeerManager.getAllDocumentIds(request.databaseId);
    return response;
}
项目:stetho    文件:Page.java   
private void notifyExecutionContexts(JsonRpcPeer peer) {
  ExecutionContextDescription context = new ExecutionContextDescription();
  context.frameId = "1";
  context.id = 1;
  ExecutionContextCreatedParams params = new ExecutionContextCreatedParams();
  params.context = context;
  peer.invokeMethod("Runtime.executionContextCreated",params,null /* callback */);
}
项目:stetho    文件:Page.java   
@ChromeDevtoolsMethod
public JsonRpcResult getResourceTree(JsonRpcPeer peer,JSONObject params) {
  // The DOMStorage module expects one key/value store per "security origin" which has a 1:1
  // relationship with resource tree frames.
  List<String> prefsTags = SharedPreferencesHelper.getSharedPreferenceTags(mContext);
  Iterator<String> prefsTagsIter = prefsTags.iterator();

  FrameResourceTree tree = createSimpleFrameResourceTree(
      "1",null /* parentId */,"Stetho",prefsTagsIter.hasNext() ? prefsTagsIter.next() : "");
  if (tree.childFrames == null) {
    tree.childFrames = new ArrayList<FrameResourceTree>();
  }

  int nextChildFrameId = 1;
  while (prefsTagsIter.hasNext()) {
    String frameId = "1." + (nextChildFrameId++);
    String prefsTag = prefsTagsIter.next();
    FrameResourceTree child = createSimpleFrameResourceTree(
        frameId,"1","Child #" + frameId,prefsTag);
    tree.childFrames.add(child);
  }

  GetResourceTreeParams resultParams = new GetResourceTreeParams();
  resultParams.frameTree = tree;
  return resultParams;
}
项目:stetho    文件:Page.java   
@ChromeDevtoolsMethod
public void startScreencast(final JsonRpcPeer peer,JSONObject params) {
  final StartScreencastRequest request = mObjectMapper.convertValue(
      params,StartScreencastRequest.class);
  if (mScreencastdispatcher == null) {
    mScreencastdispatcher = new Screencastdispatcher();
    mScreencastdispatcher.startScreencast(peer,request);
  }
}
项目:stetho    文件:Page.java   
@ChromeDevtoolsMethod
public void stopScreencast(JsonRpcPeer peer,JSONObject params) {
  if (mScreencastdispatcher != null) {
    mScreencastdispatcher.stopScreencast();
    mScreencastdispatcher = null;
  }
}
项目:stetho    文件:DOM.java   
@ChromeDevtoolsMethod
public JsonRpcResult getDocument(JsonRpcPeer peer,JSONObject params) {
  final GetDocumentResponse result = new GetDocumentResponse();

  result.root = mDocument.postAndWait(new UncheckedCallable<Node>() {
    @Override
    public Node call() {
      Object element = mDocument.getRootElement();
      return createNodeForElement(element,mDocument.getDocumentView(),null);
    }
  });

  return result;
}
项目:stetho    文件:DOM.java   
@ChromeDevtoolsMethod
public void hideHighlight(JsonRpcPeer peer,JSONObject params) {
  mDocument.postAndWait(new Runnable() {
    @Override
    public void run() {
      mDocument.hideHighlight();
    }
  });
}
项目:stetho    文件:DOM.java   
@ChromeDevtoolsMethod
public ResolveNodeResponse resolveNode(JsonRpcPeer peer,JSONObject params)
    throws JsonRpcException {
  final ResolveNodeRequest request = mObjectMapper.convertValue(params,ResolveNodeRequest.class);

  final Object element = mDocument.postAndWait(new UncheckedCallable<Object>() {
    @Override
    public Object call() {
      return mDocument.getElementForNodeId(request.nodeId);
    }
  });

  if (element == null) {
    throw new JsonRpcException(
        new JsonRpcError(
            JsonRpcError.ErrorCode.INVALID_ParaMS,"No kNown nodeId=" + request.nodeId,null /* data */));
  }

  int mappedobjectId = Runtime.mapObject(peer,element);

  Runtime.RemoteObject remoteObject = new Runtime.RemoteObject();
  remoteObject.type = Runtime.ObjectType.OBJECT;
  remoteObject.subtype = Runtime.ObjectSubType.NODE;
  remoteObject.className = element.getClass().getName();
  remoteObject.value = null; // not a primitive
  remoteObject.description = null; // not sure what this does...
  remoteObject.objectId = String.valueOf(mappedobjectId);
  ResolveNodeResponse response = new ResolveNodeResponse();
  response.object = remoteObject;

  return response;
}
项目:stetho    文件:DOM.java   
@ChromeDevtoolsMethod
public void setInspectModeEnabled(JsonRpcPeer peer,JSONObject params) {
  final SetInspectModeEnabledRequest request = mObjectMapper.convertValue(
      params,SetInspectModeEnabledRequest.class);

  mDocument.postAndWait(new Runnable() {
    @Override
    public void run() {
      mDocument.setInspectModeEnabled(request.enabled);
    }
  });
}
项目:stetho    文件:DOM.java   
@ChromeDevtoolsMethod
public PerformSearchResponse performSearch(JsonRpcPeer peer,final JSONObject params) {
  final PerformSearchRequest request = mObjectMapper.convertValue(
      params,PerformSearchRequest.class);

  final ArrayListAccumulator<Integer> resultNodeIds = new ArrayListAccumulator<>();

  mDocument.postAndWait(new Runnable() {
    @Override
    public void run() {
      mDocument.findMatchingElements(request.query,resultNodeIds);
    }
  });

  // Each search action has a unique ID so that
  // it can be queried later.
  final String searchId = String.valueOf(mResultCounter.getAndIncrement());

  mSearchResults.put(searchId,resultNodeIds);

  final PerformSearchResponse response = new PerformSearchResponse();
  response.searchId = searchId;
  response.resultCount = resultNodeIds.size();

  return response;
}
项目:stetho    文件:DOM.java   
@ChromeDevtoolsMethod
public void discardSearchResults(JsonRpcPeer peer,JSONObject params) {
  final discardSearchResultsRequest request = mObjectMapper.convertValue(
    params,discardSearchResultsRequest.class);

  if (request.searchId != null) {
    mSearchResults.remove(request.searchId);
  }
}
项目:stetho    文件:DOMStorage.java   
@ChromeDevtoolsMethod
public void removeDOMStorageItem(JsonRpcPeer peer,JSONObject params) throws JSONException {
  StorageId storage = mObjectMapper.convertValue(
      params.getJSONObject("storageId"),StorageId.class);
  String key = params.getString("key");

  if (storage.isLocalStorage) {
    SharedPreferences prefs = mContext.getSharedPreferences(
        storage.securityOrigin,Context.MODE_PRIVATE);
    prefs.edit().remove(key).apply();
  }
}
项目:stetho    文件:CSS.java   
@ChromeDevtoolsMethod
public JsonRpcResult getComputedStyleForNode(JsonRpcPeer peer,JSONObject params) {
  final GetComputedStyleForNodeRequest request = mObjectMapper.convertValue(
      params,GetComputedStyleForNodeRequest.class);

  final GetComputedStyleForNodeResult result = new GetComputedStyleForNodeResult();
  result.computedStyle = new ArrayList<>();

  mDocument.postAndWait(new Runnable() {
    @Override
    public void run() {
      Object element = mDocument.getElementForNodeId(request.nodeId);

      if (element == null) {
        LogUtil.e("Tried to get the style of an element that does not exist,using nodeid=" +
            request.nodeId);

        return;
      }

      mDocument.getElementComputedStyles(
          element,new ComputedStyleAccumulator() {
            @Override
            public void store(String name,String value) {
              final CSSComputedStyleProperty property = new CSSComputedStyleproperty();
              property.name = name;
              property.value = value;
              result.computedStyle.add(property);
            }
          });
    }
  });

  return result;
}
项目:stetho    文件:Runtime.java   
@Nonnull
private static synchronized Session getSession(final JsonRpcPeer peer) {
  Session session = sSessions.get(peer);
  if (session == null) {
    session = new Session();
    sSessions.put(peer,session);
    peer.registerdisconnectReceiver(new disconnectReceiver() {
      @Override
      public void ondisconnect() {
        sSessions.remove(peer);
      }
    });
  }
  return session;
}
项目:stetho    文件:Runtime.java   
@ChromeDevtoolsMethod
public CallFunctionOnResponse callFunctionOn(JsonRpcPeer peer,JSONObject params)
    throws JsonRpcException {
  CallFunctionOnRequest args = mObjectMapper.convertValue(params,CallFunctionOnRequest.class);

  Session session = getSession(peer);
  Object object = session.getobjectOrThrow(args.objectId);

  // The DevTools UI thinks it can run arbitrary JavaScript against us in order to figure out
  // the class structure of an object.  That obvIoUsly won't fly,and there's no way to
  // translate without building a crude JavaScript parser so let's just go ahead and guess
  // what this function does by name.
  if (!args.functionDeclaration.startsWith("function protoList(")) {
    throw new JsonRpcException(
        new JsonRpcError(
            JsonRpcError.ErrorCode.INTERNAL_ERROR,"Expected protoList,got: " + args.functionDeclaration,null /* data */));
  }

  // Since this is really a function call we have to create this fake object to hold the
  // "result" of the function.
  ObjectProtoContainer objectContainer = new ObjectProtoContainer(object);
  RemoteObject result = new RemoteObject();
  result.type = ObjectType.OBJECT;
  result.subtype = ObjectSubType.NODE;
  result.className = object.getClass().getName();
  result.description = getPropertyClassName(object);
  result.objectId = String.valueOf(session.getobjects().putObject(objectContainer));

  CallFunctionOnResponse response = new CallFunctionOnResponse();
  response.result = result;
  response.wasThrown = false;

  return response;
}
项目:stetho    文件:ChromePeerManager.java   
/**
 * Register a new peer,adding them to an internal list of receivers.
 *
 * @param peer
 * @return True if this is a newly registered peer; false if it was already registered.
 */
public synchronized boolean addPeer(JsonRpcPeer peer) {
  if (mReceivingPeers.containsKey(peer)) {
    return false;
  }

  disconnectReceiver disconnectReceiver = new UnregisterOndisconnect(peer);
  peer.registerdisconnectReceiver(disconnectReceiver);
  mReceivingPeers.put(peer,disconnectReceiver);
  mReceivingPeeRSSnapshot = null;
  if (mListener != null) {
    mListener.onPeerRegistered(peer);
  }
  return true;
}
项目:stetho    文件:ChromePeerManager.java   
/**
 * Unregister an existing peer.
 *
 * @param peer
 */
public synchronized void removePeer(JsonRpcPeer peer) {
  if (mReceivingPeers.remove(peer) != null) {
    mReceivingPeeRSSnapshot = null;
    if (mListener != null) {
      mListener.onPeerUnregistered(peer);
    }
  }
}
项目:stetho    文件:ChromePeerManager.java   
private synchronized JsonRpcPeer[] getReceivingPeeRSSnapshot() {
  if (mReceivingPeeRSSnapshot == null) {
    mReceivingPeeRSSnapshot = mReceivingPeers.keySet().toArray(
        new JsonRpcPeer[mReceivingPeers.size()]);
  }
  return mReceivingPeeRSSnapshot;
}
项目:stetho    文件:ChromePeerManager.java   
private void sendMessagetoPeers(String method,Object params,@Nullable PendingRequestCallback callback) {
  JsonRpcPeer[] peers = getReceivingPeeRSSnapshot();
  for (JsonRpcPeer peer : peers) {
    try {
      peer.invokeMethod(method,callback);
    } catch (NotYetConnectedException e) {
      LogRedirector.e(TAG,"Error delivering data to Chrome",e);
    }
  }
}
项目:stetho    文件:PeersRegisteredListener.java   
@Override
public final void onPeerRegistered(JsonRpcPeer peer) {
  if (mPeers.incrementAndGet() == 1) {
    onFirstPeerRegistered();
  }
  onPeerAdded(peer);
}
项目:stetho    文件:PeersRegisteredListener.java   
@Override
public final void onPeerUnregistered(JsonRpcPeer peer) {
  if (mPeers.decrementAndGet() == 0) {
    onLastPeerUnregistered();
  }
  onPeerRemoved(peer);
}
项目:stetho    文件:Methoddispatcher.java   
public JSONObject invoke(JsonRpcPeer peer,@Nullable JSONObject params)
    throws InvocationTargetException,illegalaccessexception,JSONException,JsonRpcException {
  Object internalResult = mMethod.invoke(mInstance,peer,params);
  if (internalResult == null || internalResult instanceof EmptyResult) {
    return new JSONObject();
  } else {
    JsonRpcResult convertableResult = (JsonRpcResult)internalResult;
    return mObjectMapper.convertValue(convertableResult,JSONObject.class);
  }
}
项目:stetho    文件:Methoddispatcher.java   
/**
 * Determines if the method is a {@link ChromeDevtoolsMethod},and validates accordingly
 * if it is.
 *
 * @throws IllegalArgumentException Thrown if it is a {@link ChromeDevtoolsMethod} but
 *     it otherwise fails to satisfy requirements.
 */
private static boolean isDevtoolsMethod(Method method) throws IllegalArgumentException {
  if (!method.isAnnotationPresent(ChromeDevtoolsMethod.class)) {
    return false;
  } else {
    Class<?> args[] = method.getParameterTypes();
    String methodName = method.getDeclaringClass().getSimpleName() + "." + method.getName();
    Util.throwIfNot(args.length == 2,"%s: expected 2 args,got %s",methodName,args.length);
    Util.throwIfNot(args[0].equals(JsonRpcPeer.class),"%s: expected 1st arg of JsonRpcPeer,args[0].getName());
    Util.throwIfNot(args[1].equals(JSONObject.class),"%s: expected 2nd arg of JSONObject,args[1].getName());

    Class<?> returnType = method.getReturnType();
    if (!returnType.equals(void.class)) {
      Util.throwIfNot(JsonRpcResult.class.isAssignableFrom(returnType),"%s: expected JsonRpcResult return type,returnType.getName());
    }
    return true;
  }
}
项目:stetho    文件:Screencastdispatcher.java   
public void startScreencast(JsonRpcPeer peer,Page.StartScreencastRequest request) {
  LogUtil.d("Starting screencast");
  mRequest = request;
  mHandlerThread = new HandlerThread("Screencast Thread");
  mHandlerThread.start();
  mPeer = peer;
  mIsRunning = true;
  mStream = new ByteArrayOutputStream();
  mBackgroundHandler = new Handler(mHandlerThread.getLooper());
  mMainHandler.postDelayed(mBitmapFetchRunnable,FRAME_DELAY);
}
项目:stetho    文件:ChromeDevtoolsServer.java   
@Override
public void onClose(SimpleSession session,int code,String reasonPhrase) {
  LogRedirector.d(TAG,"onClose: reason=" + code + " " + reasonPhrase);

  JsonRpcPeer peer = mPeers.remove(session);
  if (peer != null) {
    peer.invokedisconnectReceivers();
  }
}
项目:stetho    文件:ChromeDevtoolsServer.java   
private void handleRemoteMessage(JsonRpcPeer peer,String message)
    throws IOException,MessageHandlingException,JSONException {
  // Parse as a generic JSONObject first since we don't kNow if this is a request or response.
  JSONObject messageNode = new JSONObject(message);
  if (messageNode.has("method")) {
    handleRemoteRequest(peer,messageNode);
  } else if (messageNode.has("result")) {
    handleRemoteResponse(peer,messageNode);
  } else {
    throw new MessageHandlingException("Improper JSON-RPC message: " + message);
  }
}

com.facebook.stetho.inspector.jsonrpc.JsonRpcResult的实例源码

com.facebook.stetho.inspector.jsonrpc.JsonRpcResult的实例源码

项目:Stetho-Couchbase    文件:Database.java   
@ChromeDevtoolsMethod
@SuppressWarnings("unused")
public JsonRpcResult executesql(JsonRpcPeer peer,JSONObject params) {
    Timber.d("executesql: %s",String.valueOf(params));

    ExecutesqlResponse response = new ExecutesqlResponse();
    try {
        ExecutesqlRequest request = mObjectMapper.convertValue(params,ExecutesqlRequest.class);
        return mCouchbasePeerManager.executesql(request.databaseId,request.query);
    } catch (Exception e) {
        Timber.e(e.toString());
        Error error = new Error();
        error.code = 0;
        error.message = e.getMessage();
        response.sqlError = error;
        return response;
    }
}
项目:stetho    文件:Database.java   
@ChromeDevtoolsMethod
public JsonRpcResult getDatabaseTableNames(JsonRpcPeer peer,JSONObject params)
    throws JsonRpcException {
  GetDatabaseTableNamesRequest request = mObjectMapper.convertValue(params,GetDatabaseTableNamesRequest.class);

  String databaseId = request.databaseId;
  DatabaseDescriptorHolder holder =
      mPeerListener.getDatabaseDescriptorHolder(databaseId);

  try {
    GetDatabaseTableNamesResponse response = new GetDatabaseTableNamesResponse();
    response.tableNames = holder.driver.getTableNames(holder.descriptor);
    return response;
  } catch (sqliteException e) {
    throw new JsonRpcException(
        new JsonRpcError(
            JsonRpcError.ErrorCode.INVALID_REQUEST,e.toString(),null /* data */));
  }
}
项目:stetho    文件:DOMStorage.java   
@ChromeDevtoolsMethod
public JsonRpcResult getDOMStorageItems(JsonRpcPeer peer,JSONObject params)
    throws JSONException {
  StorageId storage = mObjectMapper.convertValue(
      params.getJSONObject("storageId"),StorageId.class);

  ArrayList<List<String>> entries = new ArrayList<List<String>>();
  String prefTag = storage.securityOrigin;
  if (storage.isLocalStorage) {
    SharedPreferences prefs = mContext.getSharedPreferences(prefTag,Context.MODE_PRIVATE);
    for (Map.Entry<String,?> prefsEntry : prefs.getAll().entrySet()) {
      ArrayList<String> entry = new ArrayList<String>(2);
      entry.add(prefsEntry.getKey());
      entry.add(SharedPreferencesHelper.valuetoString(prefsEntry.getValue()));
      entries.add(entry);
    }
  }

  GetDOMStorageItemsResult result = new GetDOMStorageItemsResult();
  result.entries = entries;
  return result;
}
项目:stetho-realm    文件:Database.java   
@ChromeDevtoolsMethod
public JsonRpcResult getDatabaseTableNames(JsonRpcPeer peer,JSONObject params) {
    final SharedRealm realm = getRealm(
        objectMapper.convertValue(params,GetDatabaseTableNamesRequest.class).databaseId);
    final int size = (int) realm.size();
    final List<String> tableNames = new ArrayList<>(size);
    for (int i = 0; i < size; ++i) {
        tableNames.add(realm.getTableName(i));
    }

    final GetDatabaseTableNamesResponse response = new GetDatabaseTableNamesResponse();
    response.tableNames = tableNames;
    return response;
}
项目:StethoRealm    文件:Database.java   
@ChromeDevtoolsMethod
@SuppressWarnings("unused")
public JsonRpcResult getDatabaseTableNames(JsonRpcPeer peer,JSONObject params) {
    GetDatabaseTableNamesRequest request = objectMapper.convertValue(params,GetDatabaseTableNamesRequest.class);
    GetDatabaseTableNamesResponse response = new GetDatabaseTableNamesResponse();
    response.tableNames = realmPeerManager.getDatabaseTableNames(request.databaseId,withMetaTables);
    return response;
}
项目:Stetho-Couchbase    文件:Database.java   
@ChromeDevtoolsMethod
@SuppressWarnings("unused")
public JsonRpcResult getDatabaseTableNames(JsonRpcPeer peer,JSONObject params) {
    Timber.d("getAllDocumentIds: %s",String.valueOf(params));
    GetDatabaseTableNamesRequest request = mObjectMapper.convertValue(params,GetDatabaseTableNamesRequest.class);
    GetDatabaseTableNamesResponse response = new GetDatabaseTableNamesResponse();
    response.tableNames = mCouchbasePeerManager.getAllDocumentIds(request.databaseId);
    return response;
}
项目:stetho    文件:Page.java   
@ChromeDevtoolsMethod
public JsonRpcResult getResourceTree(JsonRpcPeer peer,JSONObject params) {
  // The DOMStorage module expects one key/value store per "security origin" which has a 1:1
  // relationship with resource tree frames.
  List<String> prefsTags = SharedPreferencesHelper.getSharedPreferenceTags(mContext);
  Iterator<String> prefsTagsIter = prefsTags.iterator();

  FrameResourceTree tree = createSimpleFrameResourceTree(
      "1",null /* parentId */,"Stetho",prefsTagsIter.hasNext() ? prefsTagsIter.next() : "");
  if (tree.childFrames == null) {
    tree.childFrames = new ArrayList<FrameResourceTree>();
  }

  int nextChildFrameId = 1;
  while (prefsTagsIter.hasNext()) {
    String frameId = "1." + (nextChildFrameId++);
    String prefsTag = prefsTagsIter.next();
    FrameResourceTree child = createSimpleFrameResourceTree(
        frameId,"1","Child #" + frameId,prefsTag);
    tree.childFrames.add(child);
  }

  GetResourceTreeParams resultParams = new GetResourceTreeParams();
  resultParams.frameTree = tree;
  return resultParams;
}
项目:stetho    文件:DOM.java   
@ChromeDevtoolsMethod
public JsonRpcResult getDocument(JsonRpcPeer peer,JSONObject params) {
  final GetDocumentResponse result = new GetDocumentResponse();

  result.root = mDocument.postAndWait(new UncheckedCallable<Node>() {
    @Override
    public Node call() {
      Object element = mDocument.getRootElement();
      return createNodeForElement(element,mDocument.getDocumentView(),null);
    }
  });

  return result;
}
项目:stetho    文件:CSS.java   
@ChromeDevtoolsMethod
public JsonRpcResult getComputedStyleForNode(JsonRpcPeer peer,JSONObject params) {
  final GetComputedStyleForNodeRequest request = mObjectMapper.convertValue(
      params,GetComputedStyleForNodeRequest.class);

  final GetComputedStyleForNodeResult result = new GetComputedStyleForNodeResult();
  result.computedStyle = new ArrayList<>();

  mDocument.postAndWait(new Runnable() {
    @Override
    public void run() {
      Object element = mDocument.getElementForNodeId(request.nodeId);

      if (element == null) {
        LogUtil.e("Tried to get the style of an element that does not exist,using nodeid=" +
            request.nodeId);

        return;
      }

      mDocument.getElementComputedStyles(
          element,new ComputedStyleAccumulator() {
            @Override
            public void store(String name,String value) {
              final CSSComputedStyleProperty property = new CSSComputedStyleproperty();
              property.name = name;
              property.value = value;
              result.computedStyle.add(property);
            }
          });
    }
  });

  return result;
}
项目:stetho    文件:Methoddispatcher.java   
public JSONObject invoke(JsonRpcPeer peer,@Nullable JSONObject params)
    throws InvocationTargetException,illegalaccessexception,JSONException,JsonRpcException {
  Object internalResult = mMethod.invoke(mInstance,peer,params);
  if (internalResult == null || internalResult instanceof EmptyResult) {
    return new JSONObject();
  } else {
    JsonRpcResult convertableResult = (JsonRpcResult)internalResult;
    return mObjectMapper.convertValue(convertableResult,JSONObject.class);
  }
}
项目:stetho    文件:Methoddispatcher.java   
/**
 * Determines if the method is a {@link ChromeDevtoolsMethod},and validates accordingly
 * if it is.
 *
 * @throws IllegalArgumentException Thrown if it is a {@link ChromeDevtoolsMethod} but
 *     it otherwise fails to satisfy requirements.
 */
private static boolean isDevtoolsMethod(Method method) throws IllegalArgumentException {
  if (!method.isAnnotationPresent(ChromeDevtoolsMethod.class)) {
    return false;
  } else {
    Class<?> args[] = method.getParameterTypes();
    String methodName = method.getDeclaringClass().getSimpleName() + "." + method.getName();
    Util.throwIfNot(args.length == 2,"%s: expected 2 args,got %s",methodName,args.length);
    Util.throwIfNot(args[0].equals(JsonRpcPeer.class),"%s: expected 1st arg of JsonRpcPeer,args[0].getName());
    Util.throwIfNot(args[1].equals(JSONObject.class),"%s: expected 2nd arg of JSONObject,args[1].getName());

    Class<?> returnType = method.getReturnType();
    if (!returnType.equals(void.class)) {
      Util.throwIfNot(JsonRpcResult.class.isAssignableFrom(returnType),"%s: expected JsonRpcResult return type,returnType.getName());
    }
    return true;
  }
}
项目:stetho    文件:Worker.java   
@ChromeDevtoolsMethod
public JsonRpcResult canInspectWorkers(JsonRpcPeer peer,JSONObject params) {
  return new SimpleBooleanResult(true);
}
项目:stetho    文件:Page.java   
@ChromeDevtoolsMethod
public JsonRpcResult canScreencast(JsonRpcPeer peer,JSONObject params) {
  return new SimpleBooleanResult(true);
}
项目:stetho    文件:Page.java   
@ChromeDevtoolsMethod
public JsonRpcResult hasTouchInputs(JsonRpcPeer peer,JSONObject params) {
  return new SimpleBooleanResult(false);
}
项目:stetho    文件:HeapProfiler.java   
@ChromeDevtoolsMethod
public JsonRpcResult getProfileHeaders(JsonRpcPeer peer,JSONObject params) {
  ProfileHeaderResponse response = new ProfileHeaderResponse();
  response.headers = Collections.emptyList();
  return response;
}
项目:stetho    文件:Debugger.java   
@ChromeDevtoolsMethod
public JsonRpcResult canSetScriptSource(JsonRpcPeer peer,JSONObject params) {
  return new SimpleBooleanResult(false);
}
项目:stetho    文件:Profiler.java   
@ChromeDevtoolsMethod
public JsonRpcResult getProfileHeaders(JsonRpcPeer peer,JSONObject params) {
  ProfileHeaderResponse response = new ProfileHeaderResponse();
  response.headers = Collections.emptyList();
  return response;
}
项目:stetho    文件:Runtime.java   
@ChromeDevtoolsMethod
public JsonRpcResult evaluate(JsonRpcPeer peer,JSONObject params) {
  return getSession(peer).evaluate(mReplFactory,params);
}
项目:stetho    文件:Runtime.java   
@ChromeDevtoolsMethod
public JsonRpcResult getProperties(JsonRpcPeer peer,JSONObject params) throws JsonRpcException {
  return getSession(peer).getProperties(params);
}

Django JSON-RPC

Django JSON-RPC

Django JSON-RPC https://github.com/samuraisam/django-json-rpc

Travis Build Status PyPI version

A basic JSON-RPC Implementation for your Django-powered sites.

Features:

  • Simple, pythonic API</li>
  • Support for Django authentication</li>
  • Support for all official Django Python/Version combinations</li>
  • Supports JSON-RPC 1.0, 1.1, 1.2 and 2.0 Spec
  • Proxy to test your JSON Service
  • Run-time type checking
  • Graphical JSON-RPC browser and web console
  • Provides system.describe

The basic API:

myproj/myapp/views.py

from jsonrpc import jsonrpc_method

@jsonrpc_method(''myapp.sayHello'')
def whats_the_time(request, name=''Lester''):
  return "Hello %s" % name

@jsonrpc_method(''myapp.gimmeThat'', authenticated=True)
def something_special(request, secret_data):
  return {''sauce'': [''authenticated'', ''sauce'']}

myproj/urls.py

from django.conf.urls.defaults import *
from jsonrpc import jsonrpc_site
import myproj.myapp.views # you must import the views that need connected

urlpatterns = patterns('''',
  url(r''^json/browse/'', ''jsonrpc.views.browse'', name="jsonrpc_browser"), # for the graphical browser/web console only, omissible
  url(r''^json/'', jsonrpc_site.dispatch, name="jsonrpc_mountpoint"),
  url(r''^json/(?P<method>[a-zA-Z0-9.]+)$'', jsonrpc_site.dispatch) # for HTTP GET only, also omissible
)

To test your service: You can test your service using the provided graphical browser and console, available at http://YOUR_URL/json/browse/ (if using the url patterns from above) or with the included ServiceProxy:

>>> from jsonrpc.proxy import ServiceProxy

>>> s = ServiceProxy(''http://localhost:8080/json/'')

>>> s.myapp.sayHello(''Sam'')
{u''error'': None, u''id'': u''jsonrpc'', u''result'': u''Hello Sam''}

>>> s.myapp.gimmeThat(''username'', ''password'', ''test data'')
{u''error'': None, u''id'': u''jsonrpc'', u''result'': {u''sauce'': [u''authenticated'', u''sauce'']}}

We add the jsonrpc_version variable to the request object. It be either ''1.0'', ''1.1'' or ''2.0''. Arg.

Guide

Adding JSON-RPC to your application

1. Install django-json-rpc

git clone git://github.com/samuraisam/django-json-rpc.git
cd django-json-rpc
python setup.py install

# Add ''jsonrpc'' to your INSTALLED_APPS in your settings.py file

2. Write JSON-RPC methods

from jsonrpc import jsonrpc_method

@jsonrpc_method(''app.register'')
def register_user(request, username, password):
  u = User.objects.create_user(username, ''internal@app.net'', password)
  u.save()
  return u.__dict__

@jsonrpc_method(''app.change_password'', authenticated=True)
def change_password(request, new_password):
  request.user.set_password(new_password)
  request.user.save()
  return u.__dict__

3. Add the JSON-RPC mountpoint and import your views

from jsonrpc import jsonrpc_site
import app.views

urlpatterns = patterns('''',
  url(r''^json/$'', jsonrpc_site.dispatch, name=''jsonrpc_mountpoint''),
  # ... among your other URLs
)

The jsonrpc_method decorator

Wraps a function turns it into a json-rpc method. Adds several attributes to the function speific to the JSON-RPC machinery and adds it to the default jsonrpc_site if one isn''t provided. You must import the module containing these functions in your urls.py.

jsonrpc.jsonrpc_method(name, authenticated=False, safe=False, validate=False)

<ul> <li> `name`

The name of your method. IE: namespace.methodName

</li> <li> `authenticated=False`

Adds username and password arguments to the beginning of your method if the user hasn''t already been authenticated. These will be used to authenticate the user against django.contrib.authenticate If you use HTTP auth or other authentication middleware, username and password will not be added, and this method will only check against request.user.is_authenticated.

You may pass a callablle to replace django.contrib.auth.authenticate as the authentication method. It must return either a User or None and take the keyword arguments username and password.

</li> <li> `safe=False`

Designates whether or not your method may be accessed by HTTP GET. By default this is turned off.

</li> <li> `validate=False`

Validates the arguments passed to your method based on type information provided in the signature. Supply type information by including types in your method declaration. Like so:

  @jsonrpc_method(''myapp.specialSauce(Array, String)'', validate=True)
  def special_sauce(self, ingredients, instructions):
    return SpecialSauce(ingredients, instructions)

Calls to myapp.specialSauce will now check each arguments type before calling special_sauce, throwing an InvalidParamsError when it encounters a discrepancy. This can significantly reduce the amount of code required to write JSON-RPC services.

NOTE: Type checking is only available on Python versions 2.6 or greater.

</li> <li> `site=default_site`

Defines which site the jsonrpc method will be added to. Can be any object that provides a register(name, func) method.

</li> </ul>

Using type checking on methods (Python 2.6 or greater)

When writing web services you often end up manually checking the types of parameters passed. django-json-rpc provides a way to eliminate much of that code by specifying the types in your method signature. As specified in the JSON-RPC spec the available types are Object Array Number Boolean String Nil and Any meaning any type.

  @jsonrpc_method(''app.addStrings(arg1=String, arg2=String) -> String'', validate=True)
  def add_strings(request, arg1, arg2):
    return arg1 + arg2

However contrived this example, a lot of extra information about our function is available. The system.describe method will automatically be able to provide more information about the parameters and return type. Provide validate=True to the jsonrpc_method decorator and you can be guaranteed to receive two string objects when add_strings is called.

Note: Return type information is used only for reference, return value types are not checked.

Types can be specified a number of ways, the following are all equivalent:

  # using JSON types:
  @jsonrpc_method(''app.findSelection(query=Object, limit=Number)'')

  # using Python types:
  @jsonrpc_method(''app.findSelection(query=dict, limit=int)'')

  # with mixed keyword parameters
  @jsonrpc_method(''app.findSelection(dict, limit=int)'')

  # with no keyword parameters
  @jsonrpc_method(''app.findSelection(dict, int)'')

  # with a return value
  @jsonrpc_method(''app.findSelection(dict, int) -> list'')

Using the browser

To access the browser simply add another entry to your urls.py file, before the json dispatch one. Make sure to include the name attribute of each url.

urlpatterns = patterns('''',
  ...
  url(r''^json/browse/$'', ''jsonrpc.views.browse'', name=''jsonrpc_browser'')
  url(r''^json/'', jsonrpc_site.dispatch, name="jsonrpc_mountpoint"),
  ...
)

Enabling HTTP-GET

JSON-RPC 1.1 includes support for methods which are accessible by HTTP GET which it calls idempotent. Add the following to your urls.py file to set up the GET URL.

urlpatterns += patterns('''',
  (r''^json/(?P<method>[a-zA-Z0-9.-_]+)$'', jsonrpc_site.dispatch),
)

Each method that you want to be accessible by HTTP GET must also be marked safe in the method decorator:

@jsonrpc_method(''app.trimTails(String)'', safe=True)
def trim_tails(request, arg1):
  return arg1[:5]

You can then call the method by loading /jsonrpc/app.trimTails?arg1=omgnowai

Using authentication on methods

There is no specific support for authentication in the JSON-RPC spec beyond whatever authentication the transport offers. To restrict access to methods to registered users provide authenticated=True to the method decorator. Doing so will add two arguments to the beginning of your method signature, username and password (and always in that order). By default, the credentials are authenticated against the builtin User database but any method can be used.

@jsonrpc_method(''app.thupertheecrit'', authenticated=True)
def thupertheecrit(request, value):
  p = request.user.get_profile()
  p.theecrit = value
  p.save()
  return p.__dict__

Using your own authentication method:

def mah_authenticate(username, password):
  return CustomUserClass.authenticate(username, password)

@jsonrpc_method(''app.thupertheecrit'', authenticated=mah_authenticate)
def thupertheecrit(request, value):
  request.user.theecrit = value
  request.user.save()
  return request.user.__dict__

In case authentication is handled before your method is called, like in some middleware, providing authenticated=True to the method decorator will only check that request.user is authenticated and won''t add any parameters to the beginning of your method.

今天关于开始-JSON-RPC-“冒号太多”的介绍到此结束,谢谢您的阅读,有关(译) JSON-RPC 2.0 规范(中文版)、com.facebook.stetho.inspector.jsonrpc.JsonRpcPeer的实例源码、com.facebook.stetho.inspector.jsonrpc.JsonRpcResult的实例源码、Django JSON-RPC等更多相关知识的信息可以在本站进行查询。

本文标签: