refactor: move emqx_json to emqx_utils_json

This commit is contained in:
Stefan Strigler 2023-04-13 14:02:37 +02:00
parent a0cfac3a1a
commit f8e9e54393
130 changed files with 508 additions and 331 deletions

View File

@ -22,9 +22,9 @@
%% This rebar.config is necessary because the app may be used as a %% This rebar.config is necessary because the app may be used as a
%% `git_subdir` dependency in other projects. %% `git_subdir` dependency in other projects.
{deps, [ {deps, [
{emqx_utils, {path, "../emqx_utils"}},
{lc, {git, "https://github.com/emqx/lc.git", {tag, "0.3.2"}}}, {lc, {git, "https://github.com/emqx/lc.git", {tag, "0.3.2"}}},
{gproc, {git, "https://github.com/uwiger/gproc", {tag, "0.8.0"}}}, {gproc, {git, "https://github.com/uwiger/gproc", {tag, "0.8.0"}}},
{jiffy, {git, "https://github.com/emqx/jiffy", {tag, "1.0.5"}}},
{cowboy, {git, "https://github.com/emqx/cowboy", {tag, "2.9.0"}}}, {cowboy, {git, "https://github.com/emqx/cowboy", {tag, "2.9.0"}}},
{esockd, {git, "https://github.com/emqx/esockd", {tag, "5.9.6"}}}, {esockd, {git, "https://github.com/emqx/esockd", {tag, "5.9.6"}}},
{ekka, {git, "https://github.com/emqx/ekka", {tag, "0.14.6"}}}, {ekka, {git, "https://github.com/emqx/ekka", {tag, "0.14.6"}}},

View File

@ -423,7 +423,7 @@ do_actions(deactivate, Alarm = #deactivated_alarm{name = Name}, [log | More]) ->
do_actions(deactivate, Alarm, More); do_actions(deactivate, Alarm, More);
do_actions(Operation, Alarm, [publish | More]) -> do_actions(Operation, Alarm, [publish | More]) ->
Topic = topic(Operation), Topic = topic(Operation),
{ok, Payload} = emqx_json:safe_encode(normalize(Alarm)), {ok, Payload} = emqx_utils_json:safe_encode(normalize(Alarm)),
Message = emqx_message:make( Message = emqx_message:make(
?MODULE, ?MODULE,
0, 0,

View File

@ -92,7 +92,7 @@ format(Msg, Meta, Config) ->
} }
end, end,
Data = maps:without([report_cb], Data0), Data = maps:without([report_cb], Data0),
jiffy:encode(json_obj(Data, Config)). emqx_utils_json:encode(json_obj(Data, Config)).
maybe_format_msg({report, Report} = Msg, #{report_cb := Cb} = Meta, Config) -> maybe_format_msg({report, Report} = Msg, #{report_cb := Cb} = Meta, Config) ->
case is_map(Report) andalso Cb =:= ?DEFAULT_FORMATTER of case is_map(Report) andalso Cb =:= ?DEFAULT_FORMATTER of

View File

@ -2583,7 +2583,7 @@ to_url(Str) ->
end. end.
to_json_binary(Str) -> to_json_binary(Str) ->
case emqx_json:safe_decode(Str) of case emqx_utils_json:safe_decode(Str) of
{ok, _} -> {ok, _} ->
{ok, iolist_to_binary(Str)}; {ok, iolist_to_binary(Str)};
Error -> Error ->

View File

@ -348,7 +348,7 @@ publish(Event, Payload) when
Event == unsubscribed Event == unsubscribed
-> ->
Topic = event_topic(Event, Payload), Topic = event_topic(Event, Payload),
safe_publish(Topic, emqx_json:encode(Payload)). safe_publish(Topic, emqx_utils_json:encode(Payload)).
metric_topic(Name) -> metric_topic(Name) ->
translate_topic("metrics/", Name). translate_topic("metrics/", Name).

View File

@ -1036,7 +1036,7 @@ switch_proxy(Switch, Name, ProxyHost, ProxyPort) ->
off -> #{<<"enabled">> => false}; off -> #{<<"enabled">> => false};
on -> #{<<"enabled">> => true} on -> #{<<"enabled">> => true}
end, end,
BodyBin = emqx_json:encode(Body), BodyBin = emqx_utils_json:encode(Body),
{ok, {{_, 200, _}, _, _}} = httpc:request( {ok, {{_, 200, _}, _, _}} = httpc:request(
post, post,
{Url, [], "application/json", BodyBin}, {Url, [], "application/json", BodyBin},
@ -1056,7 +1056,7 @@ timeout_proxy(on, Name, ProxyHost, ProxyPort) ->
<<"toxicity">> => 1.0, <<"toxicity">> => 1.0,
<<"attributes">> => #{<<"timeout">> => 0} <<"attributes">> => #{<<"timeout">> => 0}
}, },
BodyBin = emqx_json:encode(Body), BodyBin = emqx_utils_json:encode(Body),
{ok, {{_, 200, _}, _, _}} = httpc:request( {ok, {{_, 200, _}, _, _}} = httpc:request(
post, post,
{Url, [], "application/json", BodyBin}, {Url, [], "application/json", BodyBin},
@ -1091,7 +1091,7 @@ latency_up_proxy(on, Name, ProxyHost, ProxyPort) ->
<<"jitter">> => 3_000 <<"jitter">> => 3_000
} }
}, },
BodyBin = emqx_json:encode(Body), BodyBin = emqx_utils_json:encode(Body),
{ok, {{_, 200, _}, _, _}} = httpc:request( {ok, {{_, 200, _}, _, _}} = httpc:request(
post, post,
{Url, [], "application/json", BodyBin}, {Url, [], "application/json", BodyBin},

View File

@ -54,7 +54,7 @@ request_api(Method, Url, QueryParams, Auth, Body, HttpOpts) ->
[] -> [] ->
{NewUrl, [Auth]}; {NewUrl, [Auth]};
_ -> _ ->
{NewUrl, [Auth], "application/json", emqx_json:encode(Body)} {NewUrl, [Auth], "application/json", emqx_utils_json:encode(Body)}
end, end,
do_request_api(Method, Request, HttpOpts). do_request_api(Method, Request, HttpOpts).
@ -70,7 +70,7 @@ do_request_api(Method, Request, HttpOpts) ->
end. end.
get_http_data(ResponseBody) -> get_http_data(ResponseBody) ->
emqx_json:decode(ResponseBody, [return_maps]). emqx_utils_json:decode(ResponseBody, [return_maps]).
auth_header(User, Pass) -> auth_header(User, Pass) ->
Encoded = base64:encode_to_string(lists:append([User, ":", Pass])), Encoded = base64:encode_to_string(lists:append([User, ":", Pass])),

View File

@ -57,5 +57,5 @@ t_fill_default_values(_) ->
WithDefaults WithDefaults
), ),
%% ensure JSON compatible %% ensure JSON compatible
_ = emqx_json:encode(WithDefaults), _ = emqx_utils_json:encode(WithDefaults),
ok. ok.

View File

@ -402,7 +402,7 @@ request(Method, Url, QueryParams, Body) ->
Opts = #{return_all => true}, Opts = #{return_all => true},
case emqx_mgmt_api_test_util:request_api(Method, Url, QueryParams, AuthHeader, Body, Opts) of case emqx_mgmt_api_test_util:request_api(Method, Url, QueryParams, AuthHeader, Body, Opts) of
{ok, {Reason, Headers, BodyR}} -> {ok, {Reason, Headers, BodyR}} ->
{ok, {Reason, Headers, emqx_json:decode(BodyR, [return_maps])}}; {ok, {Reason, Headers, emqx_utils_json:decode(BodyR, [return_maps])}};
Error -> Error ->
Error Error
end. end.
@ -1052,7 +1052,7 @@ do_t_validations(_Config) ->
), ),
{error, {_, _, ResRaw1}} = update_listener_via_api(ListenerId, ListenerData1), {error, {_, _, ResRaw1}} = update_listener_via_api(ListenerId, ListenerData1),
#{<<"code">> := <<"BAD_REQUEST">>, <<"message">> := MsgRaw1} = #{<<"code">> := <<"BAD_REQUEST">>, <<"message">> := MsgRaw1} =
emqx_json:decode(ResRaw1, [return_maps]), emqx_utils_json:decode(ResRaw1, [return_maps]),
?assertMatch( ?assertMatch(
#{ #{
<<"mismatches">> := <<"mismatches">> :=
@ -1064,7 +1064,7 @@ do_t_validations(_Config) ->
} }
} }
}, },
emqx_json:decode(MsgRaw1, [return_maps]) emqx_utils_json:decode(MsgRaw1, [return_maps])
), ),
ok. ok.

View File

@ -430,7 +430,7 @@ request(Method, Url, QueryParams, Body) ->
Opts = #{return_all => true}, Opts = #{return_all => true},
case emqx_mgmt_api_test_util:request_api(Method, Url, QueryParams, AuthHeader, Body, Opts) of case emqx_mgmt_api_test_util:request_api(Method, Url, QueryParams, AuthHeader, Body, Opts) of
{ok, {Reason, Headers, BodyR}} -> {ok, {Reason, Headers, BodyR}} ->
{ok, {Reason, Headers, emqx_json:decode(BodyR, [return_maps])}}; {ok, {Reason, Headers, emqx_utils_json:decode(BodyR, [return_maps])}};
Error -> Error ->
Error Error
end. end.
@ -827,7 +827,7 @@ do_t_validations(_Config) ->
), ),
{error, {_, _, ResRaw1}} = update_listener_via_api(ListenerId, ListenerData1), {error, {_, _, ResRaw1}} = update_listener_via_api(ListenerId, ListenerData1),
#{<<"code">> := <<"BAD_REQUEST">>, <<"message">> := MsgRaw1} = #{<<"code">> := <<"BAD_REQUEST">>, <<"message">> := MsgRaw1} =
emqx_json:decode(ResRaw1, [return_maps]), emqx_utils_json:decode(ResRaw1, [return_maps]),
?assertMatch( ?assertMatch(
#{ #{
<<"mismatches">> := <<"mismatches">> :=
@ -839,7 +839,7 @@ do_t_validations(_Config) ->
} }
} }
}, },
emqx_json:decode(MsgRaw1, [return_maps]) emqx_utils_json:decode(MsgRaw1, [return_maps])
), ),
ListenerData2 = ListenerData2 =
@ -857,7 +857,7 @@ do_t_validations(_Config) ->
), ),
{error, {_, _, ResRaw2}} = update_listener_via_api(ListenerId, ListenerData2), {error, {_, _, ResRaw2}} = update_listener_via_api(ListenerId, ListenerData2),
#{<<"code">> := <<"BAD_REQUEST">>, <<"message">> := MsgRaw2} = #{<<"code">> := <<"BAD_REQUEST">>, <<"message">> := MsgRaw2} =
emqx_json:decode(ResRaw2, [return_maps]), emqx_utils_json:decode(ResRaw2, [return_maps]),
?assertMatch( ?assertMatch(
#{ #{
<<"mismatches">> := <<"mismatches">> :=
@ -869,7 +869,7 @@ do_t_validations(_Config) ->
} }
} }
}, },
emqx_json:decode(MsgRaw2, [return_maps]) emqx_utils_json:decode(MsgRaw2, [return_maps])
), ),
ListenerData3a = ListenerData3a =
@ -889,7 +889,7 @@ do_t_validations(_Config) ->
ListenerData3 = emqx_map_lib:deep_remove([<<"ssl_options">>, <<"certfile">>], ListenerData3a), ListenerData3 = emqx_map_lib:deep_remove([<<"ssl_options">>, <<"certfile">>], ListenerData3a),
{error, {_, _, ResRaw3}} = update_listener_via_api(ListenerId, ListenerData3), {error, {_, _, ResRaw3}} = update_listener_via_api(ListenerId, ListenerData3),
#{<<"code">> := <<"BAD_REQUEST">>, <<"message">> := MsgRaw3} = #{<<"code">> := <<"BAD_REQUEST">>, <<"message">> := MsgRaw3} =
emqx_json:decode(ResRaw3, [return_maps]), emqx_utils_json:decode(ResRaw3, [return_maps]),
?assertMatch( ?assertMatch(
#{ #{
<<"mismatches">> := <<"mismatches">> :=
@ -901,7 +901,7 @@ do_t_validations(_Config) ->
} }
} }
}, },
emqx_json:decode(MsgRaw3, [return_maps]) emqx_utils_json:decode(MsgRaw3, [return_maps])
), ),
ok. ok.

View File

@ -14,10 +14,10 @@
%% limitations under the License. %% limitations under the License.
%%-------------------------------------------------------------------- %%--------------------------------------------------------------------
-module(prop_emqx_json). -module(prop_emqx_utils_json).
-import( -import(
emqx_json, emqx_utils_json,
[ [
decode/1, decode/1,
decode/2, decode/2,

View File

@ -2,6 +2,7 @@
{deps, [ {deps, [
{emqx, {path, "../emqx"}}, {emqx, {path, "../emqx"}},
{emqx_utils, {path, "../emqx_utils"}},
{emqx_connector, {path, "../emqx_connector"}} {emqx_connector, {path, "../emqx_connector"}}
]}. ]}.

View File

@ -357,7 +357,7 @@ qs([{K, V} | More], Acc) ->
qs(More, [["&", uri_encode(K), "=", uri_encode(V)] | Acc]). qs(More, [["&", uri_encode(K), "=", uri_encode(V)] | Acc]).
serialize_body(<<"application/json">>, Body) -> serialize_body(<<"application/json">>, Body) ->
emqx_json:encode(Body); emqx_utils_json:encode(Body);
serialize_body(<<"application/x-www-form-urlencoded">>, Body) -> serialize_body(<<"application/x-www-form-urlencoded">>, Body) ->
qs(maps:to_list(Body)). qs(maps:to_list(Body)).
@ -395,7 +395,7 @@ safely_parse_body(ContentType, Body) ->
end. end.
parse_body(<<"application/json", _/binary>>, Body) -> parse_body(<<"application/json", _/binary>>, Body) ->
{ok, emqx_json:decode(Body, [return_maps])}; {ok, emqx_utils_json:decode(Body, [return_maps])};
parse_body(<<"application/x-www-form-urlencoded", _/binary>>, Body) -> parse_body(<<"application/x-www-form-urlencoded", _/binary>>, Body) ->
Flags = [<<"result">>, <<"is_superuser">>], Flags = [<<"result">>, <<"is_superuser">>],
RawMap = maps:from_list(cow_qs:parse_qs(Body)), RawMap = maps:from_list(cow_qs:parse_qs(Body)),

View File

@ -99,7 +99,7 @@ handle_info(
State1; State1;
{StatusLine, Headers, Body} -> {StatusLine, Headers, Body} ->
try try
JWKS = jose_jwk:from(emqx_json:decode(Body, [return_maps])), JWKS = jose_jwk:from(emqx_utils_json:decode(Body, [return_maps])),
{_, JWKs} = JWKS#jose_jwk.keys, {_, JWKs} = JWKS#jose_jwk.keys,
State1#{jwks := JWKs} State1#{jwks := JWKs}
catch catch

View File

@ -407,7 +407,7 @@ do_verify(_JWT, [], _VerifyClaims) ->
do_verify(JWT, [JWK | More], VerifyClaims) -> do_verify(JWT, [JWK | More], VerifyClaims) ->
try jose_jws:verify(JWK, JWT) of try jose_jws:verify(JWK, JWT) of
{true, Payload, _JWT} -> {true, Payload, _JWT} ->
Claims0 = emqx_json:decode(Payload, [return_maps]), Claims0 = emqx_utils_json:decode(Payload, [return_maps]),
Claims = try_convert_to_num(Claims0, [<<"exp">>, <<"iat">>, <<"nbf">>]), Claims = try_convert_to_num(Claims0, [<<"exp">>, <<"iat">>, <<"nbf">>]),
case verify_claims(Claims, VerifyClaims) of case verify_claims(Claims, VerifyClaims) of
ok -> ok ->

View File

@ -332,7 +332,7 @@ run_fuzzy_filter(
%% Example: data/user-credentials.json %% Example: data/user-credentials.json
import_users_from_json(Bin, #{user_group := UserGroup}) -> import_users_from_json(Bin, #{user_group := UserGroup}) ->
case emqx_json:safe_decode(Bin, [return_maps]) of case emqx_utils_json:safe_decode(Bin, [return_maps]) of
{ok, List} -> {ok, List} ->
trans(fun ?MODULE:import/2, [UserGroup, List]); trans(fun ?MODULE:import/2, [UserGroup, List]);
{error, Reason} -> {error, Reason} ->

View File

@ -29,7 +29,7 @@
-define(assertAuthenticatorsMatch(Guard, Path), -define(assertAuthenticatorsMatch(Guard, Path),
(fun() -> (fun() ->
{ok, 200, Response} = request(get, uri(Path)), {ok, 200, Response} = request(get, uri(Path)),
?assertMatch(Guard, jiffy:decode(Response, [return_maps])) ?assertMatch(Guard, emqx_utils_json:decode(Response, [return_maps]))
end)() end)()
). ).
@ -234,7 +234,7 @@ test_authenticator(PathPrefix) ->
get, get,
uri(PathPrefix ++ [?CONF_NS, "password_based:http", "status"]) uri(PathPrefix ++ [?CONF_NS, "password_based:http", "status"])
), ),
{ok, RList} = emqx_json:safe_decode(Res), {ok, RList} = emqx_utils_json:safe_decode(Res),
Snd = fun({_, Val}) -> Val end, Snd = fun({_, Val}) -> Val end,
LookupVal = fun LookupV(List, RestJson) -> LookupVal = fun LookupV(List, RestJson) ->
case List of case List of
@ -353,7 +353,7 @@ test_authenticator_users(PathPrefix) ->
<<"success">> := 0, <<"success">> := 0,
<<"nomatch">> := 1 <<"nomatch">> := 1
} }
} = jiffy:decode(PageData0, [return_maps]); } = emqx_utils_json:decode(PageData0, [return_maps]);
["listeners", 'tcp:default'] -> ["listeners", 'tcp:default'] ->
#{ #{
<<"metrics">> := #{ <<"metrics">> := #{
@ -361,7 +361,7 @@ test_authenticator_users(PathPrefix) ->
<<"success">> := 0, <<"success">> := 0,
<<"nomatch">> := 1 <<"nomatch">> := 1
} }
} = jiffy:decode(PageData0, [return_maps]) } = emqx_utils_json:decode(PageData0, [return_maps])
end, end,
InvalidUsers = [ InvalidUsers = [
@ -384,7 +384,7 @@ test_authenticator_users(PathPrefix) ->
lists:foreach( lists:foreach(
fun(User) -> fun(User) ->
{ok, 201, UserData} = request(post, UsersUri, User), {ok, 201, UserData} = request(post, UsersUri, User),
CreatedUser = jiffy:decode(UserData, [return_maps]), CreatedUser = emqx_utils_json:decode(UserData, [return_maps]),
?assertMatch(#{<<"user_id">> := _}, CreatedUser) ?assertMatch(#{<<"user_id">> := _}, CreatedUser)
end, end,
ValidUsers ValidUsers
@ -411,7 +411,7 @@ test_authenticator_users(PathPrefix) ->
<<"success">> := 1, <<"success">> := 1,
<<"nomatch">> := 1 <<"nomatch">> := 1
} }
} = jiffy:decode(PageData01, [return_maps]); } = emqx_utils_json:decode(PageData01, [return_maps]);
["listeners", 'tcp:default'] -> ["listeners", 'tcp:default'] ->
#{ #{
<<"metrics">> := #{ <<"metrics">> := #{
@ -419,7 +419,7 @@ test_authenticator_users(PathPrefix) ->
<<"success">> := 1, <<"success">> := 1,
<<"nomatch">> := 1 <<"nomatch">> := 1
} }
} = jiffy:decode(PageData01, [return_maps]) } = emqx_utils_json:decode(PageData01, [return_maps])
end, end,
{ok, 200, Page1Data} = request(get, UsersUri ++ "?page=1&limit=2"), {ok, 200, Page1Data} = request(get, UsersUri ++ "?page=1&limit=2"),
@ -433,7 +433,7 @@ test_authenticator_users(PathPrefix) ->
<<"count">> := 3 <<"count">> := 3
} }
} = } =
jiffy:decode(Page1Data, [return_maps]), emqx_utils_json:decode(Page1Data, [return_maps]),
{ok, 200, Page2Data} = request(get, UsersUri ++ "?page=2&limit=2"), {ok, 200, Page2Data} = request(get, UsersUri ++ "?page=2&limit=2"),
@ -445,7 +445,7 @@ test_authenticator_users(PathPrefix) ->
<<"limit">> := 2, <<"limit">> := 2,
<<"count">> := 3 <<"count">> := 3
} }
} = jiffy:decode(Page2Data, [return_maps]), } = emqx_utils_json:decode(Page2Data, [return_maps]),
?assertEqual(2, length(Page1Users)), ?assertEqual(2, length(Page1Users)),
?assertEqual(1, length(Page2Users)), ?assertEqual(1, length(Page2Users)),
@ -465,7 +465,7 @@ test_authenticator_users(PathPrefix) ->
<<"limit">> := 3, <<"limit">> := 3,
<<"count">> := 1 <<"count">> := 1
} }
} = jiffy:decode(Super1Data, [return_maps]), } = emqx_utils_json:decode(Super1Data, [return_maps]),
?assertEqual( ?assertEqual(
[<<"u2">>], [<<"u2">>],
@ -482,7 +482,7 @@ test_authenticator_users(PathPrefix) ->
<<"limit">> := 3, <<"limit">> := 3,
<<"count">> := 2 <<"count">> := 2
} }
} = jiffy:decode(Super2Data, [return_maps]), } = emqx_utils_json:decode(Super2Data, [return_maps]),
?assertEqual( ?assertEqual(
[<<"u1">>, <<"u3">>], [<<"u1">>, <<"u3">>],
@ -509,7 +509,7 @@ test_authenticator_user(PathPrefix) ->
{ok, 200, UserData} = request(get, UsersUri ++ "/u1"), {ok, 200, UserData} = request(get, UsersUri ++ "/u1"),
FetchedUser = jiffy:decode(UserData, [return_maps]), FetchedUser = emqx_utils_json:decode(UserData, [return_maps]),
?assertMatch(#{<<"user_id">> := <<"u1">>}, FetchedUser), ?assertMatch(#{<<"user_id">> := <<"u1">>}, FetchedUser),
?assertNotMatch(#{<<"password">> := _}, FetchedUser), ?assertNotMatch(#{<<"password">> := _}, FetchedUser),

View File

@ -41,7 +41,7 @@
-define(SERVER_RESPONSE_JSON(Result), ?SERVER_RESPONSE_JSON(Result, false)). -define(SERVER_RESPONSE_JSON(Result), ?SERVER_RESPONSE_JSON(Result, false)).
-define(SERVER_RESPONSE_JSON(Result, IsSuperuser), -define(SERVER_RESPONSE_JSON(Result, IsSuperuser),
jiffy:encode(#{ emqx_utils_json:encode(#{
result => Result, result => Result,
is_superuser => IsSuperuser is_superuser => IsSuperuser
}) })
@ -172,11 +172,11 @@ t_no_value_for_placeholder(_Config) ->
#{ #{
<<"cert_subject">> := <<"">>, <<"cert_subject">> := <<"">>,
<<"cert_common_name">> := <<"">> <<"cert_common_name">> := <<"">>
} = jiffy:decode(RawBody, [return_maps]), } = emqx_utils_json:decode(RawBody, [return_maps]),
Req = cowboy_req:reply( Req = cowboy_req:reply(
200, 200,
#{<<"content-type">> => <<"application/json">>}, #{<<"content-type">> => <<"application/json">>},
jiffy:encode(#{result => allow, is_superuser => false}), emqx_utils_json:encode(#{result => allow, is_superuser => false}),
Req1 Req1
), ),
{ok, Req, State} {ok, Req, State}
@ -444,7 +444,7 @@ samples() ->
Req = cowboy_req:reply( Req = cowboy_req:reply(
200, 200,
#{<<"content-type">> => <<"application/json">>}, #{<<"content-type">> => <<"application/json">>},
jiffy:encode(#{result => allow, is_superuser => false}), emqx_utils_json:encode(#{result => allow, is_superuser => false}),
Req0 Req0
), ),
{ok, Req, State} {ok, Req, State}
@ -459,7 +459,7 @@ samples() ->
Req = cowboy_req:reply( Req = cowboy_req:reply(
200, 200,
#{<<"content-type">> => <<"application/json">>}, #{<<"content-type">> => <<"application/json">>},
jiffy:encode(#{result => allow, is_superuser => true}), emqx_utils_json:encode(#{result => allow, is_superuser => true}),
Req0 Req0
), ),
{ok, Req, State} {ok, Req, State}
@ -512,11 +512,11 @@ samples() ->
#{ #{
<<"username">> := <<"plain">>, <<"username">> := <<"plain">>,
<<"password">> := <<"plain">> <<"password">> := <<"plain">>
} = jiffy:decode(RawBody, [return_maps]), } = emqx_utils_json:decode(RawBody, [return_maps]),
Req = cowboy_req:reply( Req = cowboy_req:reply(
200, 200,
#{<<"content-type">> => <<"application/json">>}, #{<<"content-type">> => <<"application/json">>},
jiffy:encode(#{result => allow, is_superuser => false}), emqx_utils_json:encode(#{result => allow, is_superuser => false}),
Req1 Req1
), ),
{ok, Req, State} {ok, Req, State}
@ -539,7 +539,7 @@ samples() ->
Req = cowboy_req:reply( Req = cowboy_req:reply(
200, 200,
#{<<"content-type">> => <<"application/json">>}, #{<<"content-type">> => <<"application/json">>},
jiffy:encode(#{result => allow, is_superuser => false}), emqx_utils_json:encode(#{result => allow, is_superuser => false}),
Req1 Req1
), ),
{ok, Req, State} {ok, Req, State}
@ -565,11 +565,11 @@ samples() ->
<<"peerhost">> := <<"127.0.0.1">>, <<"peerhost">> := <<"127.0.0.1">>,
<<"cert_subject">> := <<"cert_subject_data">>, <<"cert_subject">> := <<"cert_subject_data">>,
<<"cert_common_name">> := <<"cert_common_name_data">> <<"cert_common_name">> := <<"cert_common_name_data">>
} = jiffy:decode(RawBody, [return_maps]), } = emqx_utils_json:decode(RawBody, [return_maps]),
Req = cowboy_req:reply( Req = cowboy_req:reply(
200, 200,
#{<<"content-type">> => <<"application/json">>}, #{<<"content-type">> => <<"application/json">>},
jiffy:encode(#{result => allow, is_superuser => false}), emqx_utils_json:encode(#{result => allow, is_superuser => false}),
Req1 Req1
), ),
{ok, Req, State} {ok, Req, State}

View File

@ -168,7 +168,7 @@ cowboy_handler(Req0, State) ->
Req = cowboy_req:reply( Req = cowboy_req:reply(
200, 200,
#{<<"content-type">> => <<"application/json">>}, #{<<"content-type">> => <<"application/json">>},
jiffy:encode(#{result => allow, is_superuser => false}), emqx_utils_json:encode(#{result => allow, is_superuser => false}),
Req0 Req0
), ),
{ok, Req, State}. {ok, Req, State}.

View File

@ -467,7 +467,7 @@ jwks_handler(Req0, State) ->
Req = cowboy_req:reply( Req = cowboy_req:reply(
200, 200,
#{<<"content-type">> => <<"application/json">>}, #{<<"content-type">> => <<"application/json">>},
jiffy:encode(JWKS), emqx_utils_json:encode(JWKS),
Req0 Req0
), ),
{ok, Req, State}. {ok, Req, State}.

View File

@ -3,6 +3,7 @@
{erl_opts, [debug_info, nowarn_unused_import]}. {erl_opts, [debug_info, nowarn_unused_import]}.
{deps, [ {deps, [
{emqx, {path, "../emqx"}}, {emqx, {path, "../emqx"}},
{emqx_utils, {path, "../emqx_utils"}},
{emqx_connector, {path, "../emqx_connector"}} {emqx_connector, {path, "../emqx_connector"}}
]}. ]}.

View File

@ -144,7 +144,7 @@ parse_http_resp_body(<<"application/x-www-form-urlencoded", _/binary>>, Body) ->
end; end;
parse_http_resp_body(<<"application/json", _/binary>>, Body) -> parse_http_resp_body(<<"application/json", _/binary>>, Body) ->
try try
result(emqx_json:decode(Body, [return_maps])) result(emqx_utils_json:decode(Body, [return_maps]))
catch catch
_:_ -> error _:_ -> error
end. end.

View File

@ -67,12 +67,12 @@ t_clean_cahce(_) ->
ok = emqtt:publish(C, <<"a/b/c">>, <<"{\"x\":1,\"y\":1}">>, 0), ok = emqtt:publish(C, <<"a/b/c">>, <<"{\"x\":1,\"y\":1}">>, 0),
{ok, 200, Result3} = request(get, uri(["clients", "emqx0", "authorization", "cache"])), {ok, 200, Result3} = request(get, uri(["clients", "emqx0", "authorization", "cache"])),
?assertEqual(2, length(emqx_json:decode(Result3))), ?assertEqual(2, length(emqx_utils_json:decode(Result3))),
request(delete, uri(["authorization", "cache"])), request(delete, uri(["authorization", "cache"])),
{ok, 200, Result4} = request(get, uri(["clients", "emqx0", "authorization", "cache"])), {ok, 200, Result4} = request(get, uri(["clients", "emqx0", "authorization", "cache"])),
?assertEqual(0, length(emqx_json:decode(Result4))), ?assertEqual(0, length(emqx_utils_json:decode(Result4))),
ok. ok.

View File

@ -182,7 +182,7 @@ t_api(_) ->
{ok, 404, ErrResult} = request(get, uri(["authorization", "sources", "http"]), []), {ok, 404, ErrResult} = request(get, uri(["authorization", "sources", "http"]), []),
?assertMatch( ?assertMatch(
#{<<"code">> := <<"NOT_FOUND">>, <<"message">> := <<"Not found: http">>}, #{<<"code">> := <<"NOT_FOUND">>, <<"message">> := <<"Not found: http">>},
emqx_json:decode(ErrResult, [return_maps]) emqx_utils_json:decode(ErrResult, [return_maps])
), ),
[ [
@ -215,7 +215,8 @@ t_api(_) ->
), ),
{ok, 200, Result3} = request(get, uri(["authorization", "sources", "http"]), []), {ok, 200, Result3} = request(get, uri(["authorization", "sources", "http"]), []),
?assertMatch( ?assertMatch(
#{<<"type">> := <<"http">>, <<"enable">> := false}, emqx_json:decode(Result3, [return_maps]) #{<<"type">> := <<"http">>, <<"enable">> := false},
emqx_utils_json:decode(Result3, [return_maps])
), ),
Keyfile = emqx_common_test_helpers:app_path( Keyfile = emqx_common_test_helpers:app_path(
@ -253,7 +254,7 @@ t_api(_) ->
<<"total">> := 0, <<"total">> := 0,
<<"nomatch">> := 0 <<"nomatch">> := 0
} }
} = emqx_json:decode(Status4, [return_maps]), } = emqx_utils_json:decode(Status4, [return_maps]),
?assertMatch( ?assertMatch(
#{ #{
<<"type">> := <<"mongodb">>, <<"type">> := <<"mongodb">>,
@ -265,7 +266,7 @@ t_api(_) ->
<<"verify">> := <<"verify_none">> <<"verify">> := <<"verify_none">>
} }
}, },
emqx_json:decode(Result4, [return_maps]) emqx_utils_json:decode(Result4, [return_maps])
), ),
{ok, Cacert} = file:read_file(Cacertfile), {ok, Cacert} = file:read_file(Cacertfile),
@ -297,7 +298,7 @@ t_api(_) ->
<<"verify">> := <<"verify_none">> <<"verify">> := <<"verify_none">>
} }
}, },
emqx_json:decode(Result5, [return_maps]) emqx_utils_json:decode(Result5, [return_maps])
), ),
{ok, 200, Status5_1} = request(get, uri(["authorization", "sources", "mongodb", "status"]), []), {ok, 200, Status5_1} = request(get, uri(["authorization", "sources", "mongodb", "status"]), []),
@ -308,7 +309,7 @@ t_api(_) ->
<<"total">> := 0, <<"total">> := 0,
<<"nomatch">> := 0 <<"nomatch">> := 0
} }
} = emqx_json:decode(Status5_1, [return_maps]), } = emqx_utils_json:decode(Status5_1, [return_maps]),
#{ #{
ssl := #{ ssl := #{
@ -355,7 +356,7 @@ t_api(_) ->
<<"code">> := <<"BAD_REQUEST">>, <<"code">> := <<"BAD_REQUEST">>,
<<"message">> := <<"Type mismatch", _/binary>> <<"message">> := <<"Type mismatch", _/binary>>
}, },
emqx_json:decode(TypeMismatch, [return_maps]) emqx_utils_json:decode(TypeMismatch, [return_maps])
), ),
lists:foreach( lists:foreach(
@ -443,7 +444,7 @@ t_api(_) ->
<<"total">> := 1, <<"total">> := 1,
<<"nomatch">> := 0 <<"nomatch">> := 0
} }
} = emqx_json:decode(Status5, [return_maps]) } = emqx_utils_json:decode(Status5, [return_maps])
end end
), ),
@ -469,7 +470,7 @@ t_api(_) ->
<<"total">> := 2, <<"total">> := 2,
<<"nomatch">> := 0 <<"nomatch">> := 0
} }
} = emqx_json:decode(Status6, [return_maps]) } = emqx_utils_json:decode(Status6, [return_maps])
end end
), ),
@ -495,7 +496,7 @@ t_api(_) ->
<<"total">> := 3, <<"total">> := 3,
<<"nomatch">> := 0 <<"nomatch">> := 0
} }
} = emqx_json:decode(Status7, [return_maps]) } = emqx_utils_json:decode(Status7, [return_maps])
end end
), ),
ok. ok.
@ -621,7 +622,7 @@ t_aggregate_metrics(_) ->
). ).
get_sources(Result) -> get_sources(Result) ->
maps:get(<<"sources">>, emqx_json:decode(Result, [return_maps])). maps:get(<<"sources">>, emqx_utils_json:decode(Result, [return_maps])).
data_dir() -> emqx:data_dir(). data_dir() -> emqx:data_dir().

View File

@ -311,7 +311,7 @@ t_json_body(_Config) ->
<<"topic">> := <<"t">>, <<"topic">> := <<"t">>,
<<"action">> := <<"publish">> <<"action">> := <<"publish">>
}, },
jiffy:decode(RawBody, [return_maps]) emqx_utils_json:decode(RawBody, [return_maps])
), ),
{ok, ?AUTHZ_HTTP_RESP(allow, Req1), State} {ok, ?AUTHZ_HTTP_RESP(allow, Req1), State}
end, end,
@ -366,7 +366,7 @@ t_placeholder_and_body(_Config) ->
<<"CN">> := ?PH_CERT_CN_NAME, <<"CN">> := ?PH_CERT_CN_NAME,
<<"CS">> := ?PH_CERT_SUBJECT <<"CS">> := ?PH_CERT_SUBJECT
}, },
jiffy:decode(PostVars, [return_maps]) emqx_utils_json:decode(PostVars, [return_maps])
), ),
{ok, ?AUTHZ_HTTP_RESP(allow, Req1), State} {ok, ?AUTHZ_HTTP_RESP(allow, Req1), State}
end, end,
@ -418,7 +418,7 @@ t_no_value_for_placeholder(_Config) ->
#{ #{
<<"mountpoint">> := <<"[]">> <<"mountpoint">> := <<"[]">>
}, },
jiffy:decode(RawBody, [return_maps]) emqx_utils_json:decode(RawBody, [return_maps])
), ),
{ok, ?AUTHZ_HTTP_RESP(allow, Req1), State} {ok, ?AUTHZ_HTTP_RESP(allow, Req1), State}
end, end,

View File

@ -1,7 +1,10 @@
%% -*- mode: erlang -*- %% -*- mode: erlang -*-
{erl_opts, [debug_info]}. {erl_opts, [debug_info]}.
{deps, [{emqx, {path, "../emqx"}}]}. {deps, [
{emqx, {path, "../emqx"}},
{emqx_utils, {path, "../emqx_utils"}}
]}.
{shell, [ {shell, [
{apps, [emqx_auto_subscribe]} {apps, [emqx_auto_subscribe]}

View File

@ -141,7 +141,7 @@ t_update(_) ->
Auth = emqx_mgmt_api_test_util:auth_header_(), Auth = emqx_mgmt_api_test_util:auth_header_(),
Body = [#{topic => ?TOPIC_S}], Body = [#{topic => ?TOPIC_S}],
{ok, Response} = emqx_mgmt_api_test_util:request_api(put, Path, "", Auth, Body), {ok, Response} = emqx_mgmt_api_test_util:request_api(put, Path, "", Auth, Body),
ResponseMap = emqx_json:decode(Response, [return_maps]), ResponseMap = emqx_utils_json:decode(Response, [return_maps]),
?assertEqual(1, erlang:length(ResponseMap)), ?assertEqual(1, erlang:length(ResponseMap)),
BadBody1 = #{topic => ?TOPIC_S}, BadBody1 = #{topic => ?TOPIC_S},
@ -177,7 +177,7 @@ t_update(_) ->
emqtt:disconnect(Client), emqtt:disconnect(Client),
{ok, GETResponse} = emqx_mgmt_api_test_util:request_api(get, Path), {ok, GETResponse} = emqx_mgmt_api_test_util:request_api(get, Path),
GETResponseMap = emqx_json:decode(GETResponse, [return_maps]), GETResponseMap = emqx_utils_json:decode(GETResponse, [return_maps]),
?assertEqual(1, erlang:length(GETResponseMap)), ?assertEqual(1, erlang:length(GETResponseMap)),
ok. ok.

View File

@ -1,6 +1,8 @@
{erl_opts, [debug_info]}. {erl_opts, [debug_info]}.
{deps, [ {emqx, {path, "../emqx"}} {deps, [
, {emqx_resource, {path, "../../apps/emqx_resource"}} {emqx, {path, "../emqx"}},
{emqx_utils, {path, "../emqx_utils"}},
{emqx_resource, {path, "../../apps/emqx_resource"}}
]}. ]}.
{shell, [ {shell, [

View File

@ -1028,6 +1028,6 @@ deobfuscate(NewConf, OldConf) ->
). ).
map_to_json(M) -> map_to_json(M) ->
emqx_json:encode( emqx_utils_json:encode(
emqx_map_lib:jsonable_map(M, fun(K, V) -> {K, emqx_map_lib:binary_string(V)} end) emqx_map_lib:jsonable_map(M, fun(K, V) -> {K, emqx_map_lib:binary_string(V)} end)
). ).

View File

@ -1304,4 +1304,4 @@ str(S) when is_list(S) -> S;
str(S) when is_binary(S) -> binary_to_list(S). str(S) when is_binary(S) -> binary_to_list(S).
json(B) when is_binary(B) -> json(B) when is_binary(B) ->
emqx_json:decode(B, [return_maps]). emqx_utils_json:decode(B, [return_maps]).

View File

@ -705,7 +705,7 @@ create_bridge_api(Config, Overrides) ->
Res = Res =
case emqx_mgmt_api_test_util:request_api(post, Path, "", AuthHeader, Params, Opts) of case emqx_mgmt_api_test_util:request_api(post, Path, "", AuthHeader, Params, Opts) of
{ok, {Status, Headers, Body0}} -> {ok, {Status, Headers, Body0}} ->
{ok, {Status, Headers, emqx_json:decode(Body0, [return_maps])}}; {ok, {Status, Headers, emqx_utils_json:decode(Body0, [return_maps])}};
Error -> Error ->
Error Error
end, end,
@ -728,7 +728,7 @@ update_bridge_api(Config, Overrides) ->
ct:pal("updating bridge (via http): ~p", [Params]), ct:pal("updating bridge (via http): ~p", [Params]),
Res = Res =
case emqx_mgmt_api_test_util:request_api(put, Path, "", AuthHeader, Params, Opts) of case emqx_mgmt_api_test_util:request_api(put, Path, "", AuthHeader, Params, Opts) of
{ok, {_Status, _Headers, Body0}} -> {ok, emqx_json:decode(Body0, [return_maps])}; {ok, {_Status, _Headers, Body0}} -> {ok, emqx_utils_json:decode(Body0, [return_maps])};
Error -> Error Error -> Error
end, end,
ct:pal("bridge update result: ~p", [Res]), ct:pal("bridge update result: ~p", [Res]),
@ -776,7 +776,7 @@ do_wait_for_expected_published_messages(Messages, Acc, _Timeout) when map_size(M
do_wait_for_expected_published_messages(Messages0, Acc0, Timeout) -> do_wait_for_expected_published_messages(Messages0, Acc0, Timeout) ->
receive receive
{publish, Msg0 = #{payload := Payload}} -> {publish, Msg0 = #{payload := Payload}} ->
case emqx_json:safe_decode(Payload, [return_maps]) of case emqx_utils_json:safe_decode(Payload, [return_maps]) of
{error, _} -> {error, _} ->
ct:pal("unexpected message: ~p; discarding", [Msg0]), ct:pal("unexpected message: ~p; discarding", [Msg0]),
do_wait_for_expected_published_messages(Messages0, Acc0, Timeout); do_wait_for_expected_published_messages(Messages0, Acc0, Timeout);
@ -928,7 +928,7 @@ create_rule_and_action_http(Config) ->
AuthHeader = emqx_mgmt_api_test_util:auth_header_(), AuthHeader = emqx_mgmt_api_test_util:auth_header_(),
ct:pal("rule action params: ~p", [Params]), ct:pal("rule action params: ~p", [Params]),
case emqx_mgmt_api_test_util:request_api(post, Path, "", AuthHeader, Params) of case emqx_mgmt_api_test_util:request_api(post, Path, "", AuthHeader, Params) of
{ok, Res} -> {ok, emqx_json:decode(Res, [return_maps])}; {ok, Res} -> {ok, emqx_utils_json:decode(Res, [return_maps])};
Error -> Error Error -> Error
end. end.
@ -1188,7 +1188,7 @@ t_start_and_consume_ok(Config) ->
<<"offset">> := OffsetReply, <<"offset">> := OffsetReply,
<<"headers">> := #{<<"hkey">> := <<"hvalue">>} <<"headers">> := #{<<"hkey">> := <<"hvalue">>}
}, },
emqx_json:decode(PayloadBin, [return_maps]), emqx_utils_json:decode(PayloadBin, [return_maps]),
#{ #{
offset_reply => OffsetReply, offset_reply => OffsetReply,
kafka_topic => KafkaTopic, kafka_topic => KafkaTopic,
@ -1300,7 +1300,7 @@ t_multiple_topic_mappings(Config) ->
%% as configured. %% as configured.
Payloads = Payloads =
lists:sort([ lists:sort([
case emqx_json:safe_decode(P, [return_maps]) of case emqx_utils_json:safe_decode(P, [return_maps]) of
{ok, Decoded} -> Decoded; {ok, Decoded} -> Decoded;
{error, _} -> P {error, _} -> P
end end
@ -1441,7 +1441,7 @@ do_t_failed_creation_then_fixed(Config) ->
<<"offset">> := _, <<"offset">> := _,
<<"headers">> := #{<<"hkey">> := <<"hvalue">>} <<"headers">> := #{<<"hkey">> := <<"hvalue">>}
}, },
emqx_json:decode(PayloadBin, [return_maps]), emqx_utils_json:decode(PayloadBin, [return_maps]),
#{ #{
kafka_topic => KafkaTopic, kafka_topic => KafkaTopic,
payload => Payload payload => Payload
@ -1636,7 +1636,7 @@ t_bridge_rule_action_source(Config) ->
<<"headers">> := #{<<"hkey">> := <<"hvalue">>}, <<"headers">> := #{<<"hkey">> := <<"hvalue">>},
<<"topic">> := KafkaTopic <<"topic">> := KafkaTopic
}, },
emqx_json:decode(RawPayload, [return_maps]) emqx_utils_json:decode(RawPayload, [return_maps])
), ),
?retry( ?retry(
_Interval = 200, _Interval = 200,
@ -2004,7 +2004,7 @@ t_begin_offset_earliest(Config) ->
%% the consumers %% the consumers
Published = receive_published(#{n => NumMessages}), Published = receive_published(#{n => NumMessages}),
Payloads = lists:map( Payloads = lists:map(
fun(#{payload := P}) -> emqx_json:decode(P, [return_maps]) end, fun(#{payload := P}) -> emqx_utils_json:decode(P, [return_maps]) end,
Published Published
), ),
?assert( ?assert(

View File

@ -802,7 +802,7 @@ api_path(Parts) ->
?HOST ++ filename:join([?BASE_PATH | Parts]). ?HOST ++ filename:join([?BASE_PATH | Parts]).
json(Data) -> json(Data) ->
{ok, Jsx} = emqx_json:safe_decode(Data, [return_maps]), {ok, Jsx} = emqx_utils_json:safe_decode(Data, [return_maps]),
Jsx. Jsx.
delete_all_bridges() -> delete_all_bridges() ->

View File

@ -7,6 +7,7 @@
{deps, [ {deps, [
{emqx, {path, "../emqx"}}, {emqx, {path, "../emqx"}},
{emqx_utils, {path, "../emqx_utils"}},
{emqx_resource, {path, "../emqx_resource"}}, {emqx_resource, {path, "../emqx_resource"}},
{eldap2, {git, "https://github.com/emqx/eldap2", {tag, "v0.2.2"}}}, {eldap2, {git, "https://github.com/emqx/eldap2", {tag, "v0.2.2"}}},
{mysql, {git, "https://github.com/emqx/mysql-otp", {tag, "1.7.2"}}}, {mysql, {git, "https://github.com/emqx/mysql-otp", {tag, "1.7.2"}}},

View File

@ -516,7 +516,7 @@ process_request(
}. }.
process_request_body(undefined, Msg) -> process_request_body(undefined, Msg) ->
emqx_json:encode(Msg); emqx_utils_json:encode(Msg);
process_request_body(BodyTks, Msg) -> process_request_body(BodyTks, Msg) ->
emqx_plugin_libs_rule:proc_tmpl(BodyTks, Msg). emqx_plugin_libs_rule:proc_tmpl(BodyTks, Msg).

View File

@ -123,7 +123,7 @@ process_payload(From, MapMsg) ->
do_process_payload(maps:get(payload, From, undefined), MapMsg). do_process_payload(maps:get(payload, From, undefined), MapMsg).
do_process_payload(undefined, Msg) -> do_process_payload(undefined, Msg) ->
emqx_json:encode(Msg); emqx_utils_json:encode(Msg);
do_process_payload(Tks, Msg) -> do_process_payload(Tks, Msg) ->
replace_vars_in_str(Tks, Msg). replace_vars_in_str(Tks, Msg).

View File

@ -1,6 +1,9 @@
%% -*- mode: erlang -*- %% -*- mode: erlang -*-
{deps, [{emqx, {path, "../emqx"}}]}. {deps, [
{emqx, {path, "../emqx"}},
{emqx_utils, {path, "../emqx_utils"}}
]}.
{edoc_opts, [{preprocess, true}]}. {edoc_opts, [{preprocess, true}]}.
{erl_opts, [ {erl_opts, [

View File

@ -246,5 +246,5 @@ api_path(Parts) ->
?HOST ++ filename:join([?BASE_PATH | Parts]). ?HOST ++ filename:join([?BASE_PATH | Parts]).
json(Data) -> json(Data) ->
{ok, Jsx} = emqx_json:safe_decode(Data, [return_maps]), {ok, Jsx} = emqx_utils_json:safe_decode(Data, [return_maps]),
Jsx. Jsx.

View File

@ -100,7 +100,7 @@ request(Url) ->
{ok, {{"HTTP/1.1", Code, _}, _, Return}} when {ok, {{"HTTP/1.1", Code, _}, _, Return}} when
Code >= 200 andalso Code =< 299 Code >= 200 andalso Code =< 299
-> ->
{ok, emqx_json:decode(Return, [return_maps])}; {ok, emqx_utils_json:decode(Return, [return_maps])};
{ok, {Reason, _, _}} -> {ok, {Reason, _, _}} ->
{error, Reason} {error, Reason}
end. end.

View File

@ -137,10 +137,10 @@ do_request_api(Method, Request) ->
Code >= 200 andalso Code =< 299 Code >= 200 andalso Code =< 299
-> ->
ct:pal("Resp ~p ~p~n", [Code, Return]), ct:pal("Resp ~p ~p~n", [Code, Return]),
{ok, emqx_json:decode(Return, [return_maps])}; {ok, emqx_utils_json:decode(Return, [return_maps])};
{ok, {{"HTTP/1.1", Code, _}, _, Return}} -> {ok, {{"HTTP/1.1", Code, _}, _, Return}} ->
ct:pal("Resp ~p ~p~n", [Code, Return]), ct:pal("Resp ~p ~p~n", [Code, Return]),
{error, {Code, emqx_json:decode(Return, [return_maps])}}; {error, {Code, emqx_utils_json:decode(Return, [return_maps])}};
{error, Reason} -> {error, Reason} ->
{error, Reason} {error, Reason}
end. end.

View File

@ -5,7 +5,8 @@
]}. ]}.
{deps, [ {deps, [
{emqx, {path, "../emqx"}} {emqx, {path, "../emqx"}},
{emqx_utils, {path, "../emqx_utils"}}
]}. ]}.
{grpc, [ {grpc, [

View File

@ -310,7 +310,7 @@ t_update(Cfg) ->
?assertMatch([], emqx_exhook_mgr:running()). ?assertMatch([], emqx_exhook_mgr:running()).
decode_json(Data) -> decode_json(Data) ->
BinJosn = emqx_json:decode(Data, [return_maps]), BinJosn = emqx_utils_json:decode(Data, [return_maps]),
emqx_map_lib:unsafe_atom_key_map(BinJosn). emqx_map_lib:unsafe_atom_key_map(BinJosn).
request_api(Method, Url, Auth) -> request_api(Method, Url, Auth) ->
@ -332,7 +332,7 @@ request_api(Method, Url, QueryParams, Auth, Body) ->
"" -> Url; "" -> Url;
_ -> Url ++ "?" ++ QueryParams _ -> Url ++ "?" ++ QueryParams
end, end,
do_request_api(Method, {NewUrl, [Auth], "application/json", emqx_json:encode(Body)}). do_request_api(Method, {NewUrl, [Auth], "application/json", emqx_utils_json:encode(Body)}).
do_request_api(Method, Request) -> do_request_api(Method, Request) ->
case httpc:request(Method, Request, [], [{body_format, binary}]) of case httpc:request(Method, Request, [], [{body_format, binary}]) of

View File

@ -1,5 +1,6 @@
%% -*- mode: erlang -*- %% -*- mode: erlang -*-
{erl_opts, [debug_info]}. {erl_opts, [debug_info]}.
{deps, [ {deps, [
{emqx, {path, "../emqx"}} {emqx, {path, "../emqx"}},
{emqx_utils, {path, "../emqx_utils"}}
]}. ]}.

View File

@ -74,7 +74,7 @@ gateway(["load", Name, Conf]) ->
case case
emqx_gateway_conf:load_gateway( emqx_gateway_conf:load_gateway(
bin(Name), bin(Name),
emqx_json:decode(Conf, [return_maps]) emqx_utils_json:decode(Conf, [return_maps])
) )
of of
{ok, _} -> {ok, _} ->

View File

@ -404,7 +404,7 @@ return_http_error(Code, Msg) ->
-spec reason2msg({atom(), map()} | any()) -> error | string(). -spec reason2msg({atom(), map()} | any()) -> error | string().
reason2msg({badconf, #{key := Key, value := Value, reason := Reason}}) -> reason2msg({badconf, #{key := Key, value := Value, reason := Reason}}) ->
NValue = NValue =
case emqx_json:safe_encode(Value) of case emqx_utils_json:safe_encode(Value) of
{ok, Str} -> Str; {ok, Str} -> Str;
{error, _} -> emqx_gateway_utils:stringfy(Value) {error, _} -> emqx_gateway_utils:stringfy(Value)
end, end,

View File

@ -153,7 +153,7 @@ on_start_auth(authn_http) ->
Handler = fun(Req0, State) -> Handler = fun(Req0, State) ->
ct:pal("Authn Req:~p~nState:~p~n", [Req0, State]), ct:pal("Authn Req:~p~nState:~p~n", [Req0, State]),
Headers = #{<<"content-type">> => <<"application/json">>}, Headers = #{<<"content-type">> => <<"application/json">>},
Response = jiffy:encode(#{result => allow, is_superuser => false}), Response = emqx_utils_json:encode(#{result => allow, is_superuser => false}),
case cowboy_req:match_qs([username, password], Req0) of case cowboy_req:match_qs([username, password], Req0) of
#{ #{
username := <<"admin">>, username := <<"admin">>,

View File

@ -266,7 +266,7 @@ t_case_exproto(_) ->
Mod:send(Sock, ConnBin), Mod:send(Sock, ConnBin),
{ok, Recv} = Mod:recv(Sock, 5000), {ok, Recv} = Mod:recv(Sock, 5000),
C = ?FUNCTOR(Bin, emqx_json:decode(Bin, [return_maps])), C = ?FUNCTOR(Bin, emqx_utils_json:decode(Bin, [return_maps])),
?assertEqual(C(Expect), C(Recv)) ?assertEqual(C(Expect), C(Recv))
end end
) )

View File

@ -165,7 +165,7 @@ t_case_lwm2m(_) ->
Test("lwm2m", fun(SubTopic, Msg) -> Test("lwm2m", fun(SubTopic, Msg) ->
?assertEqual(true, lists:member(SubTopic, test_mqtt_broker:get_subscrbied_topics())), ?assertEqual(true, lists:member(SubTopic, test_mqtt_broker:get_subscrbied_topics())),
Payload = emqx_message:payload(Msg), Payload = emqx_message:payload(Msg),
Cmd = emqx_json:decode(Payload, [return_maps]), Cmd = emqx_utils_json:decode(Payload, [return_maps]),
?assertMatch(#{<<"msgType">> := <<"register">>, <<"data">> := _}, Cmd) ?assertMatch(#{<<"msgType">> := <<"register">>, <<"data">> := _}, Cmd)
end), end),
@ -350,7 +350,7 @@ t_case_exproto_publish(_) ->
Mod:send(Sock, ConnBin), Mod:send(Sock, ConnBin),
{ok, Recv} = Mod:recv(Sock, 5000), {ok, Recv} = Mod:recv(Sock, 5000),
C = ?FUNCTOR(Bin, emqx_json:decode(Bin, [return_maps])), C = ?FUNCTOR(Bin, emqx_utils_json:decode(Bin, [return_maps])),
?assertEqual(C(SvrMod:frame_connack(0)), C(Recv)), ?assertEqual(C(SvrMod:frame_connack(0)), C(Recv)),
Send = fun() -> Send = fun() ->
@ -387,7 +387,7 @@ t_case_exproto_subscribe(_) ->
Mod:send(Sock, ConnBin), Mod:send(Sock, ConnBin),
{ok, Recv} = Mod:recv(Sock, WaitTime), {ok, Recv} = Mod:recv(Sock, WaitTime),
C = ?FUNCTOR(Bin, emqx_json:decode(Bin, [return_maps])), C = ?FUNCTOR(Bin, emqx_utils_json:decode(Bin, [return_maps])),
?assertEqual(C(SvrMod:frame_connack(0)), C(Recv)), ?assertEqual(C(SvrMod:frame_connack(0)), C(Recv)),
SubBin = SvrMod:frame_subscribe(Topic, 0), SubBin = SvrMod:frame_subscribe(Topic, 0),

View File

@ -160,7 +160,7 @@ do_request(Mth, Req) ->
#{}; #{};
_ -> _ ->
emqx_map_lib:unsafe_atom_key_map( emqx_map_lib:unsafe_atom_key_map(
emqx_json:decode(Resp, [return_maps]) emqx_utils_json:decode(Resp, [return_maps])
) )
end, end,
{Code, NResp}; {Code, NResp};
@ -172,7 +172,7 @@ req(Path, Qs) ->
{url(Path, Qs), auth([])}. {url(Path, Qs), auth([])}.
req(Path, Qs, Body) -> req(Path, Qs, Body) ->
{url(Path, Qs), auth([]), "application/json", emqx_json:encode(Body)}. {url(Path, Qs), auth([]), "application/json", emqx_utils_json:encode(Body)}.
url(Path, []) -> url(Path, []) ->
lists:concat([?http_api_host, Path]); lists:concat([?http_api_host, Path]);

View File

@ -1,4 +1,6 @@
{erl_opts, [debug_info]}. {erl_opts, [debug_info]}.
{deps, [ {emqx, {path, "../../apps/emqx"}}, {deps, [
{emqx_gateway, {path, "../../apps/emqx_gateway"}} {emqx, {path, "../emqx"}},
{emqx_utils, {path, "../emqx_utils"}},
{emqx_gateway, {path, "../emqx_gateway"}}
]}. ]}.

View File

@ -92,7 +92,7 @@ t_send_request_api(_) ->
Req Req
), ),
#{<<"token">> := RToken, <<"payload">> := RPayload} = #{<<"token">> := RToken, <<"payload">> := RPayload} =
emqx_json:decode(Response, [return_maps]), emqx_utils_json:decode(Response, [return_maps]),
?assertEqual(Token, RToken), ?assertEqual(Token, RToken),
?assertEqual(Payload, RPayload) ?assertEqual(Payload, RPayload)
end, end,

View File

@ -1,6 +1,8 @@
{erl_opts, [debug_info]}. {erl_opts, [debug_info]}.
{deps, [ {emqx, {path, "../../apps/emqx"}}, {deps, [
{emqx_gateway, {path, "../../apps/emqx_gateway"}} {emqx, {path, "../emqx"}},
{emqx_utils, {path, "../emqx_utils"}},
{emqx_gateway, {path, "../emqx_gateway"}}
]}. ]}.
{plugins, [ {plugins, [

View File

@ -148,7 +148,7 @@ on_received_bytes(Stream, _Md) ->
fun(Reqs) -> fun(Reqs) ->
lists:foreach( lists:foreach(
fun(#{conn := Conn, bytes := Bytes}) -> fun(#{conn := Conn, bytes := Bytes}) ->
#{<<"type">> := Type} = Params = emqx_json:decode(Bytes, [return_maps]), #{<<"type">> := Type} = Params = emqx_utils_json:decode(Bytes, [return_maps]),
_ = handle_in(Conn, Type, Params) _ = handle_in(Conn, Type, Params)
end, end,
Reqs Reqs
@ -284,16 +284,16 @@ handle_out(Conn, ?TYPE_DISCONNECT) ->
%% Frame %% Frame
frame_connect(ClientInfo, Password) -> frame_connect(ClientInfo, Password) ->
emqx_json:encode(#{ emqx_utils_json:encode(#{
type => ?TYPE_CONNECT, type => ?TYPE_CONNECT,
clientinfo => ClientInfo, clientinfo => ClientInfo,
password => Password password => Password
}). }).
frame_connack(Code) -> frame_connack(Code) ->
emqx_json:encode(#{type => ?TYPE_CONNACK, code => Code}). emqx_utils_json:encode(#{type => ?TYPE_CONNACK, code => Code}).
frame_publish(Topic, Qos, Payload) -> frame_publish(Topic, Qos, Payload) ->
emqx_json:encode(#{ emqx_utils_json:encode(#{
type => ?TYPE_PUBLISH, type => ?TYPE_PUBLISH,
topic => Topic, topic => Topic,
qos => Qos, qos => Qos,
@ -301,19 +301,19 @@ frame_publish(Topic, Qos, Payload) ->
}). }).
frame_puback(Code) -> frame_puback(Code) ->
emqx_json:encode(#{type => ?TYPE_PUBACK, code => Code}). emqx_utils_json:encode(#{type => ?TYPE_PUBACK, code => Code}).
frame_subscribe(Topic, Qos) -> frame_subscribe(Topic, Qos) ->
emqx_json:encode(#{type => ?TYPE_SUBSCRIBE, topic => Topic, qos => Qos}). emqx_utils_json:encode(#{type => ?TYPE_SUBSCRIBE, topic => Topic, qos => Qos}).
frame_suback(Code) -> frame_suback(Code) ->
emqx_json:encode(#{type => ?TYPE_SUBACK, code => Code}). emqx_utils_json:encode(#{type => ?TYPE_SUBACK, code => Code}).
frame_unsubscribe(Topic) -> frame_unsubscribe(Topic) ->
emqx_json:encode(#{type => ?TYPE_UNSUBSCRIBE, topic => Topic}). emqx_utils_json:encode(#{type => ?TYPE_UNSUBSCRIBE, topic => Topic}).
frame_unsuback(Code) -> frame_unsuback(Code) ->
emqx_json:encode(#{type => ?TYPE_UNSUBACK, code => Code}). emqx_utils_json:encode(#{type => ?TYPE_UNSUBACK, code => Code}).
frame_disconnect() -> frame_disconnect() ->
emqx_json:encode(#{type => ?TYPE_DISCONNECT}). emqx_utils_json:encode(#{type => ?TYPE_DISCONNECT}).

View File

@ -351,7 +351,7 @@ opaque_to_json(BaseName, Binary) ->
[#{path => BaseName, value => base64:encode(Binary)}]. [#{path => BaseName, value => base64:encode(Binary)}].
translate_json(JSONBin) -> translate_json(JSONBin) ->
JSONTerm = emqx_json:decode(JSONBin, [return_maps]), JSONTerm = emqx_utils_json:decode(JSONBin, [return_maps]),
BaseName = maps:get(<<"bn">>, JSONTerm, <<>>), BaseName = maps:get(<<"bn">>, JSONTerm, <<>>),
ElementList = maps:get(<<"e">>, JSONTerm, []), ElementList = maps:get(<<"e">>, JSONTerm, []),
translate_element(BaseName, ElementList, []). translate_element(BaseName, ElementList, []).

View File

@ -737,7 +737,7 @@ proto_publish(
Epn, Epn,
Qos, Qos,
MountedTopic, MountedTopic,
emqx_json:encode(Payload), emqx_utils_json:encode(Payload),
#{}, #{},
Headers Headers
), ),
@ -786,7 +786,7 @@ deliver_to_coap(AlternatePath, JsonData, MQTT, CacheMode, WithContext, Session)
is_binary(JsonData) is_binary(JsonData)
-> ->
try try
TermData = emqx_json:decode(JsonData, [return_maps]), TermData = emqx_utils_json:decode(JsonData, [return_maps]),
deliver_to_coap(AlternatePath, TermData, MQTT, CacheMode, WithContext, Session) deliver_to_coap(AlternatePath, TermData, MQTT, CacheMode, WithContext, Session)
catch catch
ExClass:Error:ST -> ExClass:Error:ST ->

View File

@ -402,7 +402,7 @@ case01_register_report(Config) ->
timer:sleep(50), timer:sleep(50),
true = lists:member(SubTopic, test_mqtt_broker:get_subscrbied_topics()), true = lists:member(SubTopic, test_mqtt_broker:get_subscrbied_topics()),
ReadResult = emqx_json:encode( ReadResult = emqx_utils_json:encode(
#{ #{
<<"msgType">> => <<"register">>, <<"msgType">> => <<"register">>,
<<"data">> => #{ <<"data">> => #{
@ -478,7 +478,7 @@ case02_update_deregister(Config) ->
?LOGT("Options got: ~p", [Opts]), ?LOGT("Options got: ~p", [Opts]),
Location = maps:get(location_path, Opts), Location = maps:get(location_path, Opts),
Register = emqx_json:encode( Register = emqx_utils_json:encode(
#{ #{
<<"msgType">> => <<"register">>, <<"msgType">> => <<"register">>,
<<"data">> => #{ <<"data">> => #{
@ -521,7 +521,7 @@ case02_update_deregister(Config) ->
} = test_recv_coap_response(UdpSock), } = test_recv_coap_response(UdpSock),
{ok, changed} = Method2, {ok, changed} = Method2,
MsgId2 = RspId2, MsgId2 = RspId2,
Update = emqx_json:encode( Update = emqx_utils_json:encode(
#{ #{
<<"msgType">> => <<"update">>, <<"msgType">> => <<"update">>,
<<"data">> => #{ <<"data">> => #{
@ -754,7 +754,7 @@ case08_reregister(Config) ->
timer:sleep(50), timer:sleep(50),
true = lists:member(SubTopic, test_mqtt_broker:get_subscrbied_topics()), true = lists:member(SubTopic, test_mqtt_broker:get_subscrbied_topics()),
ReadResult = emqx_json:encode( ReadResult = emqx_utils_json:encode(
#{ #{
<<"msgType">> => <<"register">>, <<"msgType">> => <<"register">>,
<<"data">> => #{ <<"data">> => #{
@ -871,7 +871,7 @@ case10_read(Config) ->
<<"path">> => <<"/3/0/0">> <<"path">> => <<"/3/0/0">>
} }
}, },
CommandJson = emqx_json:encode(Command), CommandJson = emqx_utils_json:encode(Command),
?LOGT("CommandJson=~p", [CommandJson]), ?LOGT("CommandJson=~p", [CommandJson]),
test_mqtt_broker:publish(CommandTopic, CommandJson, 0), test_mqtt_broker:publish(CommandTopic, CommandJson, 0),
timer:sleep(50), timer:sleep(50),
@ -902,7 +902,7 @@ case10_read(Config) ->
), ),
timer:sleep(100), timer:sleep(100),
ReadResult = emqx_json:encode( ReadResult = emqx_utils_json:encode(
#{ #{
<<"requestID">> => CmdId, <<"requestID">> => CmdId,
<<"cacheID">> => CmdId, <<"cacheID">> => CmdId,
@ -957,7 +957,7 @@ case10_read_bad_request(Config) ->
<<"path">> => <<"/3333/0/0">> <<"path">> => <<"/3333/0/0">>
} }
}, },
CommandJson = emqx_json:encode(Command), CommandJson = emqx_utils_json:encode(Command),
?LOGT("CommandJson=~p", [CommandJson]), ?LOGT("CommandJson=~p", [CommandJson]),
test_mqtt_broker:publish(CommandTopic, CommandJson, 0), test_mqtt_broker:publish(CommandTopic, CommandJson, 0),
timer:sleep(50), timer:sleep(50),
@ -979,7 +979,7 @@ case10_read_bad_request(Config) ->
), ),
timer:sleep(100), timer:sleep(100),
ReadResult = emqx_json:encode(#{ ReadResult = emqx_utils_json:encode(#{
<<"requestID">> => CmdId, <<"requestID">> => CmdId,
<<"cacheID">> => CmdId, <<"cacheID">> => CmdId,
<<"msgType">> => <<"read">>, <<"msgType">> => <<"read">>,
@ -1015,7 +1015,7 @@ case10_read_separate_ack(Config) ->
<<"path">> => <<"/3/0/0">> <<"path">> => <<"/3/0/0">>
} }
}, },
CommandJson = emqx_json:encode(Command), CommandJson = emqx_utils_json:encode(Command),
?LOGT("CommandJson=~p", [CommandJson]), ?LOGT("CommandJson=~p", [CommandJson]),
test_mqtt_broker:publish(CommandTopic, CommandJson, 0), test_mqtt_broker:publish(CommandTopic, CommandJson, 0),
timer:sleep(50), timer:sleep(50),
@ -1032,7 +1032,7 @@ case10_read_separate_ack(Config) ->
?assertEqual(<<>>, Payload2), ?assertEqual(<<>>, Payload2),
test_send_empty_ack(UdpSock, "127.0.0.1", ?PORT, Request2), test_send_empty_ack(UdpSock, "127.0.0.1", ?PORT, Request2),
ReadResultACK = emqx_json:encode( ReadResultACK = emqx_utils_json:encode(
#{ #{
<<"requestID">> => CmdId, <<"requestID">> => CmdId,
<<"cacheID">> => CmdId, <<"cacheID">> => CmdId,
@ -1057,7 +1057,7 @@ case10_read_separate_ack(Config) ->
), ),
timer:sleep(100), timer:sleep(100),
ReadResult = emqx_json:encode( ReadResult = emqx_utils_json:encode(
#{ #{
<<"requestID">> => CmdId, <<"requestID">> => CmdId,
<<"cacheID">> => CmdId, <<"cacheID">> => CmdId,
@ -1100,7 +1100,7 @@ case11_read_object_tlv(Config) ->
<<"path">> => <<"/3/0">> <<"path">> => <<"/3/0">>
} }
}, },
CommandJson = emqx_json:encode(Command), CommandJson = emqx_utils_json:encode(Command),
?LOGT("CommandJson=~p", [CommandJson]), ?LOGT("CommandJson=~p", [CommandJson]),
test_mqtt_broker:publish(CommandTopic, CommandJson, 0), test_mqtt_broker:publish(CommandTopic, CommandJson, 0),
timer:sleep(50), timer:sleep(50),
@ -1132,7 +1132,7 @@ case11_read_object_tlv(Config) ->
), ),
timer:sleep(100), timer:sleep(100),
ReadResult = emqx_json:encode( ReadResult = emqx_utils_json:encode(
#{ #{
<<"requestID">> => CmdId, <<"requestID">> => CmdId,
<<"cacheID">> => CmdId, <<"cacheID">> => CmdId,
@ -1185,7 +1185,7 @@ case11_read_object_json(Config) ->
<<"path">> => <<"/3/0">> <<"path">> => <<"/3/0">>
} }
}, },
CommandJson = emqx_json:encode(Command), CommandJson = emqx_utils_json:encode(Command),
?LOGT("CommandJson=~p", [CommandJson]), ?LOGT("CommandJson=~p", [CommandJson]),
test_mqtt_broker:publish(CommandTopic, CommandJson, 0), test_mqtt_broker:publish(CommandTopic, CommandJson, 0),
timer:sleep(50), timer:sleep(50),
@ -1215,7 +1215,7 @@ case11_read_object_json(Config) ->
), ),
timer:sleep(100), timer:sleep(100),
ReadResult = emqx_json:encode( ReadResult = emqx_utils_json:encode(
#{ #{
<<"requestID">> => CmdId, <<"requestID">> => CmdId,
<<"cacheID">> => CmdId, <<"cacheID">> => CmdId,
@ -1267,7 +1267,7 @@ case12_read_resource_opaque(Config) ->
<<"path">> => <<"/3/0/8">> <<"path">> => <<"/3/0/8">>
} }
}, },
CommandJson = emqx_json:encode(Command), CommandJson = emqx_utils_json:encode(Command),
?LOGT("CommandJson=~p", [CommandJson]), ?LOGT("CommandJson=~p", [CommandJson]),
test_mqtt_broker:publish(CommandTopic, CommandJson, 0), test_mqtt_broker:publish(CommandTopic, CommandJson, 0),
timer:sleep(50), timer:sleep(50),
@ -1293,7 +1293,7 @@ case12_read_resource_opaque(Config) ->
), ),
timer:sleep(100), timer:sleep(100),
ReadResult = emqx_json:encode( ReadResult = emqx_utils_json:encode(
#{ #{
<<"requestID">> => CmdId, <<"requestID">> => CmdId,
<<"cacheID">> => CmdId, <<"cacheID">> => CmdId,
@ -1335,7 +1335,7 @@ case13_read_no_xml(Config) ->
<<"msgType">> => <<"read">>, <<"msgType">> => <<"read">>,
<<"data">> => #{<<"path">> => <<"/9723/0/0">>} <<"data">> => #{<<"path">> => <<"/9723/0/0">>}
}, },
CommandJson = emqx_json:encode(Command), CommandJson = emqx_utils_json:encode(Command),
?LOGT("CommandJson=~p", [CommandJson]), ?LOGT("CommandJson=~p", [CommandJson]),
test_mqtt_broker:publish(CommandTopic, CommandJson, 0), test_mqtt_broker:publish(CommandTopic, CommandJson, 0),
timer:sleep(50), timer:sleep(50),
@ -1360,7 +1360,7 @@ case13_read_no_xml(Config) ->
), ),
timer:sleep(100), timer:sleep(100),
ReadResult = emqx_json:encode( ReadResult = emqx_utils_json:encode(
#{ #{
<<"requestID">> => CmdId, <<"requestID">> => CmdId,
<<"cacheID">> => CmdId, <<"cacheID">> => CmdId,
@ -1399,7 +1399,7 @@ case20_single_write(Config) ->
<<"value">> => <<"12345">> <<"value">> => <<"12345">>
} }
}, },
CommandJson = emqx_json:encode(Command), CommandJson = emqx_utils_json:encode(Command),
test_mqtt_broker:publish(CommandTopic, CommandJson, 0), test_mqtt_broker:publish(CommandTopic, CommandJson, 0),
timer:sleep(50), timer:sleep(50),
Request2 = test_recv_coap_request(UdpSock), Request2 = test_recv_coap_request(UdpSock),
@ -1426,7 +1426,7 @@ case20_single_write(Config) ->
), ),
timer:sleep(100), timer:sleep(100),
ReadResult = emqx_json:encode( ReadResult = emqx_utils_json:encode(
#{ #{
<<"requestID">> => CmdId, <<"requestID">> => CmdId,
<<"cacheID">> => CmdId, <<"cacheID">> => CmdId,
@ -1470,7 +1470,7 @@ case20_write(Config) ->
] ]
} }
}, },
CommandJson = emqx_json:encode(Command), CommandJson = emqx_utils_json:encode(Command),
test_mqtt_broker:publish(CommandTopic, CommandJson, 0), test_mqtt_broker:publish(CommandTopic, CommandJson, 0),
timer:sleep(50), timer:sleep(50),
Request2 = test_recv_coap_request(UdpSock), Request2 = test_recv_coap_request(UdpSock),
@ -1497,7 +1497,7 @@ case20_write(Config) ->
), ),
timer:sleep(100), timer:sleep(100),
WriteResult = emqx_json:encode( WriteResult = emqx_utils_json:encode(
#{ #{
<<"requestID">> => CmdId, <<"requestID">> => CmdId,
<<"cacheID">> => CmdId, <<"cacheID">> => CmdId,
@ -1547,7 +1547,7 @@ case21_write_object(Config) ->
] ]
} }
}, },
CommandJson = emqx_json:encode(Command), CommandJson = emqx_utils_json:encode(Command),
test_mqtt_broker:publish(CommandTopic, CommandJson, 0), test_mqtt_broker:publish(CommandTopic, CommandJson, 0),
timer:sleep(50), timer:sleep(50),
Request2 = test_recv_coap_request(UdpSock), Request2 = test_recv_coap_request(UdpSock),
@ -1574,7 +1574,7 @@ case21_write_object(Config) ->
), ),
timer:sleep(100), timer:sleep(100),
ReadResult = emqx_json:encode( ReadResult = emqx_utils_json:encode(
#{ #{
<<"requestID">> => CmdId, <<"requestID">> => CmdId,
<<"cacheID">> => CmdId, <<"cacheID">> => CmdId,
@ -1618,7 +1618,7 @@ case22_write_error(Config) ->
] ]
} }
}, },
CommandJson = emqx_json:encode(Command), CommandJson = emqx_utils_json:encode(Command),
test_mqtt_broker:publish(CommandTopic, CommandJson, 0), test_mqtt_broker:publish(CommandTopic, CommandJson, 0),
timer:sleep(50), timer:sleep(50),
Request2 = test_recv_coap_request(UdpSock), Request2 = test_recv_coap_request(UdpSock),
@ -1639,7 +1639,7 @@ case22_write_error(Config) ->
), ),
timer:sleep(100), timer:sleep(100),
ReadResult = emqx_json:encode( ReadResult = emqx_utils_json:encode(
#{ #{
<<"requestID">> => CmdId, <<"requestID">> => CmdId,
<<"cacheID">> => CmdId, <<"cacheID">> => CmdId,
@ -1677,7 +1677,7 @@ case_create_basic(Config) ->
<<"basePath">> => <<"/5">> <<"basePath">> => <<"/5">>
} }
}, },
CommandJson = emqx_json:encode(Command), CommandJson = emqx_utils_json:encode(Command),
test_mqtt_broker:publish(CommandTopic, CommandJson, 0), test_mqtt_broker:publish(CommandTopic, CommandJson, 0),
timer:sleep(50), timer:sleep(50),
Request2 = test_recv_coap_request(UdpSock), Request2 = test_recv_coap_request(UdpSock),
@ -1703,7 +1703,7 @@ case_create_basic(Config) ->
), ),
timer:sleep(100), timer:sleep(100),
ReadResult = emqx_json:encode( ReadResult = emqx_utils_json:encode(
#{ #{
<<"requestID">> => CmdId, <<"requestID">> => CmdId,
<<"cacheID">> => CmdId, <<"cacheID">> => CmdId,
@ -1738,7 +1738,7 @@ case_delete_basic(Config) ->
<<"msgType">> => <<"delete">>, <<"msgType">> => <<"delete">>,
<<"data">> => #{<<"path">> => <<"/5/0">>} <<"data">> => #{<<"path">> => <<"/5/0">>}
}, },
CommandJson = emqx_json:encode(Command), CommandJson = emqx_utils_json:encode(Command),
test_mqtt_broker:publish(CommandTopic, CommandJson, 0), test_mqtt_broker:publish(CommandTopic, CommandJson, 0),
timer:sleep(50), timer:sleep(50),
Request2 = test_recv_coap_request(UdpSock), Request2 = test_recv_coap_request(UdpSock),
@ -1764,7 +1764,7 @@ case_delete_basic(Config) ->
), ),
timer:sleep(100), timer:sleep(100),
ReadResult = emqx_json:encode( ReadResult = emqx_utils_json:encode(
#{ #{
<<"requestID">> => CmdId, <<"requestID">> => CmdId,
<<"cacheID">> => CmdId, <<"cacheID">> => CmdId,
@ -1804,7 +1804,7 @@ case30_execute(Config) ->
<<"args">> => <<"2,7">> <<"args">> => <<"2,7">>
} }
}, },
CommandJson = emqx_json:encode(Command), CommandJson = emqx_utils_json:encode(Command),
test_mqtt_broker:publish(CommandTopic, CommandJson, 0), test_mqtt_broker:publish(CommandTopic, CommandJson, 0),
timer:sleep(50), timer:sleep(50),
Request2 = test_recv_coap_request(UdpSock), Request2 = test_recv_coap_request(UdpSock),
@ -1830,7 +1830,7 @@ case30_execute(Config) ->
), ),
timer:sleep(100), timer:sleep(100),
ReadResult = emqx_json:encode( ReadResult = emqx_utils_json:encode(
#{ #{
<<"requestID">> => CmdId, <<"requestID">> => CmdId,
<<"cacheID">> => CmdId, <<"cacheID">> => CmdId,
@ -1868,7 +1868,7 @@ case31_execute_error(Config) ->
<<"args">> => <<"2,7">> <<"args">> => <<"2,7">>
} }
}, },
CommandJson = emqx_json:encode(Command), CommandJson = emqx_utils_json:encode(Command),
test_mqtt_broker:publish(CommandTopic, CommandJson, 0), test_mqtt_broker:publish(CommandTopic, CommandJson, 0),
timer:sleep(50), timer:sleep(50),
Request2 = test_recv_coap_request(UdpSock), Request2 = test_recv_coap_request(UdpSock),
@ -1894,7 +1894,7 @@ case31_execute_error(Config) ->
), ),
timer:sleep(100), timer:sleep(100),
ReadResult = emqx_json:encode( ReadResult = emqx_utils_json:encode(
#{ #{
<<"requestID">> => CmdId, <<"requestID">> => CmdId,
<<"cacheID">> => CmdId, <<"cacheID">> => CmdId,
@ -1931,7 +1931,7 @@ case40_discover(Config) ->
<<"path">> => <<"/3/0/7">> <<"path">> => <<"/3/0/7">>
} }
}, },
CommandJson = emqx_json:encode(Command), CommandJson = emqx_utils_json:encode(Command),
test_mqtt_broker:publish(CommandTopic, CommandJson, 0), test_mqtt_broker:publish(CommandTopic, CommandJson, 0),
timer:sleep(50), timer:sleep(50),
Request2 = test_recv_coap_request(UdpSock), Request2 = test_recv_coap_request(UdpSock),
@ -1961,7 +1961,7 @@ case40_discover(Config) ->
), ),
timer:sleep(100), timer:sleep(100),
ReadResult = emqx_json:encode( ReadResult = emqx_utils_json:encode(
#{ #{
<<"requestID">> => CmdId, <<"requestID">> => CmdId,
<<"cacheID">> => CmdId, <<"cacheID">> => CmdId,
@ -2006,7 +2006,7 @@ case50_write_attribute(Config) ->
<<"lt">> => <<"5">> <<"lt">> => <<"5">>
} }
}, },
CommandJson = emqx_json:encode(Command), CommandJson = emqx_utils_json:encode(Command),
test_mqtt_broker:publish(CommandTopic, CommandJson, 0), test_mqtt_broker:publish(CommandTopic, CommandJson, 0),
timer:sleep(100), timer:sleep(100),
Request2 = test_recv_coap_request(UdpSock), Request2 = test_recv_coap_request(UdpSock),
@ -2042,7 +2042,7 @@ case50_write_attribute(Config) ->
), ),
timer:sleep(100), timer:sleep(100),
ReadResult = emqx_json:encode( ReadResult = emqx_utils_json:encode(
#{ #{
<<"requestID">> => CmdId, <<"requestID">> => CmdId,
<<"cacheID">> => CmdId, <<"cacheID">> => CmdId,
@ -2079,7 +2079,7 @@ case60_observe(Config) ->
<<"msgType">> => <<"observe">>, <<"msgType">> => <<"observe">>,
<<"data">> => #{<<"path">> => <<"/3/0/10">>} <<"data">> => #{<<"path">> => <<"/3/0/10">>}
}, },
CommandJson = emqx_json:encode(Command), CommandJson = emqx_utils_json:encode(Command),
test_mqtt_broker:publish(CommandTopic, CommandJson, 0), test_mqtt_broker:publish(CommandTopic, CommandJson, 0),
timer:sleep(50), timer:sleep(50),
Request2 = test_recv_coap_request(UdpSock), Request2 = test_recv_coap_request(UdpSock),
@ -2106,7 +2106,7 @@ case60_observe(Config) ->
), ),
timer:sleep(100), timer:sleep(100),
ReadResult = emqx_json:encode( ReadResult = emqx_utils_json:encode(
#{ #{
<<"requestID">> => CmdId, <<"requestID">> => CmdId,
<<"cacheID">> => CmdId, <<"cacheID">> => CmdId,
@ -2141,7 +2141,7 @@ case60_observe(Config) ->
timer:sleep(100), timer:sleep(100),
#coap_message{} = test_recv_coap_response(UdpSock), #coap_message{} = test_recv_coap_response(UdpSock),
ReadResult2 = emqx_json:encode( ReadResult2 = emqx_utils_json:encode(
#{ #{
<<"requestID">> => CmdId, <<"requestID">> => CmdId,
<<"cacheID">> => CmdId, <<"cacheID">> => CmdId,
@ -2173,7 +2173,7 @@ case60_observe(Config) ->
<<"path">> => <<"/3/0/10">> <<"path">> => <<"/3/0/10">>
} }
}, },
CommandJson3 = emqx_json:encode(Command3), CommandJson3 = emqx_utils_json:encode(Command3),
test_mqtt_broker:publish(CommandTopic, CommandJson3, 0), test_mqtt_broker:publish(CommandTopic, CommandJson3, 0),
timer:sleep(50), timer:sleep(50),
Request3 = test_recv_coap_request(UdpSock), Request3 = test_recv_coap_request(UdpSock),
@ -2200,7 +2200,7 @@ case60_observe(Config) ->
), ),
timer:sleep(100), timer:sleep(100),
ReadResult3 = emqx_json:encode( ReadResult3 = emqx_utils_json:encode(
#{ #{
<<"requestID">> => CmdId3, <<"requestID">> => CmdId3,
<<"cacheID">> => CmdId3, <<"cacheID">> => CmdId3,
@ -2242,7 +2242,7 @@ case60_observe(Config) ->
%% MsgId1), %% MsgId1),
%% #coap_message{method = Method1} = test_recv_coap_response(UdpSock), %% #coap_message{method = Method1} = test_recv_coap_response(UdpSock),
%% ?assertEqual({ok,created}, Method1), %% ?assertEqual({ok,created}, Method1),
%% ReadResult = emqx_json:encode( %% ReadResult = emqx_utils_json:encode(
%% #{<<"msgType">> => <<"register">>, %% #{<<"msgType">> => <<"register">>,
%% <<"data">> => #{ %% <<"data">> => #{
%% <<"alternatePath">> => <<"/">>, %% <<"alternatePath">> => <<"/">>,
@ -2268,7 +2268,7 @@ case60_observe(Config) ->
%% <<"path">> => <<"/19/0/0">> %% <<"path">> => <<"/19/0/0">>
%% } %% }
%% }, %% },
%% CommandJson = emqx_json:encode(Command), %% CommandJson = emqx_utils_json:encode(Command),
%% test_mqtt_broker:publish(CommandTopic, CommandJson, 0), %% test_mqtt_broker:publish(CommandTopic, CommandJson, 0),
%% timer:sleep(50), %% timer:sleep(50),
%% Request2 = test_recv_coap_request(UdpSock), %% Request2 = test_recv_coap_request(UdpSock),
@ -2325,7 +2325,7 @@ case60_observe(Config) ->
%% <<"value">> => base64:encode(<<12345:32>>) %% <<"value">> => base64:encode(<<12345:32>>)
%% }}, %% }},
%% %%
%% CommandJson = emqx_json:encode(Command), %% CommandJson = emqx_utils_json:encode(Command),
%% test_mqtt_broker:publish(CommandTopic, CommandJson, 0), %% test_mqtt_broker:publish(CommandTopic, CommandJson, 0),
%% timer:sleep(50), %% timer:sleep(50),
%% Request2 = test_recv_coap_request(UdpSock), %% Request2 = test_recv_coap_request(UdpSock),
@ -2342,7 +2342,7 @@ case60_observe(Config) ->
%% {ok, changed}, #coap_content{}, Request2, true), %% {ok, changed}, #coap_content{}, Request2, true),
%% timer:sleep(100), %% timer:sleep(100),
%% %%
%% ReadResult = emqx_json:encode( %% ReadResult = emqx_utils_json:encode(
%% #{<<"requestID">> => CmdId, %% #{<<"requestID">> => CmdId,
%% <<"cacheID">> => CmdId, %% <<"cacheID">> => CmdId,
%% <<"data">> => #{ %% <<"data">> => #{
@ -2502,7 +2502,7 @@ send_read_command_1(CmdId, _UdpSock) ->
<<"msgType">> => <<"read">>, <<"msgType">> => <<"read">>,
<<"data">> => #{<<"path">> => <<"/3/0/0">>} <<"data">> => #{<<"path">> => <<"/3/0/0">>}
}, },
CommandJson = emqx_json:encode(Command), CommandJson = emqx_utils_json:encode(Command),
test_mqtt_broker:publish(CommandTopic, CommandJson, 0), test_mqtt_broker:publish(CommandTopic, CommandJson, 0),
timer:sleep(50). timer:sleep(50).
@ -2528,7 +2528,7 @@ verify_read_response_1(CmdId, UdpSock) ->
true true
), ),
ReadResult = emqx_json:encode( ReadResult = emqx_utils_json:encode(
#{ #{
<<"requestID">> => CmdId, <<"requestID">> => CmdId,
<<"cacheID">> => CmdId, <<"cacheID">> => CmdId,

View File

@ -131,7 +131,7 @@ t_lookup_read(Config) ->
<<"path">> => <<"/3/0/0">> <<"path">> => <<"/3/0/0">>
} }
}, },
CommandJson = emqx_json:encode(Command), CommandJson = emqx_utils_json:encode(Command),
?LOGT("CommandJson=~p", [CommandJson]), ?LOGT("CommandJson=~p", [CommandJson]),
test_mqtt_broker:publish(CommandTopic, CommandJson, 0), test_mqtt_broker:publish(CommandTopic, CommandJson, 0),
@ -178,7 +178,7 @@ t_lookup_discover(Config) ->
<<"path">> => <<"/3/0/7">> <<"path">> => <<"/3/0/7">>
} }
}, },
CommandJson = emqx_json:encode(Command), CommandJson = emqx_utils_json:encode(Command),
test_mqtt_broker:publish(CommandTopic, CommandJson, 0), test_mqtt_broker:publish(CommandTopic, CommandJson, 0),
timer:sleep(200), timer:sleep(200),
@ -350,10 +350,10 @@ no_received_request(ClientId, Path, Action) ->
<<"codeMsg">> => <<"reply_not_received">>, <<"codeMsg">> => <<"reply_not_received">>,
<<"path">> => Path <<"path">> => Path
}, },
?assertEqual(NotReceived, emqx_json:decode(Response, [return_maps])). ?assertEqual(NotReceived, emqx_utils_json:decode(Response, [return_maps])).
normal_received_request(ClientId, Path, Action) -> normal_received_request(ClientId, Path, Action) ->
Response = call_lookup_api(ClientId, Path, Action), Response = call_lookup_api(ClientId, Path, Action),
RCont = emqx_json:decode(Response, [return_maps]), RCont = emqx_utils_json:decode(Response, [return_maps]),
?assertEqual(list_to_binary(ClientId), maps:get(<<"clientid">>, RCont, undefined)), ?assertEqual(list_to_binary(ClientId), maps:get(<<"clientid">>, RCont, undefined)),
?assertEqual(Path, maps:get(<<"path">>, RCont, undefined)), ?assertEqual(Path, maps:get(<<"path">>, RCont, undefined)),
?assertEqual(Action, maps:get(<<"action">>, RCont, undefined)), ?assertEqual(Action, maps:get(<<"action">>, RCont, undefined)),

View File

@ -1,4 +1,6 @@
{erl_opts, [debug_info]}. {erl_opts, [debug_info]}.
{deps, [ {emqx, {path, "../../apps/emqx"}}, {deps, [
{emqx, {path, "../../apps/emqx"}},
{emqx_utils, {path, "../emqx_utils"}},
{emqx_gateway, {path, "../../apps/emqx_gateway"}} {emqx_gateway, {path, "../../apps/emqx_gateway"}}
]}. ]}.

View File

@ -1,5 +1,8 @@
%% -*- mode: erlang -*- %% -*- mode: erlang -*-
{deps, [{emqx, {path, "../emqx"}}]}. {deps, [
{emqx, {path, "../emqx"}},
{emqx_utils, {path, "../emqx_utils"}}
]}.
{project_plugins, [erlfmt]}. {project_plugins, [erlfmt]}.

View File

@ -3,7 +3,7 @@
{id, "emqx_machine"}, {id, "emqx_machine"},
{description, "The EMQX Machine"}, {description, "The EMQX Machine"},
% strict semver, bump manually! % strict semver, bump manually!
{vsn, "0.2.1"}, {vsn, "0.2.2"},
{modules, []}, {modules, []},
{registered, []}, {registered, []},
{applications, [kernel, stdlib, emqx_ctl]}, {applications, [kernel, stdlib, emqx_ctl]},

View File

@ -88,7 +88,7 @@ start_sysmon() ->
end. end.
node_status() -> node_status() ->
emqx_json:encode(#{ emqx_utils_json:encode(#{
backend => mria_rlog:backend(), backend => mria_rlog:backend(),
role => mria_rlog:role() role => mria_rlog:role()
}). }).

View File

@ -1,6 +1,9 @@
%% -*- mode: erlang -*- %% -*- mode: erlang -*-
{deps, [{emqx, {path, "../emqx"}}]}. {deps, [
{emqx, {path, "../emqx"}},
{emqx_utils, {path, "../emqx_utils"}}
]}.
{edoc_opts, [{preprocess, true}]}. {edoc_opts, [{preprocess, true}]}.
{erl_opts, [ {erl_opts, [

View File

@ -165,7 +165,7 @@ banned(post, #{body := Body}) ->
{ok, Banned} -> {ok, Banned} ->
{200, format(Banned)}; {200, format(Banned)};
{error, {already_exist, Old}} -> {error, {already_exist, Old}} ->
OldBannedFormat = emqx_json:encode(format(Old)), OldBannedFormat = emqx_utils_json:encode(format(Old)),
{400, 'ALREADY_EXISTS', OldBannedFormat} {400, 'ALREADY_EXISTS', OldBannedFormat}
end end
end. end.

View File

@ -56,7 +56,7 @@ get_alarms(AssertCount, Activated) ->
Qs = "activated=" ++ Activated, Qs = "activated=" ++ Activated,
Headers = emqx_mgmt_api_test_util:auth_header_(), Headers = emqx_mgmt_api_test_util:auth_header_(),
{ok, Response} = emqx_mgmt_api_test_util:request_api(get, Path, Qs, Headers), {ok, Response} = emqx_mgmt_api_test_util:request_api(get, Path, Qs, Headers),
Data = emqx_json:decode(Response, [return_maps]), Data = emqx_utils_json:decode(Response, [return_maps]),
Meta = maps:get(<<"meta">>, Data), Meta = maps:get(<<"meta">>, Data),
Page = maps:get(<<"page">>, Meta), Page = maps:get(<<"page">>, Meta),
Limit = maps:get(<<"limit">>, Meta), Limit = maps:get(<<"limit">>, Meta),

View File

@ -228,7 +228,7 @@ list_app() ->
AuthHeader = emqx_dashboard_SUITE:auth_header_(), AuthHeader = emqx_dashboard_SUITE:auth_header_(),
Path = emqx_mgmt_api_test_util:api_path(["api_key"]), Path = emqx_mgmt_api_test_util:api_path(["api_key"]),
case emqx_mgmt_api_test_util:request_api(get, Path, AuthHeader) of case emqx_mgmt_api_test_util:request_api(get, Path, AuthHeader) of
{ok, Apps} -> {ok, emqx_json:decode(Apps, [return_maps])}; {ok, Apps} -> {ok, emqx_utils_json:decode(Apps, [return_maps])};
Error -> Error Error -> Error
end. end.
@ -236,7 +236,7 @@ read_app(Name) ->
AuthHeader = emqx_dashboard_SUITE:auth_header_(), AuthHeader = emqx_dashboard_SUITE:auth_header_(),
Path = emqx_mgmt_api_test_util:api_path(["api_key", Name]), Path = emqx_mgmt_api_test_util:api_path(["api_key", Name]),
case emqx_mgmt_api_test_util:request_api(get, Path, AuthHeader) of case emqx_mgmt_api_test_util:request_api(get, Path, AuthHeader) of
{ok, Res} -> {ok, emqx_json:decode(Res, [return_maps])}; {ok, Res} -> {ok, emqx_utils_json:decode(Res, [return_maps])};
Error -> Error Error -> Error
end. end.
@ -251,7 +251,7 @@ create_app(Name) ->
enable => true enable => true
}, },
case emqx_mgmt_api_test_util:request_api(post, Path, "", AuthHeader, App) of case emqx_mgmt_api_test_util:request_api(post, Path, "", AuthHeader, App) of
{ok, Res} -> {ok, emqx_json:decode(Res, [return_maps])}; {ok, Res} -> {ok, emqx_utils_json:decode(Res, [return_maps])};
Error -> Error Error -> Error
end. end.
@ -260,7 +260,7 @@ create_unexpired_app(Name, Params) ->
Path = emqx_mgmt_api_test_util:api_path(["api_key"]), Path = emqx_mgmt_api_test_util:api_path(["api_key"]),
App = maps:merge(#{name => Name, desc => <<"Note"/utf8>>, enable => true}, Params), App = maps:merge(#{name => Name, desc => <<"Note"/utf8>>, enable => true}, Params),
case emqx_mgmt_api_test_util:request_api(post, Path, "", AuthHeader, App) of case emqx_mgmt_api_test_util:request_api(post, Path, "", AuthHeader, App) of
{ok, Res} -> {ok, emqx_json:decode(Res, [return_maps])}; {ok, Res} -> {ok, emqx_utils_json:decode(Res, [return_maps])};
Error -> Error Error -> Error
end. end.
@ -273,7 +273,7 @@ update_app(Name, Change) ->
AuthHeader = emqx_dashboard_SUITE:auth_header_(), AuthHeader = emqx_dashboard_SUITE:auth_header_(),
UpdatePath = emqx_mgmt_api_test_util:api_path(["api_key", Name]), UpdatePath = emqx_mgmt_api_test_util:api_path(["api_key", Name]),
case emqx_mgmt_api_test_util:request_api(put, UpdatePath, "", AuthHeader, Change) of case emqx_mgmt_api_test_util:request_api(put, UpdatePath, "", AuthHeader, Change) of
{ok, Update} -> {ok, emqx_json:decode(Update, [return_maps])}; {ok, Update} -> {ok, emqx_utils_json:decode(Update, [return_maps])};
Error -> Error Error -> Error
end. end.

View File

@ -160,7 +160,7 @@ t_delete(_Config) ->
list_banned() -> list_banned() ->
Path = emqx_mgmt_api_test_util:api_path(["banned"]), Path = emqx_mgmt_api_test_util:api_path(["banned"]),
case emqx_mgmt_api_test_util:request_api(get, Path) of case emqx_mgmt_api_test_util:request_api(get, Path) of
{ok, Apps} -> {ok, emqx_json:decode(Apps, [return_maps])}; {ok, Apps} -> {ok, emqx_utils_json:decode(Apps, [return_maps])};
Error -> Error Error -> Error
end. end.
@ -168,7 +168,7 @@ create_banned(Banned) ->
AuthHeader = emqx_mgmt_api_test_util:auth_header_(), AuthHeader = emqx_mgmt_api_test_util:auth_header_(),
Path = emqx_mgmt_api_test_util:api_path(["banned"]), Path = emqx_mgmt_api_test_util:api_path(["banned"]),
case emqx_mgmt_api_test_util:request_api(post, Path, "", AuthHeader, Banned) of case emqx_mgmt_api_test_util:request_api(post, Path, "", AuthHeader, Banned) of
{ok, Res} -> {ok, emqx_json:decode(Res, [return_maps])}; {ok, Res} -> {ok, emqx_utils_json:decode(Res, [return_maps])};
Error -> Error Error -> Error
end. end.

View File

@ -58,7 +58,7 @@ t_clients(_) ->
%% get /clients %% get /clients
ClientsPath = emqx_mgmt_api_test_util:api_path(["clients"]), ClientsPath = emqx_mgmt_api_test_util:api_path(["clients"]),
{ok, Clients} = emqx_mgmt_api_test_util:request_api(get, ClientsPath), {ok, Clients} = emqx_mgmt_api_test_util:request_api(get, ClientsPath),
ClientsResponse = emqx_json:decode(Clients, [return_maps]), ClientsResponse = emqx_utils_json:decode(Clients, [return_maps]),
ClientsMeta = maps:get(<<"meta">>, ClientsResponse), ClientsMeta = maps:get(<<"meta">>, ClientsResponse),
ClientsPage = maps:get(<<"page">>, ClientsMeta), ClientsPage = maps:get(<<"page">>, ClientsMeta),
ClientsLimit = maps:get(<<"limit">>, ClientsMeta), ClientsLimit = maps:get(<<"limit">>, ClientsMeta),
@ -70,7 +70,7 @@ t_clients(_) ->
%% get /clients/:clientid %% get /clients/:clientid
Client1Path = emqx_mgmt_api_test_util:api_path(["clients", binary_to_list(ClientId1)]), Client1Path = emqx_mgmt_api_test_util:api_path(["clients", binary_to_list(ClientId1)]),
{ok, Client1} = emqx_mgmt_api_test_util:request_api(get, Client1Path), {ok, Client1} = emqx_mgmt_api_test_util:request_api(get, Client1Path),
Client1Response = emqx_json:decode(Client1, [return_maps]), Client1Response = emqx_utils_json:decode(Client1, [return_maps]),
?assertEqual(Username1, maps:get(<<"username">>, Client1Response)), ?assertEqual(Username1, maps:get(<<"username">>, Client1Response)),
?assertEqual(ClientId1, maps:get(<<"clientid">>, Client1Response)), ?assertEqual(ClientId1, maps:get(<<"clientid">>, Client1Response)),
?assertEqual(120, maps:get(<<"expiry_interval">>, Client1Response)), ?assertEqual(120, maps:get(<<"expiry_interval">>, Client1Response)),
@ -130,7 +130,7 @@ t_clients(_) ->
"", "",
AuthHeader AuthHeader
), ),
[SubscriptionsData] = emqx_json:decode(SubscriptionsRes, [return_maps]), [SubscriptionsData] = emqx_utils_json:decode(SubscriptionsRes, [return_maps]),
?assertMatch( ?assertMatch(
#{ #{
<<"clientid">> := ClientId1, <<"clientid">> := ClientId1,
@ -210,7 +210,7 @@ t_query_clients_with_time(_) ->
GteParamRfc3339 ++ GteParamStamp GteParamRfc3339 ++ GteParamStamp
], ],
DecodedResults = [ DecodedResults = [
emqx_json:decode(Response, [return_maps]) emqx_utils_json:decode(Response, [return_maps])
|| {ok, Response} <- RequestResults || {ok, Response} <- RequestResults
], ],
{LteResponseDecodeds, GteResponseDecodeds} = lists:split(4, DecodedResults), {LteResponseDecodeds, GteResponseDecodeds} = lists:split(4, DecodedResults),
@ -247,7 +247,7 @@ t_keepalive(_Config) ->
{ok, C1} = emqtt:start_link(#{username => Username, clientid => ClientId}), {ok, C1} = emqtt:start_link(#{username => Username, clientid => ClientId}),
{ok, _} = emqtt:connect(C1), {ok, _} = emqtt:connect(C1),
{ok, NewClient} = emqx_mgmt_api_test_util:request_api(put, Path, <<"">>, AuthHeader, Body), {ok, NewClient} = emqx_mgmt_api_test_util:request_api(put, Path, <<"">>, AuthHeader, Body),
#{<<"keepalive">> := 11} = emqx_json:decode(NewClient, [return_maps]), #{<<"keepalive">> := 11} = emqx_utils_json:decode(NewClient, [return_maps]),
[Pid] = emqx_cm:lookup_channels(list_to_binary(ClientId)), [Pid] = emqx_cm:lookup_channels(list_to_binary(ClientId)),
#{conninfo := #{keepalive := Keepalive}} = emqx_connection:info(Pid), #{conninfo := #{keepalive := Keepalive}} = emqx_connection:info(Pid),
?assertEqual(11, Keepalive), ?assertEqual(11, Keepalive),

View File

@ -235,7 +235,7 @@ t_configs_node(_) ->
?assertEqual(error, ExpType), ?assertEqual(error, ExpType),
?assertMatch({{_, 404, _}, _, _}, ExpRes), ?assertMatch({{_, 404, _}, _, _}, ExpRes),
{_, _, Body} = ExpRes, {_, _, Body} = ExpRes,
?assertMatch(#{<<"code">> := <<"NOT_FOUND">>}, emqx_json:decode(Body, [return_maps])), ?assertMatch(#{<<"code">> := <<"NOT_FOUND">>}, emqx_utils_json:decode(Body, [return_maps])),
?assertMatch({error, {_, 500, _}}, get_configs("bad_node")). ?assertMatch({error, {_, 500, _}}, get_configs("bad_node")).
@ -245,7 +245,7 @@ get_config(Name) ->
Path = emqx_mgmt_api_test_util:api_path(["configs", Name]), Path = emqx_mgmt_api_test_util:api_path(["configs", Name]),
case emqx_mgmt_api_test_util:request_api(get, Path) of case emqx_mgmt_api_test_util:request_api(get, Path) of
{ok, Res} -> {ok, Res} ->
{ok, emqx_json:decode(Res, [return_maps])}; {ok, emqx_utils_json:decode(Res, [return_maps])};
Error -> Error ->
Error Error
end. end.
@ -264,8 +264,8 @@ get_configs(Node, Opts) ->
end, end,
URI = emqx_mgmt_api_test_util:api_path(Path), URI = emqx_mgmt_api_test_util:api_path(Path),
case emqx_mgmt_api_test_util:request_api(get, URI, [], [], [], Opts) of case emqx_mgmt_api_test_util:request_api(get, URI, [], [], [], Opts) of
{ok, {_, _, Res}} -> {ok, emqx_json:decode(Res, [return_maps])}; {ok, {_, _, Res}} -> {ok, emqx_utils_json:decode(Res, [return_maps])};
{ok, Res} -> {ok, emqx_json:decode(Res, [return_maps])}; {ok, Res} -> {ok, emqx_utils_json:decode(Res, [return_maps])};
Error -> Error Error -> Error
end. end.
@ -273,7 +273,7 @@ update_config(Name, Change) ->
AuthHeader = emqx_mgmt_api_test_util:auth_header_(), AuthHeader = emqx_mgmt_api_test_util:auth_header_(),
UpdatePath = emqx_mgmt_api_test_util:api_path(["configs", Name]), UpdatePath = emqx_mgmt_api_test_util:api_path(["configs", Name]),
case emqx_mgmt_api_test_util:request_api(put, UpdatePath, "", AuthHeader, Change) of case emqx_mgmt_api_test_util:request_api(put, UpdatePath, "", AuthHeader, Change) of
{ok, Update} -> {ok, emqx_json:decode(Update, [return_maps])}; {ok, Update} -> {ok, emqx_utils_json:decode(Update, [return_maps])};
Error -> Error Error -> Error
end. end.

View File

@ -385,7 +385,7 @@ action_listener(ID, Action, Running) ->
request(Method, Url, QueryParams, Body) -> request(Method, Url, QueryParams, Body) ->
AuthHeader = emqx_mgmt_api_test_util:auth_header_(), AuthHeader = emqx_mgmt_api_test_util:auth_header_(),
case emqx_mgmt_api_test_util:request_api(Method, Url, QueryParams, AuthHeader, Body) of case emqx_mgmt_api_test_util:request_api(Method, Url, QueryParams, AuthHeader, Body) of
{ok, Res} -> emqx_json:decode(Res, [return_maps]); {ok, Res} -> emqx_utils_json:decode(Res, [return_maps]);
Error -> Error Error -> Error
end. end.

View File

@ -32,13 +32,13 @@ end_per_suite(_) ->
t_metrics_api(_) -> t_metrics_api(_) ->
{ok, MetricsResponse} = request_helper("metrics?aggregate=true"), {ok, MetricsResponse} = request_helper("metrics?aggregate=true"),
MetricsFromAPI = emqx_json:decode(MetricsResponse, [return_maps]), MetricsFromAPI = emqx_utils_json:decode(MetricsResponse, [return_maps]),
AggregateMetrics = emqx_mgmt:get_metrics(), AggregateMetrics = emqx_mgmt:get_metrics(),
match_helper(AggregateMetrics, MetricsFromAPI). match_helper(AggregateMetrics, MetricsFromAPI).
t_single_node_metrics_api(_) -> t_single_node_metrics_api(_) ->
{ok, MetricsResponse} = request_helper("metrics"), {ok, MetricsResponse} = request_helper("metrics"),
[MetricsFromAPI] = emqx_json:decode(MetricsResponse, [return_maps]), [MetricsFromAPI] = emqx_utils_json:decode(MetricsResponse, [return_maps]),
LocalNodeMetrics = maps:from_list( LocalNodeMetrics = maps:from_list(
emqx_mgmt:get_metrics(node()) ++ [{node, to_bin(node())}] emqx_mgmt:get_metrics(node()) ++ [{node, to_bin(node())}]
), ),

View File

@ -53,7 +53,7 @@ end_per_testcase(_, Config) ->
t_nodes_api(_) -> t_nodes_api(_) ->
NodesPath = emqx_mgmt_api_test_util:api_path(["nodes"]), NodesPath = emqx_mgmt_api_test_util:api_path(["nodes"]),
{ok, Nodes} = emqx_mgmt_api_test_util:request_api(get, NodesPath), {ok, Nodes} = emqx_mgmt_api_test_util:request_api(get, NodesPath),
NodesResponse = emqx_json:decode(Nodes, [return_maps]), NodesResponse = emqx_utils_json:decode(Nodes, [return_maps]),
LocalNodeInfo = hd(NodesResponse), LocalNodeInfo = hd(NodesResponse),
Node = binary_to_atom(maps:get(<<"node">>, LocalNodeInfo), utf8), Node = binary_to_atom(maps:get(<<"node">>, LocalNodeInfo), utf8),
?assertEqual(Node, node()), ?assertEqual(Node, node()),
@ -63,7 +63,7 @@ t_nodes_api(_) ->
NodePath = emqx_mgmt_api_test_util:api_path(["nodes", atom_to_list(node())]), NodePath = emqx_mgmt_api_test_util:api_path(["nodes", atom_to_list(node())]),
{ok, NodeInfo} = emqx_mgmt_api_test_util:request_api(get, NodePath), {ok, NodeInfo} = emqx_mgmt_api_test_util:request_api(get, NodePath),
NodeNameResponse = NodeNameResponse =
binary_to_atom(maps:get(<<"node">>, emqx_json:decode(NodeInfo, [return_maps])), utf8), binary_to_atom(maps:get(<<"node">>, emqx_utils_json:decode(NodeInfo, [return_maps])), utf8),
?assertEqual(node(), NodeNameResponse), ?assertEqual(node(), NodeNameResponse),
BadNodePath = emqx_mgmt_api_test_util:api_path(["nodes", "badnode"]), BadNodePath = emqx_mgmt_api_test_util:api_path(["nodes", "badnode"]),
@ -75,7 +75,7 @@ t_nodes_api(_) ->
t_log_path(_) -> t_log_path(_) ->
NodePath = emqx_mgmt_api_test_util:api_path(["nodes", atom_to_list(node())]), NodePath = emqx_mgmt_api_test_util:api_path(["nodes", atom_to_list(node())]),
{ok, NodeInfo} = emqx_mgmt_api_test_util:request_api(get, NodePath), {ok, NodeInfo} = emqx_mgmt_api_test_util:request_api(get, NodePath),
#{<<"log_path">> := Path} = emqx_json:decode(NodeInfo, [return_maps]), #{<<"log_path">> := Path} = emqx_utils_json:decode(NodeInfo, [return_maps]),
?assertEqual( ?assertEqual(
<<"log">>, <<"log">>,
filename:basename(Path) filename:basename(Path)
@ -85,7 +85,7 @@ t_node_stats_api(_) ->
StatsPath = emqx_mgmt_api_test_util:api_path(["nodes", atom_to_binary(node(), utf8), "stats"]), StatsPath = emqx_mgmt_api_test_util:api_path(["nodes", atom_to_binary(node(), utf8), "stats"]),
SystemStats = emqx_mgmt:get_stats(), SystemStats = emqx_mgmt:get_stats(),
{ok, StatsResponse} = emqx_mgmt_api_test_util:request_api(get, StatsPath), {ok, StatsResponse} = emqx_mgmt_api_test_util:request_api(get, StatsPath),
Stats = emqx_json:decode(StatsResponse, [return_maps]), Stats = emqx_utils_json:decode(StatsResponse, [return_maps]),
Fun = Fun =
fun(Key) -> fun(Key) ->
?assertEqual(maps:get(Key, SystemStats), maps:get(atom_to_binary(Key, utf8), Stats)) ?assertEqual(maps:get(Key, SystemStats), maps:get(atom_to_binary(Key, utf8), Stats))
@ -103,7 +103,7 @@ t_node_metrics_api(_) ->
emqx_mgmt_api_test_util:api_path(["nodes", atom_to_binary(node(), utf8), "metrics"]), emqx_mgmt_api_test_util:api_path(["nodes", atom_to_binary(node(), utf8), "metrics"]),
SystemMetrics = emqx_mgmt:get_metrics(), SystemMetrics = emqx_mgmt:get_metrics(),
{ok, MetricsResponse} = emqx_mgmt_api_test_util:request_api(get, MetricsPath), {ok, MetricsResponse} = emqx_mgmt_api_test_util:request_api(get, MetricsPath),
Metrics = emqx_json:decode(MetricsResponse, [return_maps]), Metrics = emqx_utils_json:decode(MetricsResponse, [return_maps]),
Fun = Fun =
fun(Key) -> fun(Key) ->
?assertEqual(maps:get(Key, SystemMetrics), maps:get(atom_to_binary(Key, utf8), Metrics)) ?assertEqual(maps:get(Key, SystemMetrics), maps:get(atom_to_binary(Key, utf8), Metrics))

View File

@ -136,14 +136,14 @@ t_bad_plugin(Config) ->
list_plugins() -> list_plugins() ->
Path = emqx_mgmt_api_test_util:api_path(["plugins"]), Path = emqx_mgmt_api_test_util:api_path(["plugins"]),
case emqx_mgmt_api_test_util:request_api(get, Path) of case emqx_mgmt_api_test_util:request_api(get, Path) of
{ok, Apps} -> {ok, emqx_json:decode(Apps, [return_maps])}; {ok, Apps} -> {ok, emqx_utils_json:decode(Apps, [return_maps])};
Error -> Error Error -> Error
end. end.
describe_plugins(Name) -> describe_plugins(Name) ->
Path = emqx_mgmt_api_test_util:api_path(["plugins", Name]), Path = emqx_mgmt_api_test_util:api_path(["plugins", Name]),
case emqx_mgmt_api_test_util:request_api(get, Path) of case emqx_mgmt_api_test_util:request_api(get, Path) of
{ok, Res} -> {ok, emqx_json:decode(Res, [return_maps])}; {ok, Res} -> {ok, emqx_utils_json:decode(Res, [return_maps])};
Error -> Error Error -> Error
end. end.
@ -172,7 +172,7 @@ update_boot_order(Name, MoveBody) ->
Auth = emqx_mgmt_api_test_util:auth_header_(), Auth = emqx_mgmt_api_test_util:auth_header_(),
Path = emqx_mgmt_api_test_util:api_path(["plugins", Name, "move"]), Path = emqx_mgmt_api_test_util:api_path(["plugins", Name, "move"]),
case emqx_mgmt_api_test_util:request_api(post, Path, "", Auth, MoveBody) of case emqx_mgmt_api_test_util:request_api(post, Path, "", Auth, MoveBody) of
{ok, Res} -> {ok, emqx_json:decode(Res, [return_maps])}; {ok, Res} -> {ok, emqx_utils_json:decode(Res, [return_maps])};
Error -> Error Error -> Error
end. end.
@ -206,7 +206,7 @@ create_renamed_package(PackagePath, NewNameVsn) ->
NewPackagePath. NewPackagePath.
update_release_json(["release.json"], FileContent, NewName) -> update_release_json(["release.json"], FileContent, NewName) ->
ContentMap = emqx_json:decode(FileContent, [return_maps]), ContentMap = emqx_utils_json:decode(FileContent, [return_maps]),
emqx_json:encode(ContentMap#{<<"name">> => NewName}); emqx_utils_json:encode(ContentMap#{<<"name">> => NewName});
update_release_json(_FileName, FileContent, _NewName) -> update_release_json(_FileName, FileContent, _NewName) ->
FileContent. FileContent.

View File

@ -352,4 +352,4 @@ receive_assert(Topic, Qos, Payload) ->
end. end.
decode_json(In) -> decode_json(In) ->
emqx_json:decode(In, [return_maps]). emqx_utils_json:decode(In, [return_maps]).

View File

@ -33,7 +33,7 @@ end_per_suite(_) ->
t_stats_api(_) -> t_stats_api(_) ->
S = emqx_mgmt_api_test_util:api_path(["stats?aggregate=false"]), S = emqx_mgmt_api_test_util:api_path(["stats?aggregate=false"]),
{ok, S1} = emqx_mgmt_api_test_util:request_api(get, S), {ok, S1} = emqx_mgmt_api_test_util:request_api(get, S),
[Stats1] = emqx_json:decode(S1, [return_maps]), [Stats1] = emqx_utils_json:decode(S1, [return_maps]),
SystemStats1 = emqx_mgmt:get_stats(), SystemStats1 = emqx_mgmt:get_stats(),
Fun1 = Fun1 =
fun(Key) -> fun(Key) ->
@ -43,7 +43,7 @@ t_stats_api(_) ->
StatsPath = emqx_mgmt_api_test_util:api_path(["stats?aggregate=true"]), StatsPath = emqx_mgmt_api_test_util:api_path(["stats?aggregate=true"]),
SystemStats = emqx_mgmt:get_stats(), SystemStats = emqx_mgmt:get_stats(),
{ok, StatsResponse} = emqx_mgmt_api_test_util:request_api(get, StatsPath), {ok, StatsResponse} = emqx_mgmt_api_test_util:request_api(get, StatsPath),
Stats = emqx_json:decode(StatsResponse, [return_maps]), Stats = emqx_utils_json:decode(StatsResponse, [return_maps]),
?assertEqual(erlang:length(maps:keys(SystemStats)), erlang:length(maps:keys(Stats))), ?assertEqual(erlang:length(maps:keys(SystemStats)), erlang:length(maps:keys(Stats))),
Fun = Fun =
fun(Key) -> fun(Key) ->

View File

@ -55,7 +55,7 @@ t_subscription_api(Config) ->
{ok, _, _} = emqtt:subscribe(Client, ?TOPIC2), {ok, _, _} = emqtt:subscribe(Client, ?TOPIC2),
Path = emqx_mgmt_api_test_util:api_path(["subscriptions"]), Path = emqx_mgmt_api_test_util:api_path(["subscriptions"]),
{ok, Response} = emqx_mgmt_api_test_util:request_api(get, Path), {ok, Response} = emqx_mgmt_api_test_util:request_api(get, Path),
Data = emqx_json:decode(Response, [return_maps]), Data = emqx_utils_json:decode(Response, [return_maps]),
Meta = maps:get(<<"meta">>, Data), Meta = maps:get(<<"meta">>, Data),
?assertEqual(1, maps:get(<<"page">>, Meta)), ?assertEqual(1, maps:get(<<"page">>, Meta)),
?assertEqual(emqx_mgmt:default_row_limit(), maps:get(<<"limit">>, Meta)), ?assertEqual(emqx_mgmt:default_row_limit(), maps:get(<<"limit">>, Meta)),
@ -158,7 +158,7 @@ t_list_with_internal_subscription(_Config) ->
request_json(Method, Query, Headers) when is_list(Query) -> request_json(Method, Query, Headers) when is_list(Query) ->
Qs = uri_string:compose_query(Query), Qs = uri_string:compose_query(Query),
{ok, MatchRes} = emqx_mgmt_api_test_util:request_api(Method, path(), Qs, Headers), {ok, MatchRes} = emqx_mgmt_api_test_util:request_api(Method, path(), Qs, Headers),
emqx_json:decode(MatchRes, [return_maps]). emqx_utils_json:decode(MatchRes, [return_maps]).
path() -> path() ->
emqx_mgmt_api_test_util:api_path(["subscriptions"]). emqx_mgmt_api_test_util:api_path(["subscriptions"]).

View File

@ -108,7 +108,8 @@ request_api(Method, Url, QueryParams, AuthOrHeaders, Body, Opts) when
end, end,
do_request_api( do_request_api(
Method, Method,
{NewUrl, build_http_header(AuthOrHeaders), "application/json", emqx_json:encode(Body)}, {NewUrl, build_http_header(AuthOrHeaders), "application/json",
emqx_utils_json:encode(Body)},
Opts Opts
). ).

View File

@ -49,7 +49,7 @@ t_nodes_api(Config) ->
%% list all %% list all
Path = emqx_mgmt_api_test_util:api_path(["topics"]), Path = emqx_mgmt_api_test_util:api_path(["topics"]),
{ok, Response} = emqx_mgmt_api_test_util:request_api(get, Path), {ok, Response} = emqx_mgmt_api_test_util:request_api(get, Path),
RoutesData = emqx_json:decode(Response, [return_maps]), RoutesData = emqx_utils_json:decode(Response, [return_maps]),
Meta = maps:get(<<"meta">>, RoutesData), Meta = maps:get(<<"meta">>, RoutesData),
?assertEqual(1, maps:get(<<"page">>, Meta)), ?assertEqual(1, maps:get(<<"page">>, Meta)),
?assertEqual(emqx_mgmt:default_row_limit(), maps:get(<<"limit">>, Meta)), ?assertEqual(emqx_mgmt:default_row_limit(), maps:get(<<"limit">>, Meta)),
@ -68,7 +68,7 @@ t_nodes_api(Config) ->
]), ]),
Headers = emqx_mgmt_api_test_util:auth_header_(), Headers = emqx_mgmt_api_test_util:auth_header_(),
{ok, MatchResponse} = emqx_mgmt_api_test_util:request_api(get, Path, QS, Headers), {ok, MatchResponse} = emqx_mgmt_api_test_util:request_api(get, Path, QS, Headers),
MatchData = emqx_json:decode(MatchResponse, [return_maps]), MatchData = emqx_utils_json:decode(MatchResponse, [return_maps]),
?assertMatch( ?assertMatch(
#{<<"count">> := 1, <<"page">> := 1, <<"limit">> := 100}, #{<<"count">> := 1, <<"page">> := 1, <<"limit">> := 100},
maps:get(<<"meta">>, MatchData) maps:get(<<"meta">>, MatchData)
@ -90,6 +90,6 @@ t_nodes_api(Config) ->
[ [
#{<<"topic">> := Topic, <<"node">> := Node1}, #{<<"topic">> := Topic, <<"node">> := Node1},
#{<<"topic">> := Topic, <<"node">> := Node2} #{<<"topic">> := Topic, <<"node">> := Node2}
] = emqx_json:decode(RouteResponse, [return_maps]), ] = emqx_utils_json:decode(RouteResponse, [return_maps]),
?assertEqual(lists:usort([Node, atom_to_binary(Slave)]), lists:usort([Node1, Node2])). ?assertEqual(lists:usort([Node, atom_to_binary(Slave)]), lists:usort([Node1, Node2])).

View File

@ -384,7 +384,7 @@ api_path(Path) ->
emqx_mgmt_api_test_util:api_path([Path]). emqx_mgmt_api_test_util:api_path([Path]).
json(Data) -> json(Data) ->
{ok, Jsx} = emqx_json:safe_decode(Data, [return_maps]), {ok, Jsx} = emqx_utils_json:safe_decode(Data, [return_maps]),
Jsx. Jsx.
load() -> load() ->

View File

@ -2,6 +2,7 @@
{deps, [ {deps, [
{emqx, {path, "../emqx"}}, {emqx, {path, "../emqx"}},
{emqx_utils, {path, "../emqx_utils"}},
{emqx_conf, {path, "../emqx_conf"}} {emqx_conf, {path, "../emqx_conf"}}
]}. ]}.
{project_plugins, [erlfmt]}. {project_plugins, [erlfmt]}.

View File

@ -356,7 +356,7 @@ get_telemetry(State0 = #state{node_uuid = NodeUUID, cluster_uuid = ClusterUUID})
report_telemetry(State0 = #state{url = URL}) -> report_telemetry(State0 = #state{url = URL}) ->
{State, Data} = get_telemetry(State0), {State, Data} = get_telemetry(State0),
case emqx_json:safe_encode(Data) of case emqx_utils_json:safe_encode(Data) of
{ok, Bin} -> {ok, Bin} ->
httpc_request(post, URL, [], Bin), httpc_request(post, URL, [], Bin),
?tp(debug, telemetry_data_reported, #{}); ?tp(debug, telemetry_data_reported, #{});

View File

@ -243,7 +243,7 @@ status(put, #{body := Body}) ->
data(get, _Request) -> data(get, _Request) ->
case emqx_modules_conf:is_telemetry_enabled() of case emqx_modules_conf:is_telemetry_enabled() of
true -> true ->
{200, emqx_json:encode(get_telemetry_data())}; {200, emqx_utils_json:encode(get_telemetry_data())};
false -> false ->
{404, #{ {404, #{
code => ?NOT_FOUND, code => ?NOT_FOUND,

View File

@ -229,7 +229,7 @@ t_large_payload(_) ->
%%-------------------------------------------------------------------- %%--------------------------------------------------------------------
decode_json(Data) -> decode_json(Data) ->
BinJson = emqx_json:decode(Data, [return_maps]), BinJson = emqx_utils_json:decode(Data, [return_maps]),
emqx_map_lib:unsafe_atom_key_map(BinJson). emqx_map_lib:unsafe_atom_key_map(BinJson).
clear_all_record() -> clear_all_record() ->

View File

@ -75,7 +75,7 @@ t_mqtt_topic_rewrite(_) ->
?assertEqual( ?assertEqual(
Rules, Rules,
emqx_json:decode(Result, [return_maps]) emqx_utils_json:decode(Result, [return_maps])
). ).
t_mqtt_topic_rewrite_limit(_) -> t_mqtt_topic_rewrite_limit(_) ->

View File

@ -512,7 +512,7 @@ t_send_after_enable(_) ->
), ),
receive receive
{request, post, _URL, _Headers, Body} -> {request, post, _URL, _Headers, Body} ->
{ok, Decoded} = emqx_json:safe_decode(Body, [return_maps]), {ok, Decoded} = emqx_utils_json:safe_decode(Body, [return_maps]),
?assertMatch( ?assertMatch(
#{ #{
<<"uuid">> := _, <<"uuid">> := _,

View File

@ -1,5 +1,8 @@
%% -*- mode: erlang -*- %% -*- mode: erlang -*-
{deps, [{emqx, {path, "../emqx"}}]}. {deps, [
{emqx, {path, "../emqx"}},
{emqx_utils, {path, "../emqx_utils"}}
]}.
{project_plugins, [erlfmt]}. {project_plugins, [erlfmt]}.

View File

@ -240,7 +240,7 @@ sql_data(Bin) when is_binary(Bin) -> Bin;
sql_data(Num) when is_number(Num) -> Num; sql_data(Num) when is_number(Num) -> Num;
sql_data(Bool) when is_boolean(Bool) -> Bool; sql_data(Bool) when is_boolean(Bool) -> Bool;
sql_data(Atom) when is_atom(Atom) -> atom_to_binary(Atom, utf8); sql_data(Atom) when is_atom(Atom) -> atom_to_binary(Atom, utf8);
sql_data(Map) when is_map(Map) -> emqx_json:encode(Map). sql_data(Map) when is_map(Map) -> emqx_utils_json:encode(Map).
-spec bin(term()) -> binary(). -spec bin(term()) -> binary().
bin(Val) -> emqx_plugin_libs_rule:bin(Val). bin(Val) -> emqx_plugin_libs_rule:bin(Val).

View File

@ -236,11 +236,11 @@ tcp_connectivity(Host, Port, Timeout) ->
str(Bin) when is_binary(Bin) -> binary_to_list(Bin); str(Bin) when is_binary(Bin) -> binary_to_list(Bin);
str(Num) when is_number(Num) -> number_to_list(Num); str(Num) when is_number(Num) -> number_to_list(Num);
str(Atom) when is_atom(Atom) -> atom_to_list(Atom); str(Atom) when is_atom(Atom) -> atom_to_list(Atom);
str(Map) when is_map(Map) -> binary_to_list(emqx_json:encode(Map)); str(Map) when is_map(Map) -> binary_to_list(emqx_utils_json:encode(Map));
str(List) when is_list(List) -> str(List) when is_list(List) ->
case io_lib:printable_list(List) of case io_lib:printable_list(List) of
true -> List; true -> List;
false -> binary_to_list(emqx_json:encode(List)) false -> binary_to_list(emqx_utils_json:encode(List))
end; end;
str(Data) -> str(Data) ->
error({invalid_str, Data}). error({invalid_str, Data}).
@ -258,11 +258,11 @@ utf8_str(Str) ->
bin(Bin) when is_binary(Bin) -> Bin; bin(Bin) when is_binary(Bin) -> Bin;
bin(Num) when is_number(Num) -> number_to_binary(Num); bin(Num) when is_number(Num) -> number_to_binary(Num);
bin(Atom) when is_atom(Atom) -> atom_to_binary(Atom, utf8); bin(Atom) when is_atom(Atom) -> atom_to_binary(Atom, utf8);
bin(Map) when is_map(Map) -> emqx_json:encode(Map); bin(Map) when is_map(Map) -> emqx_utils_json:encode(Map);
bin(List) when is_list(List) -> bin(List) when is_list(List) ->
case io_lib:printable_list(List) of case io_lib:printable_list(List) of
true -> list_to_binary(List); true -> list_to_binary(List);
false -> emqx_json:encode(List) false -> emqx_utils_json:encode(List)
end; end;
bin(Data) -> bin(Data) ->
error({invalid_bin, Data}). error({invalid_bin, Data}).
@ -312,7 +312,7 @@ float2str(Float, Precision) when is_float(Float) and is_integer(Precision) ->
float_to_binary(Float, [{decimals, Precision}, compact]). float_to_binary(Float, [{decimals, Precision}, compact]).
map(Bin) when is_binary(Bin) -> map(Bin) when is_binary(Bin) ->
case emqx_json:decode(Bin, [return_maps]) of case emqx_utils_json:decode(Bin, [return_maps]) of
Map = #{} -> Map; Map = #{} -> Map;
_ -> error({invalid_map, Bin}) _ -> error({invalid_map, Bin})
end; end;

View File

@ -2,6 +2,7 @@
{deps, [ {deps, [
{emqx, {path, "../emqx"}}, {emqx, {path, "../emqx"}},
{emqx_utils, {path, "../emqx_utils"}},
{prometheus, {git, "https://github.com/deadtrickster/prometheus.erl", {tag, "v4.8.1"}}} {prometheus, {git, "https://github.com/deadtrickster/prometheus.erl", {tag, "v4.8.1"}}}
]}. ]}.

View File

@ -66,7 +66,7 @@ t_prometheus_api(_) ->
Auth = emqx_mgmt_api_test_util:auth_header_(), Auth = emqx_mgmt_api_test_util:auth_header_(),
{ok, Response} = emqx_mgmt_api_test_util:request_api(get, Path, "", Auth), {ok, Response} = emqx_mgmt_api_test_util:request_api(get, Path, "", Auth),
Conf = emqx_json:decode(Response, [return_maps]), Conf = emqx_utils_json:decode(Response, [return_maps]),
?assertMatch( ?assertMatch(
#{ #{
<<"push_gateway_server">> := _, <<"push_gateway_server">> := _,
@ -84,7 +84,7 @@ t_prometheus_api(_) ->
NewConf = Conf#{<<"interval">> => <<"2s">>, <<"vm_statistics_collector">> => <<"disabled">>}, NewConf = Conf#{<<"interval">> => <<"2s">>, <<"vm_statistics_collector">> => <<"disabled">>},
{ok, Response2} = emqx_mgmt_api_test_util:request_api(put, Path, "", Auth, NewConf), {ok, Response2} = emqx_mgmt_api_test_util:request_api(put, Path, "", Auth, NewConf),
Conf2 = emqx_json:decode(Response2, [return_maps]), Conf2 = emqx_utils_json:decode(Response2, [return_maps]),
?assertMatch(NewConf, Conf2), ?assertMatch(NewConf, Conf2),
?assertEqual({ok, []}, application:get_env(prometheus, vm_statistics_collector_metrics)), ?assertEqual({ok, []}, application:get_env(prometheus, vm_statistics_collector_metrics)),
?assertEqual({ok, all}, application:get_env(prometheus, vm_memory_collector_metrics)), ?assertEqual({ok, all}, application:get_env(prometheus, vm_memory_collector_metrics)),
@ -106,7 +106,7 @@ t_stats_api(_) ->
Headers = [{"accept", "application/json"}, Auth], Headers = [{"accept", "application/json"}, Auth],
{ok, Response} = emqx_mgmt_api_test_util:request_api(get, Path, "", Headers), {ok, Response} = emqx_mgmt_api_test_util:request_api(get, Path, "", Headers),
Data = emqx_json:decode(Response, [return_maps]), Data = emqx_utils_json:decode(Response, [return_maps]),
?assertMatch(#{<<"client">> := _, <<"delivery">> := _}, Data), ?assertMatch(#{<<"client">> := _, <<"delivery">> := _}, Data),
{ok, _} = emqx_mgmt_api_test_util:request_api(get, Path, "", Auth), {ok, _} = emqx_mgmt_api_test_util:request_api(get, Path, "", Auth),

View File

@ -1,6 +1,9 @@
%% -*- mode: erlang -*- %% -*- mode: erlang -*-
{deps, [{emqx, {path, "../emqx"}}]}. {deps, [
{emqx, {path, "../emqx"}},
{emqx_utils, {path, "../emqx_utils"}}
]}.
{edoc_opts, [{preprocess, true}]}. {edoc_opts, [{preprocess, true}]}.
{erl_opts, [ {erl_opts, [

View File

@ -72,7 +72,7 @@ t_config(_Config) ->
), ),
UpdateConf = fun(Enable) -> UpdateConf = fun(Enable) ->
RawConf = emqx_json:decode(ConfJson, [return_maps]), RawConf = emqx_utils_json:decode(ConfJson, [return_maps]),
UpdateJson = RawConf#{<<"enable">> := Enable}, UpdateJson = RawConf#{<<"enable">> := Enable},
{ok, UpdateResJson} = request_api( {ok, UpdateResJson} = request_api(
put, put,
@ -81,7 +81,7 @@ t_config(_Config) ->
auth_header_(), auth_header_(),
UpdateJson UpdateJson
), ),
UpdateRawConf = emqx_json:decode(UpdateResJson, [return_maps]), UpdateRawConf = emqx_utils_json:decode(UpdateResJson, [return_maps]),
?assertEqual(Enable, maps:get(<<"enable">>, UpdateRawConf)) ?assertEqual(Enable, maps:get(<<"enable">>, UpdateRawConf))
end, end,
@ -224,7 +224,7 @@ t_lookup_and_delete(_) ->
t_change_storage_type(_Config) -> t_change_storage_type(_Config) ->
Path = api_path(["mqtt", "retainer"]), Path = api_path(["mqtt", "retainer"]),
{ok, ConfJson} = request_api(get, Path), {ok, ConfJson} = request_api(get, Path),
RawConf = emqx_json:decode(ConfJson, [return_maps]), RawConf = emqx_utils_json:decode(ConfJson, [return_maps]),
%% pre-conditions %% pre-conditions
?assertMatch( ?assertMatch(
#{ #{
@ -271,7 +271,7 @@ t_change_storage_type(_Config) ->
auth_header_(), auth_header_(),
ChangedConf ChangedConf
), ),
UpdatedRawConf = emqx_json:decode(UpdateResJson, [return_maps]), UpdatedRawConf = emqx_utils_json:decode(UpdateResJson, [return_maps]),
?assertMatch( ?assertMatch(
#{ #{
<<"backend">> := #{ <<"backend">> := #{
@ -311,7 +311,7 @@ t_change_storage_type(_Config) ->
%% HTTP Request %% HTTP Request
%%-------------------------------------------------------------------- %%--------------------------------------------------------------------
decode_json(Data) -> decode_json(Data) ->
BinJson = emqx_json:decode(Data, [return_maps]), BinJson = emqx_utils_json:decode(Data, [return_maps]),
emqx_map_lib:unsafe_atom_key_map(BinJson). emqx_map_lib:unsafe_atom_key_map(BinJson).
%%-------------------------------------------------------------------- %%--------------------------------------------------------------------

View File

@ -1,7 +1,8 @@
%% -*- mode: erlang -*- %% -*- mode: erlang -*-
{deps, [ {deps, [
{emqx, {path, "../emqx"}} {emqx, {path, "../emqx"}},
{emqx_utils, {path, "../emqx_utils"}}
]}. ]}.
{erl_opts, [ {erl_opts, [

View File

@ -213,7 +213,7 @@ replace_simple_var(Val, _Data, _Default) ->
Val. Val.
format_msg([], Selected) -> format_msg([], Selected) ->
emqx_json:encode(Selected); emqx_utils_json:encode(Selected);
format_msg(Tokens, Selected) -> format_msg(Tokens, Selected) ->
emqx_plugin_libs_rule:proc_tmpl(Tokens, Selected). emqx_plugin_libs_rule:proc_tmpl(Tokens, Selected).

View File

@ -468,7 +468,7 @@ err_msg(Msg) ->
encode_nested_error(RuleError, Reason) when is_tuple(Reason) -> encode_nested_error(RuleError, Reason) when is_tuple(Reason) ->
encode_nested_error(RuleError, element(1, Reason)); encode_nested_error(RuleError, element(1, Reason));
encode_nested_error(RuleError, Reason) -> encode_nested_error(RuleError, Reason) ->
case emqx_json:safe_encode([{RuleError, Reason}]) of case emqx_utils_json:safe_encode([{RuleError, Reason}]) of
{ok, Json} -> {ok, Json} ->
Json; Json;
_ -> _ ->

View File

@ -987,10 +987,10 @@ base64_decode(Data) when is_binary(Data) ->
base64:decode(Data). base64:decode(Data).
json_encode(Data) -> json_encode(Data) ->
emqx_json:encode(Data). emqx_utils_json:encode(Data).
json_decode(Data) -> json_decode(Data) ->
emqx_json:decode(Data, [return_maps]). emqx_utils_json:decode(Data, [return_maps]).
term_encode(Term) -> term_encode(Term) ->
erlang:term_to_binary(Term). erlang:term_to_binary(Term).

View File

@ -86,7 +86,7 @@ general_map_put(Key, Val, Map, OrgData) ->
). ).
general_find(KeyOrIndex, Data, OrgData, Handler) when is_binary(Data) -> general_find(KeyOrIndex, Data, OrgData, Handler) when is_binary(Data) ->
try emqx_json:decode(Data, [return_maps]) of try emqx_utils_json:decode(Data, [return_maps]) of
Json -> general_find(KeyOrIndex, Json, OrgData, Handler) Json -> general_find(KeyOrIndex, Json, OrgData, Handler)
catch catch
_:_ -> Handler(not_found) _:_ -> Handler(not_found)

View File

@ -495,7 +495,7 @@ cache_payload(DecodedP) ->
safe_decode_and_cache(MaybeJson) -> safe_decode_and_cache(MaybeJson) ->
try try
cache_payload(emqx_json:decode(MaybeJson, [return_maps])) cache_payload(emqx_utils_json:decode(MaybeJson, [return_maps]))
catch catch
_:_ -> error({decode_json_failed, MaybeJson}) _:_ -> error({decode_json_failed, MaybeJson})
end. end.

View File

@ -614,7 +614,9 @@ t_event_client_disconnected_normal(_Config) ->
receive receive
{publish, #{topic := T, payload := Payload}} -> {publish, #{topic := T, payload := Payload}} ->
?assertEqual(RepubT, T), ?assertEqual(RepubT, T),
?assertMatch(#{<<"reason">> := <<"normal">>}, emqx_json:decode(Payload, [return_maps])) ?assertMatch(
#{<<"reason">> := <<"normal">>}, emqx_utils_json:decode(Payload, [return_maps])
)
after 1000 -> after 1000 ->
ct:fail(wait_for_repub_disconnected_normal) ct:fail(wait_for_repub_disconnected_normal)
end, end,
@ -651,7 +653,9 @@ t_event_client_disconnected_kicked(_Config) ->
receive receive
{publish, #{topic := T, payload := Payload}} -> {publish, #{topic := T, payload := Payload}} ->
?assertEqual(RepubT, T), ?assertEqual(RepubT, T),
?assertMatch(#{<<"reason">> := <<"kicked">>}, emqx_json:decode(Payload, [return_maps])) ?assertMatch(
#{<<"reason">> := <<"kicked">>}, emqx_utils_json:decode(Payload, [return_maps])
)
after 1000 -> after 1000 ->
ct:fail(wait_for_repub_disconnected_kicked) ct:fail(wait_for_repub_disconnected_kicked)
end, end,
@ -692,7 +696,7 @@ t_event_client_disconnected_discarded(_Config) ->
{publish, #{topic := T, payload := Payload}} -> {publish, #{topic := T, payload := Payload}} ->
?assertEqual(RepubT, T), ?assertEqual(RepubT, T),
?assertMatch( ?assertMatch(
#{<<"reason">> := <<"discarded">>}, emqx_json:decode(Payload, [return_maps]) #{<<"reason">> := <<"discarded">>}, emqx_utils_json:decode(Payload, [return_maps])
) )
after 1000 -> after 1000 ->
ct:fail(wait_for_repub_disconnected_discarded) ct:fail(wait_for_repub_disconnected_discarded)
@ -737,7 +741,7 @@ t_event_client_disconnected_takenover(_Config) ->
{publish, #{topic := T, payload := Payload}} -> {publish, #{topic := T, payload := Payload}} ->
?assertEqual(RepubT, T), ?assertEqual(RepubT, T),
?assertMatch( ?assertMatch(
#{<<"reason">> := <<"takenover">>}, emqx_json:decode(Payload, [return_maps]) #{<<"reason">> := <<"takenover">>}, emqx_utils_json:decode(Payload, [return_maps])
) )
after 1000 -> after 1000 ->
ct:fail(wait_for_repub_disconnected_discarded) ct:fail(wait_for_repub_disconnected_discarded)
@ -2800,7 +2804,7 @@ verify_event(EventName) ->
[ [
begin begin
%% verify fields can be formatted to JSON string %% verify fields can be formatted to JSON string
_ = emqx_json:encode(Fields), _ = emqx_utils_json:encode(Fields),
%% verify metadata fields %% verify metadata fields
verify_metadata_fields(EventName, Fields), verify_metadata_fields(EventName, Fields),
%% verify available fields for each event name %% verify available fields for each event name

View File

@ -46,13 +46,13 @@ end_per_suite(_Config) ->
ok. ok.
init_per_testcase(t_crud_rule_api, Config) -> init_per_testcase(t_crud_rule_api, Config) ->
meck:new(emqx_json, [passthrough]), meck:new(emqx_utils_json, [passthrough]),
init_per_testcase(common, Config); init_per_testcase(common, Config);
init_per_testcase(_, Config) -> init_per_testcase(_, Config) ->
Config. Config.
end_per_testcase(t_crud_rule_api, Config) -> end_per_testcase(t_crud_rule_api, Config) ->
meck:unload(emqx_json), meck:unload(emqx_utils_json),
end_per_testcase(common, Config); end_per_testcase(common, Config);
end_per_testcase(_, _Config) -> end_per_testcase(_, _Config) ->
{200, #{data := Rules}} = {200, #{data := Rules}} =
@ -136,7 +136,7 @@ t_crud_rule_api(_Config) ->
), ),
?assertMatch( ?assertMatch(
#{<<"select_and_transform_error">> := <<"decode_json_failed">>}, #{<<"select_and_transform_error">> := <<"decode_json_failed">>},
emqx_json:decode(SelectAndTransformJsonError, [return_maps]) emqx_utils_json:decode(SelectAndTransformJsonError, [return_maps])
), ),
{400, #{ {400, #{
code := 'BAD_REQUEST', code := 'BAD_REQUEST',
@ -150,7 +150,7 @@ t_crud_rule_api(_Config) ->
), ),
?assertMatch( ?assertMatch(
#{<<"select_and_transform_error">> := <<"badarg">>}, #{<<"select_and_transform_error">> := <<"badarg">>},
emqx_json:decode(SelectAndTransformBadArgError, [return_maps]) emqx_utils_json:decode(SelectAndTransformBadArgError, [return_maps])
), ),
{400, #{ {400, #{
code := 'BAD_REQUEST', code := 'BAD_REQUEST',
@ -162,7 +162,7 @@ t_crud_rule_api(_Config) ->
) )
), ),
?assertMatch({match, _}, re:run(BadSqlMessage, "syntax error")), ?assertMatch({match, _}, re:run(BadSqlMessage, "syntax error")),
meck:expect(emqx_json, safe_encode, 1, {error, foo}), meck:expect(emqx_utils_json, safe_encode, 1, {error, foo}),
?assertMatch( ?assertMatch(
{400, #{ {400, #{
code := 'BAD_REQUEST', code := 'BAD_REQUEST',

View File

@ -1,5 +1,8 @@
%% -*- mode: erlang -*- %% -*- mode: erlang -*-
{deps, [{emqx, {path, "../emqx"}}]}. {deps, [
{emqx, {path, "../emqx"}},
{emqx_utils, {path, "../emqx_utils"}}
]}.
{project_plugins, [erlfmt]}. {project_plugins, [erlfmt]}.

View File

@ -108,7 +108,7 @@ t_get_history(_) ->
"page=1&limit=10", "page=1&limit=10",
auth_header_() auth_header_()
), ),
#{<<"data">> := [First | _]} = emqx_json:decode(Data, [return_maps]), #{<<"data">> := [First | _]} = emqx_utils_json:decode(Data, [return_maps]),
?assertMatch( ?assertMatch(
#{ #{
@ -165,7 +165,7 @@ t_settting(_) ->
?assertEqual(Conf2#{stats_type := <<"internal">>}, GetReturn). ?assertEqual(Conf2#{stats_type := <<"internal">>}, GetReturn).
decode_json(Data) -> decode_json(Data) ->
BinJosn = emqx_json:decode(Data, [return_maps]), BinJosn = emqx_utils_json:decode(Data, [return_maps]),
emqx_map_lib:unsafe_atom_key_map(BinJosn). emqx_map_lib:unsafe_atom_key_map(BinJosn).
request_api(Method, Url, Auth) -> request_api(Method, Url, Auth) ->
@ -187,7 +187,7 @@ request_api(Method, Url, QueryParams, Auth, Body) ->
"" -> Url; "" -> Url;
_ -> Url ++ "?" ++ QueryParams _ -> Url ++ "?" ++ QueryParams
end, end,
do_request_api(Method, {NewUrl, [Auth], "application/json", emqx_json:encode(Body)}). do_request_api(Method, {NewUrl, [Auth], "application/json", emqx_utils_json:encode(Body)}).
do_request_api(Method, Request) -> do_request_api(Method, Request) ->
ct:pal("Method: ~p, Request: ~p", [Method, Request]), ct:pal("Method: ~p, Request: ~p", [Method, Request]),

Some files were not shown because too many files have changed in this diff Show More