userlist) {
32 | this.userlist = userlist;
33 | }
34 | }
35 |
--------------------------------------------------------------------------------
/samples/dubbo-sample-service/src/main/java/org/apache/dubbo/erlang/sample/service/facade/UserOperator.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Licensed to the Apache Software Foundation (ASF) under one or more
3 | * contributor license agreements. See the NOTICE file distributed with
4 | * this work for additional information regarding copyright ownership.
5 | * The ASF licenses this file to You under the Apache License, Version 2.0
6 | * (the "License"); you may not use this file except in compliance with
7 | * the License. You may obtain a copy of the License at
8 | *
9 | * http://www.apache.org/licenses/LICENSE-2.0
10 | *
11 | * Unless required by applicable law or agreed to in writing, software
12 | * distributed under the License is distributed on an "AS IS" BASIS,
13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 | * See the License for the specific language governing permissions and
15 | * limitations under the License.
16 | */
17 |
18 | package org.apache.dubbo.erlang.sample.service.facade;
19 |
20 | import org.apache.dubbo.erlang.sample.service.bean.UserInfo;
21 | import org.apache.dubbo.erlang.sample.service.bean.UserInfoRequest;
22 | import org.apache.dubbo.erlang.sample.service.bean.UserRes;
23 |
24 | public interface UserOperator {
25 | public String genUserId();
26 |
27 | public UserInfo getUserInfo(String userid);
28 |
29 | public UserInfo queryUserInfo(UserInfoRequest request);
30 |
31 | public UserRes queryUserList(String info);
32 |
33 | }
34 |
--------------------------------------------------------------------------------
/samples/dubbo-sample-service/src/main/java/org/apache/dubbo/erlang/sample/service/impl/UserOperatorImpl.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Licensed to the Apache Software Foundation (ASF) under one or more
3 | * contributor license agreements. See the NOTICE file distributed with
4 | * this work for additional information regarding copyright ownership.
5 | * The ASF licenses this file to You under the Apache License, Version 2.0
6 | * (the "License"); you may not use this file except in compliance with
7 | * the License. You may obtain a copy of the License at
8 | *
9 | * http://www.apache.org/licenses/LICENSE-2.0
10 | *
11 | * Unless required by applicable law or agreed to in writing, software
12 | * distributed under the License is distributed on an "AS IS" BASIS,
13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 | * See the License for the specific language governing permissions and
15 | * limitations under the License.
16 | */
17 |
18 | package org.apache.dubbo.erlang.sample.service.impl;
19 |
20 | import org.apache.dubbo.erlang.sample.service.bean.UserInfo;
21 | import org.apache.dubbo.erlang.sample.service.bean.UserInfoRequest;
22 | import org.apache.dubbo.erlang.sample.service.bean.UserRes;
23 | import org.apache.dubbo.erlang.sample.service.facade.UserOperator;
24 | import org.apache.dubbo.rpc.RpcContext;
25 |
26 | public class UserOperatorImpl implements UserOperator {
27 |
28 | @Override
29 | public String genUserId() {
30 | return "userid-123";
31 | }
32 |
33 | @Override
34 | public UserInfo getUserInfo(String userid) {
35 | UserInfo info = new UserInfo();
36 | info.setUserAge(10);
37 | info.setUserId("1");
38 | info.setUserName("testname");
39 | return info;
40 | }
41 |
42 | @Override
43 | public UserInfo queryUserInfo(UserInfoRequest request) {
44 |
45 | System.out.println("request:" + request.getRequestId());
46 | UserInfo info = new UserInfo();
47 | info.setUserAge(99);
48 | info.setUserId("id123");
49 | info.setUserName("中文姓名");
50 | RpcContext.getContext().setAttachment("attachment_test_key","attachment_test_value");
51 | return info;
52 | }
53 |
54 | @Override
55 | public UserRes queryUserList(String info) {
56 | return null;
57 | }
58 | }
59 |
--------------------------------------------------------------------------------
/samples/dubbo-sample-service/src/main/resources/applicationConsumer.xml:
--------------------------------------------------------------------------------
1 |
2 |
18 |
19 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
--------------------------------------------------------------------------------
/samples/dubbo-sample-service/src/main/resources/applicationProvider.xml:
--------------------------------------------------------------------------------
1 |
2 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
--------------------------------------------------------------------------------
/samples/dubbo-sample-service/src/main/resources/log4j.properties:
--------------------------------------------------------------------------------
1 | log4j.rootLogger=DEBUG,console
2 | log4j.appender.console=org.apache.log4j.ConsoleAppender
3 | log4j.appender.console.Threshold=DEBUG
4 | #log4j.appender.console.ImmediateFlush=true
5 | #log4j.appender.console.Target=System.err
6 | log4j.appender.console.layout=org.apache.log4j.PatternLayout
7 | log4j.appender.console.layout.ConversionPattern=%-d{yyyy-MM-dd HH\:mm\:ss} [%c]-[%p] %m%n
8 |
--------------------------------------------------------------------------------
/samples/dubbo-sample-service/src/test/java/org/apache/dubbo/erlang/sample/service/AppTest.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Licensed to the Apache Software Foundation (ASF) under one or more
3 | * contributor license agreements. See the NOTICE file distributed with
4 | * this work for additional information regarding copyright ownership.
5 | * The ASF licenses this file to You under the Apache License, Version 2.0
6 | * (the "License"); you may not use this file except in compliance with
7 | * the License. You may obtain a copy of the License at
8 | *
9 | * http://www.apache.org/licenses/LICENSE-2.0
10 | *
11 | * Unless required by applicable law or agreed to in writing, software
12 | * distributed under the License is distributed on an "AS IS" BASIS,
13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 | * See the License for the specific language governing permissions and
15 | * limitations under the License.
16 | */
17 |
18 | package org.apache.dubbo.erlang.sample.service;
19 |
20 | import static org.junit.Assert.assertTrue;
21 |
22 | import org.junit.Test;
23 |
24 | /**
25 | * Unit test for simple App.
26 | */
27 | public class AppTest {
28 | /**
29 | * Rigorous Test :-)
30 | */
31 | @Test
32 | public void shouldAnswerWithTrue() {
33 | assertTrue(true);
34 | }
35 | }
36 |
--------------------------------------------------------------------------------
/samples/dubboerl_demo/README.md:
--------------------------------------------------------------------------------
1 | dubboerl_demo
2 | =====
3 |
4 | An OTP application
5 |
6 | Build
7 | -----
8 |
9 | $ rebar3 compile
10 |
11 |
12 | Start
13 | -----
14 | ./rebar3 shell --apps "dubboerl_demo"
--------------------------------------------------------------------------------
/samples/dubboerl_demo/apps/dubbo_sample_service/include/dubbo_sample_service.hrl:
--------------------------------------------------------------------------------
1 |
2 | -record(userInfoRequest,{
3 | username ::list(),
4 | requestId ::list()}).
5 |
6 | -record(userRes,{
7 | userlist ::[]}).
8 |
9 | -record(userInfo,{
10 | userId ::list(),
11 | userName ::list(),
12 | userAge ::integer()}).
13 |
14 |
--------------------------------------------------------------------------------
/samples/dubboerl_demo/apps/dubbo_sample_service/src/dubbo_sample_service.app.src:
--------------------------------------------------------------------------------
1 | {application, dubbo_sample_service,
2 | [
3 | {description, "An OTP application"},
4 | {vsn, "1.3"},
5 | {registered, []},
6 | {mod, { dubbo_sample_service_app, []}},
7 | {applications,
8 | [kernel,
9 | stdlib,
10 | dubboerl
11 | ]},
12 | {env,[]},
13 | {modules, []},
14 | {maintainers, []},
15 | {licenses, []},
16 | {links, []}
17 | ]}.
18 |
--------------------------------------------------------------------------------
/samples/dubboerl_demo/apps/dubbo_sample_service/src/dubbo_sample_service_app.erl:
--------------------------------------------------------------------------------
1 | %%%-------------------------------------------------------------------
2 | %% @doc dubbo_sample_service public API
3 | %% @end
4 | %%%-------------------------------------------------------------------
5 |
6 | -module(dubbo_sample_service_app).
7 |
8 | -behaviour(application).
9 |
10 | %% Application callbacks
11 | -export([start/2, stop/1]).
12 |
13 | -include("dubbo_sample_service.hrl").
14 |
15 |
16 | %%====================================================================
17 | %% API
18 | %%====================================================================
19 |
20 | start(_StartType, _StartArgs) ->
21 | register_type_list(),
22 | dubbo_sample_service_sup:start_link().
23 |
24 | %%--------------------------------------------------------------------
25 | stop(_State) ->
26 | ok.
27 |
28 | %%====================================================================
29 | %% Internal functions
30 | %%====================================================================
31 |
32 |
33 | register_type_list()->
34 | List = dubbo_sample_service_type_list:get_list(),
35 | lists:map(
36 | fun({NativeType,ForeignType,Fields}) ->
37 | dubbo_type_transfer:pre_process_typedef(NativeType,ForeignType,Fields)
38 | end,List),
39 | ok.
--------------------------------------------------------------------------------
/samples/dubboerl_demo/apps/dubbo_sample_service/src/dubbo_sample_service_sup.erl:
--------------------------------------------------------------------------------
1 | %%%-------------------------------------------------------------------
2 | %% @doc dubbo_sample_service top level supervisor.
3 | %% @end
4 | %%%-------------------------------------------------------------------
5 |
6 | -module(dubbo_sample_service_sup).
7 |
8 | -behaviour(supervisor).
9 |
10 | %% API
11 | -export([start_link/0]).
12 |
13 | %% Supervisor callbacks
14 | -export([init/1]).
15 |
16 | -define(SERVER, ?MODULE).
17 |
18 | %%====================================================================
19 | %% API functions
20 | %%====================================================================
21 |
22 | start_link() ->
23 | supervisor:start_link({local, ?SERVER}, ?MODULE, []).
24 |
25 | %%====================================================================
26 | %% Supervisor callbacks
27 | %%====================================================================
28 |
29 | %% Child :: {Id,StartFunc,Restart,Shutdown,Type,Modules}
30 | init([]) ->
31 | {ok, { {one_for_all, 0, 1}, []} }.
32 |
33 | %%====================================================================
34 | %% Internal functions
35 | %%====================================================================
36 |
--------------------------------------------------------------------------------
/samples/dubboerl_demo/apps/dubbo_sample_service/src/dubbo_sample_service_type_list.erl:
--------------------------------------------------------------------------------
1 | -module(dubbo_sample_service_type_list).
2 |
3 | %% API
4 | -export([register_type_list/0,get_list/0]).
5 |
6 | -include("dubbo_sample_service.hrl").
7 |
8 | get_list()->
9 | [
10 | {userInfoRequest,<<"org.apache.dubbo.erlang.sample.service.bean.UserInfoRequest">>,record_info(fields,userInfoRequest)},
11 | {userRes,<<"org.apache.dubbo.erlang.sample.service.bean.UserRes">>,record_info(fields,userRes)},
12 | {userInfo,<<"org.apache.dubbo.erlang.sample.service.bean.UserInfo">>,record_info(fields,userInfo)} ].
13 |
14 | register_type_list()->
15 | ok.
--------------------------------------------------------------------------------
/samples/dubboerl_demo/apps/dubboerl_demo/src/api_gateway_handle.erl:
--------------------------------------------------------------------------------
1 | %%------------------------------------------------------------------------------
2 | %% Licensed to the Apache Software Foundation (ASF) under one or more
3 | %% contributor license agreements. See the NOTICE file distributed with
4 | %% this work for additional information regarding copyright ownership.
5 | %% The ASF licenses this file to You under the Apache License, Version 2.0
6 | %% (the "License"); you may not use this file except in compliance with
7 | %% the License. You may obtain a copy of the License at
8 | %%
9 | %% http://www.apache.org/licenses/LICENSE-2.0
10 | %%
11 | %% Unless required by applicable law or agreed to in writing, software
12 | %% distributed under the License is distributed on an "AS IS" BASIS,
13 | %% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 | %% See the License for the specific language governing permissions and
15 | %% limitations under the License.
16 | %%------------------------------------------------------------------------------
17 | -module(api_gateway_handle).
18 |
19 | -include_lib("dubbo_sample_service/include/dubbo_sample_service.hrl").
20 |
21 | -export([init/2]).
22 | -export([content_types_provided/2]).
23 | -export([hello_to_html/2]).
24 | -export([hello_to_json/2]).
25 | -export([hello_to_text/2]).
26 | -export([info/3]).
27 |
28 | %%init(Req, Opts) ->
29 | %% {cowboy_rest, Req, Opts}.
30 | init(Req, State) ->
31 | io:format("get loop init ~n"),
32 | request_to_dubbo(Req,State),
33 | {cowboy_loop, Req, State}.
34 |
35 | content_types_provided(Req, State) ->
36 | {[
37 | {<<"text/html">>, hello_to_html},
38 | {<<"application/json">>, hello_to_json},
39 | {<<"text/plain">>, hello_to_text}
40 | ], Req, State}.
41 |
42 | hello_to_html(Req, State) ->
43 | Body = <<"
44 |
45 |
46 | REST Hello World!
47 |
48 |
49 | REST Hello World as HTML!
50 |
51 | ">>,
52 | {Body, Req, State}.
53 |
54 | hello_to_json(Req, State) ->
55 | Body = <<"{\"rest\": \"Hello World!\"}">>,
56 | {Body, Req, State}.
57 |
58 | hello_to_text(Req, State) ->
59 | {<<"REST Hello World as text!">>, Req, State}.
60 |
61 |
62 | info({reply, Body}, Req, State) ->
63 | cowboy_req:reply(200, #{}, Body, Req),
64 | {stop, Req, State};
65 | info({'$gen_cast',{msg_back,Ref,Response,RpcContent}},Req,State)->
66 | io:format("get msg_back ~p~n",[Response]),
67 | Body = <<"
68 |
69 |
70 | REST Hello World!
71 |
72 |
73 | REST Hello World as HTML!
74 |
75 | ">>,
76 | Req2=cowboy_req:reply(200, #{}, Body, Req),
77 | {stop, Req2, State};
78 | info(_Msg, Req, State) ->
79 | io:format("get info ~p~n",[_Msg]),
80 | {ok, Req, State, hibernate}.
81 |
82 | request_to_dubbo(Req, State)->
83 | userOperator:queryUserInfo(#userInfoRequest{username = "name",requestId = "111"},#{sync=> true}),
84 | ok.
85 |
--------------------------------------------------------------------------------
/samples/dubboerl_demo/apps/dubboerl_demo/src/dubboerl_demo.app.src:
--------------------------------------------------------------------------------
1 | {application, dubboerl_demo,
2 | [{description, "An OTP application"},
3 | {vsn, "0.1.0"},
4 | {registered, []},
5 | {mod, { dubboerl_demo_app, []}},
6 | {applications,
7 | [kernel,
8 | stdlib,
9 | recon,
10 | observer_cli,
11 | dubbo_sample_service
12 | ]},
13 | {env,[]},
14 | {modules, []},
15 |
16 | {maintainers, []},
17 | {licenses, ["Apache 2.0"]},
18 | {links, []}
19 | ]}.
20 |
--------------------------------------------------------------------------------
/samples/dubboerl_demo/apps/dubboerl_demo/src/dubboerl_demo_app.erl:
--------------------------------------------------------------------------------
1 | %%%-------------------------------------------------------------------
2 | %% @doc dubboerl_demo public API
3 | %% @end
4 | %%%-------------------------------------------------------------------
5 |
6 | -module(dubboerl_demo_app).
7 |
8 | -behaviour(application).
9 |
10 | %% Application callbacks
11 | -export([start/2, stop/1,test_fun/0]).
12 |
13 | %%====================================================================
14 | %% API
15 | %%====================================================================
16 |
17 | start(_StartType, _StartArgs) ->
18 | start_app(),
19 | dubboerl:init(),
20 | start_web(),
21 | dubboerl_demo_sup:start_link().
22 |
23 | %%--------------------------------------------------------------------
24 | stop(_State) ->
25 | ok.
26 |
27 | %%====================================================================
28 | %% Internal functions
29 | %%====================================================================
30 | start_app()->
31 | application:ensure_all_started(dubboerl),
32 | application:ensure_all_started(dubbo_sample_service),
33 | application:ensure_all_started(cowboy),
34 | ok.
35 |
36 | start_web()->
37 | Dispatch = cowboy_router:compile([
38 | {'_', [
39 | {"/", api_gateway_handle, []}
40 | ]}
41 | ]),
42 | {ok, _} = cowboy:start_clear(http, [{port,9090}], #{
43 | env => #{dispatch => Dispatch}
44 | }),
45 | ok.
46 |
47 | test_fun()->
48 | ok1.
--------------------------------------------------------------------------------
/samples/dubboerl_demo/apps/dubboerl_demo/src/dubboerl_demo_sup.erl:
--------------------------------------------------------------------------------
1 | %%%-------------------------------------------------------------------
2 | %% @doc dubboerl_demo top level supervisor.
3 | %% @end
4 | %%%-------------------------------------------------------------------
5 |
6 | -module(dubboerl_demo_sup).
7 |
8 | -behaviour(supervisor).
9 |
10 | %% API
11 | -export([start_link/0]).
12 |
13 | %% Supervisor callbacks
14 | -export([init/1]).
15 |
16 | -define(SERVER, ?MODULE).
17 |
18 | %%====================================================================
19 | %% API functions
20 | %%====================================================================
21 |
22 | start_link() ->
23 | supervisor:start_link({local, ?SERVER}, ?MODULE, []).
24 |
25 | %%====================================================================
26 | %% Supervisor callbacks
27 | %%====================================================================
28 |
29 | %% Child :: {Id,StartFunc,Restart,Shutdown,Type,Modules}
30 | init([]) ->
31 | {ok, { {one_for_all, 0, 1}, []} }.
32 |
33 | %%====================================================================
34 | %% Internal functions
35 | %%====================================================================
36 |
--------------------------------------------------------------------------------
/samples/dubboerl_demo/config/sys.config:
--------------------------------------------------------------------------------
1 | [
2 | {dubboerl_demo, []},
3 | {dubboerl,[
4 | {registry,true},
5 | {zookeeper_list,[{"127.0.0.1",2181}]},
6 | {application,<<"dubboerl_demo">>},
7 | {protocol,hessian},
8 | {port,20881},
9 | {consumer,[
10 | {<<"org.apache.dubbo.erlang.sample.service.facade.UserOperator">>,[]}
11 | ]},
12 | {provider,[
13 | ]}
14 |
15 | ]},
16 | {lager, [
17 | {log_root, "./logs"},
18 | {handlers, [
19 | {lager_console_backend, debug},
20 | {lager_file_backend, [{file, "error.log"}, {level, error}]},
21 | {lager_file_backend, [{file, "console.log"}, {level, debug}]}
22 | ]}
23 | ]}
24 | ].
25 |
--------------------------------------------------------------------------------
/samples/dubboerl_demo/config/vm.args:
--------------------------------------------------------------------------------
1 | -sname dubboerl_demo
2 |
3 | -setcookie dubboerl_demo_cookie
4 |
5 | +K true
6 | +A30
7 |
--------------------------------------------------------------------------------
/samples/dubboerl_demo/nohup.out:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/apache/dubbo-erlang/3e2c2fa0f84a077de07d5363dbbc8daaa0e5c500/samples/dubboerl_demo/nohup.out
--------------------------------------------------------------------------------
/samples/dubboerl_demo/rebar.config:
--------------------------------------------------------------------------------
1 | {erl_opts, [debug_info]}.
2 | {deps, [
3 | {recon, ".*", {git, "https://github.com/ferd/recon.git", {tag, "2.3.2"}}},
4 | {observer_cli, ".*", {git, "https://github.com/zhongwencool/observer_cli.git", {tag, "1.2.1"}}},
5 | {cowboy, ".*", {git, "https://github.com/ninenines/cowboy.git", {tag, "2.3.0"}}},
6 | {dubboerl, ".*", {git, "https://github.com/apache/incubator-dubbo-erlang.git", {branch, "master"}}}
7 | ]}.
8 |
9 | {plugins, [rebar3_auto]}.
10 |
11 | {relx, [{release, {dubboerl_demo, "0.1.0"},
12 | [dubboerl_demo,
13 | sasl]},
14 |
15 | {sys_config, "./config/sys.config"},
16 | {vm_args, "./config/vm.args"},
17 |
18 | {dev_mode, true},
19 | {include_erts, false},
20 |
21 | {extended_start_script, true}]
22 | }.
23 |
24 | {profiles, [{prod, [{relx, [{dev_mode, false},
25 | {include_erts, true}]}]
26 | }]
27 | }.
28 |
--------------------------------------------------------------------------------
/samples/dubboerl_demo/rebar.lock:
--------------------------------------------------------------------------------
1 | {"1.1.0",
2 | [{<<"cowboy">>,
3 | {git,"https://github.com/ninenines/cowboy.git",
4 | {ref,"a7b06f2e138c0c03c2511ed9fe6803fc9ebf3401"}},
5 | 0},
6 | {<<"cowlib">>,
7 | {git,"https://github.com/ninenines/cowlib",
8 | {ref,"b6381527831c5ebb74759e119a517b7d22d4b23a"}},
9 | 1},
10 | {<<"dubboerl">>,
11 | {git,"https://github.com/apache/incubator-dubbo-erlang.git",
12 | {ref,"aea1facd9cf9cc7f9427329473662d8b5963e489"}},
13 | 0},
14 | {<<"erlzk">>,
15 | {git,"https://github.com/huaban/erlzk.git",
16 | {ref,"aa7190ee2343ac1341cea3edc9b9eea36c591708"}},
17 | 1},
18 | {<<"jiffy">>,{pkg,<<"jiffy">>,<<"0.15.1">>},1},
19 | {<<"observer_cli">>,
20 | {git,"https://github.com/zhongwencool/observer_cli.git",
21 | {ref,"4d5f96762bb525b4f857109c10a7d4d53af1a029"}},
22 | 0},
23 | {<<"poolboy">>,
24 | {git,"https://github.com/devinus/poolboy.git",
25 | {ref,"3bb48a893ff5598f7c73731ac17545206d259fac"}},
26 | 1},
27 | {<<"ranch">>,
28 | {git,"https://github.com/ninenines/ranch",
29 | {ref,"55c2a9d623454f372a15e99721a37093d8773b48"}},
30 | 1},
31 | {<<"recon">>,
32 | {git,"https://github.com/ferd/recon.git",
33 | {ref,"fcc1a7db6d367234171ab24a3d1762f94e57ff22"}},
34 | 0}]}.
35 | [
36 | {pkg_hash,[
37 | {<<"jiffy">>, <<"BE83B09388DA1A6C7E798207C9D6A1C4D71BB95FCC387D37D35861788F49AB97">>}]}
38 | ].
39 |
--------------------------------------------------------------------------------
/src/dubbo_adapter.erl:
--------------------------------------------------------------------------------
1 | %%------------------------------------------------------------------------------
2 | %% Licensed to the Apache Software Foundation (ASF) under one or more
3 | %% contributor license agreements. See the NOTICE file distributed with
4 | %% this work for additional information regarding copyright ownership.
5 | %% The ASF licenses this file to You under the Apache License, Version 2.0
6 | %% (the "License"); you may not use this file except in compliance with
7 | %% the License. You may obtain a copy of the License at
8 | %%
9 | %% http://www.apache.org/licenses/LICENSE-2.0
10 | %%
11 | %% Unless required by applicable law or agreed to in writing, software
12 | %% distributed under the License is distributed on an "AS IS" BASIS,
13 | %% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 | %% See the License for the specific language governing permissions and
15 | %% limitations under the License.
16 | %%------------------------------------------------------------------------------
17 | -module(dubbo_adapter).
18 |
19 | -include("dubbo.hrl").
20 | %% API
21 | -export([reference/1]).
22 |
23 | -spec(reference(Data :: #dubbo_rpc_invocation{}) -> dubbo_request()).
24 | reference(Data) ->
25 | #dubbo_request{
26 | is_event = false,
27 | is_twoway = true,
28 | mid = dubbo_id_generator:gen_id(),
29 | data = Data,
30 | mversion = <<"0.0.0">>,
31 | serialize_type = serialize_value(application:get_env(dubboerl, serialization, hessian))
32 | }.
33 |
34 | serialize_value(json) ->
35 | ?SERIALIZATION_FASTJSON;
36 | serialize_value(_) ->
37 | ?SERIALIZATION_HESSIAN.
38 |
--------------------------------------------------------------------------------
/src/dubbo_cluster.erl:
--------------------------------------------------------------------------------
1 | %%------------------------------------------------------------------------------
2 | %% Licensed to the Apache Software Foundation (ASF) under one or more
3 | %% contributor license agreements. See the NOTICE file distributed with
4 | %% this work for additional information regarding copyright ownership.
5 | %% The ASF licenses this file to You under the Apache License, Version 2.0
6 | %% (the "License"); you may not use this file except in compliance with
7 | %% the License. You may obtain a copy of the License at
8 | %%
9 | %% http://www.apache.org/licenses/LICENSE-2.0
10 | %%
11 | %% Unless required by applicable law or agreed to in writing, software
12 | %% distributed under the License is distributed on an "AS IS" BASIS,
13 | %% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 | %% See the License for the specific language governing permissions and
15 | %% limitations under the License.
16 | %%------------------------------------------------------------------------------
17 | -module(dubbo_cluster).
18 |
19 |
20 |
21 | select(Interface) ->
22 | ok.
23 |
24 | get_loadbalance() ->
25 | ok.
--------------------------------------------------------------------------------
/src/dubbo_cluster_failfast.erl:
--------------------------------------------------------------------------------
1 | %%------------------------------------------------------------------------------
2 | %% Licensed to the Apache Software Foundation (ASF) under one or more
3 | %% contributor license agreements. See the NOTICE file distributed with
4 | %% this work for additional information regarding copyright ownership.
5 | %% The ASF licenses this file to You under the Apache License, Version 2.0
6 | %% (the "License"); you may not use this file except in compliance with
7 | %% the License. You may obtain a copy of the License at
8 | %%
9 | %% http://www.apache.org/licenses/LICENSE-2.0
10 | %%
11 | %% Unless required by applicable law or agreed to in writing, software
12 | %% distributed under the License is distributed on an "AS IS" BASIS,
13 | %% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 | %% See the License for the specific language governing permissions and
15 | %% limitations under the License.
16 | %%------------------------------------------------------------------------------
17 | -module(dubbo_cluster_failfast).
18 | -behaviour(dubbo_filter).
19 |
20 | -include("dubbo.hrl").
21 | %% API
22 | -export([invoke/2, on_response/2]).
23 |
24 |
25 | invoke(#dubbo_rpc_invocation{className = Interface, loadbalance = LoadBalance} = Invocation, Acc) ->
26 | case dubbo_provider_consumer_reg_table:select_connection(Invocation#dubbo_rpc_invocation.className) of
27 | {ok, List} ->
28 | Connection = loadbalance_select(LoadBalance, List),
29 | #connection_info{pid = Pid, host_flag = HostFlag} = Connection,
30 | {ok, Invocation#dubbo_rpc_invocation{transport_pid = Pid}, Acc};
31 | %% case dubbo_traffic_control:check_goon(HostFlag, 199) of
32 | %% ok ->
33 | %%
34 |
35 | %%
36 | %%%% {ok, RequestData} = dubbo_codec:encode_request(Request2),
37 | %%%% Ref = get_ref(RequestState),
38 | %%%% gen_server:cast(Pid, {send_request, Ref, Request2, RequestData, CallBackPid, RequestState}),
39 | %%%% case is_sync(RequestState) of
40 | %%%% true ->
41 | %%%% sync_receive(Ref, get_timeout(RequestState));
42 | %%%% false -> {ok, Ref}
43 | %%%% end;
44 | %% full ->
45 | %% {error, request_full}
46 | %% end;
47 | {error, none} ->
48 | logger:error("[INVOKE] ~p error Reason no_provider", [Interface]),
49 | {stop, no_provider}
50 | end.
51 |
52 | loadbalance_select(LoadBalance, ConnectionList) ->
53 | Connection = LoadBalance:select(ConnectionList),
54 | Connection.
55 |
56 | on_response(Invocation, Result) ->
57 | {ok, Invocation, Result}.
58 |
--------------------------------------------------------------------------------
/src/dubbo_common_fun.erl:
--------------------------------------------------------------------------------
1 | %%------------------------------------------------------------------------------
2 | %% Licensed to the Apache Software Foundation (ASF) under one or more
3 | %% contributor license agreements. See the NOTICE file distributed with
4 | %% this work for additional information regarding copyright ownership.
5 | %% The ASF licenses this file to You under the Apache License, Version 2.0
6 | %% (the "License"); you may not use this file except in compliance with
7 | %% the License. You may obtain a copy of the License at
8 | %%
9 | %% http://www.apache.org/licenses/LICENSE-2.0
10 | %%
11 | %% Unless required by applicable law or agreed to in writing, software
12 | %% distributed under the License is distributed on an "AS IS" BASIS,
13 | %% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 | %% See the License for the specific language governing permissions and
15 | %% limitations under the License.
16 | %%------------------------------------------------------------------------------
17 | -module(dubbo_common_fun).
18 |
19 | -include("dubboerl.hrl").
20 | -include("dubbo.hrl").
21 | %% API
22 | -export([local_ip_v4/0, local_ip_v4_str/0, parse_url/1, url_to_binary/1, parse_url_parameter/1, binary_list_join/2]).
23 |
24 |
25 | local_ip_v4() ->
26 | {ok, Addrs} = inet:getifaddrs(),
27 | hd([
28 | Addr || {_, Opts} <- Addrs, {addr, Addr} <- Opts,
29 | size(Addr) == 4, Addr =/= {127, 0, 0, 1}
30 | ]).
31 |
32 | local_ip_v4_str() ->
33 | {V1, V2, V3, V4} = local_ip_v4(),
34 | list_to_binary(io_lib:format("~p.~p.~p.~p", [V1, V2, V3, V4])).
35 |
36 |
37 | -spec(parse_url(Url :: binary()|list()) -> {ok, #dubbo_url{}}|{error, any()}).
38 | parse_url(Url) when is_binary(Url) ->
39 | parse_url(binary_to_list(Url));
40 | parse_url(Url) ->
41 | case http_uri:parse(Url, []) of
42 | {ok, {Scheme, UserInfo, Host, Port, Path, Query}} ->
43 | QueryStr = case lists:prefix("?", Query) of
44 | true ->
45 | [_ | Query2] = Query,
46 | Query2;
47 | false ->
48 | Query
49 | end,
50 | Parameters = parse_url_parameter(QueryStr),
51 | Result = #dubbo_url{
52 | scheme = atom_to_binary(Scheme, utf8),
53 | user_info = UserInfo,
54 | host = list_to_binary(Host),
55 | port = Port,
56 | path = Path,
57 | parameters = Parameters
58 | },
59 | {ok, Result};
60 | {error, R1} ->
61 | {error, R1}
62 | end.
63 |
64 |
65 | parse_url_parameter(ParameterStr) when is_binary(ParameterStr) ->
66 | parse_url_parameter(binary_to_list(ParameterStr));
67 | parse_url_parameter(ParameterStr) ->
68 | QueryListTmp = string:tokens(ParameterStr, "&"),
69 | parse_url_parameter(QueryListTmp, #{}).
70 |
71 | parse_url_parameter([], Parameters) ->
72 | Parameters;
73 | parse_url_parameter([Item | Rest], Parameters) ->
74 | case string:tokens(Item, "=") of
75 | [Key,Value] ->
76 | parse_url_parameter(Rest, maps:put(list_to_binary(Key), list_to_binary(Value), Parameters));
77 | [Key] ->
78 | parse_url_parameter(Rest, maps:put(list_to_binary(Key), <<"">>, Parameters));
79 | [] ->
80 | parse_url_parameter(Rest, Parameters)
81 | end.
82 |
83 |
84 | url_to_binary(UrlInfo) ->
85 | ParameterStr = format_parameter(UrlInfo#dubbo_url.parameters),
86 | Value = lists:flatten(io_lib:format(<<"~s://~s:~p/~s?~s">>,
87 | [
88 | UrlInfo#dubbo_url.scheme,
89 | UrlInfo#dubbo_url.host,
90 | UrlInfo#dubbo_url.port,
91 | format_path(UrlInfo#dubbo_url.path),
92 | ParameterStr
93 | ])),
94 | list_to_binary(Value).
95 | format_path(<< ?URL_PATH_SEPARATOR:8,Rest/binary>>) ->
96 | Rest;
97 | format_path(Value) ->
98 | Value.
99 |
100 | format_parameter(Parameter) when is_map(Parameter) ->
101 | KeyValues = maps:to_list(Parameter),
102 | format_parameter(KeyValues);
103 | format_parameter(Parameters) ->
104 | KeyValues2 = [io_lib:format("~s=~s", [Key, Value]) || {Key, Value} <- Parameters],
105 | ParameterStr1 = string:join(KeyValues2, "&"),
106 | ParameterStr1.
107 |
108 | binary_list_join([], _Separator) ->
109 | <<"">>;
110 | binary_list_join([H | T], Separator) ->
111 | binary_list_join1(H, T, Separator).
112 |
113 | binary_list_join1(Header, [], _Separator) ->
114 | Header;
115 | binary_list_join1(Header, [Item | Rest], Separator) ->
116 | binary_list_join1(<>, Rest, Separator).
117 |
118 |
--------------------------------------------------------------------------------
/src/dubbo_config_util.erl:
--------------------------------------------------------------------------------
1 | %%------------------------------------------------------------------------------
2 | %% Licensed to the Apache Software Foundation (ASF) under one or more
3 | %% contributor license agreements. See the NOTICE file distributed with
4 | %% this work for additional information regarding copyright ownership.
5 | %% The ASF licenses this file to You under the Apache License, Version 2.0
6 | %% (the "License"); you may not use this file except in compliance with
7 | %% the License. You may obtain a copy of the License at
8 | %%
9 | %% http://www.apache.org/licenses/LICENSE-2.0
10 | %%
11 | %% Unless required by applicable law or agreed to in writing, software
12 | %% distributed under the License is distributed on an "AS IS" BASIS,
13 | %% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 | %% See the License for the specific language governing permissions and
15 | %% limitations under the License.
16 | %%------------------------------------------------------------------------------
17 | -module(dubbo_config_util).
18 |
19 | -include("dubbo.hrl").
20 | %% API
21 | -export([gen_consumer/3, gen_provider/6]).
22 |
23 |
24 | gen_consumer(Application, Interface, Option) ->
25 | #consumer_config{
26 | interface = Interface,
27 | application = Application,
28 | category = <<"consumers">>,
29 | check = false,
30 | default_timeout = proplists:get_value(default_timeout, Option, 500),
31 | dubbo_version = proplists:get_value(dubbo_version, Option, ?DUBBO_VERSION),
32 | methods = [],
33 | revision = <<"">>,
34 | side = <<"consumers">>
35 | }.
36 |
37 | gen_provider(Application, Port, Interface, MethodList, ImplModuleName, _Option) ->
38 | Host = dubbo_network_tools:local_ipv4_binary(),
39 | MethodList2 = [atom_to_binary(Item, utf8) || Item <- MethodList],
40 | #provider_config{
41 | protocol = <<"dubbo">>,
42 | host = Host,
43 | port = Port,
44 | interface = Interface,
45 | anyhost = true,
46 | executes = 10,
47 | application = Application,
48 | methods = MethodList2,
49 | side = <<"provider">>,
50 | impl_handle = ImplModuleName
51 | }.
--------------------------------------------------------------------------------
/src/dubbo_exchanger.erl:
--------------------------------------------------------------------------------
1 | %%------------------------------------------------------------------------------
2 | %% Licensed to the Apache Software Foundation (ASF) under one or more
3 | %% contributor license agreements. See the NOTICE file distributed with
4 | %% this work for additional information regarding copyright ownership.
5 | %% The ASF licenses this file to You under the Apache License, Version 2.0
6 | %% (the "License"); you may not use this file except in compliance with
7 | %% the License. You may obtain a copy of the License at
8 | %%
9 | %% http://www.apache.org/licenses/LICENSE-2.0
10 | %%
11 | %% Unless required by applicable law or agreed to in writing, software
12 | %% distributed under the License is distributed on an "AS IS" BASIS,
13 | %% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 | %% See the License for the specific language governing permissions and
15 | %% limitations under the License.
16 | %%------------------------------------------------------------------------------
17 | -module(dubbo_exchanger).
18 |
19 | -include("dubbo.hrl").
20 |
21 | %% API
22 | -export([connect/2]).
23 |
24 | connect(ProviderConfig, Handler) ->
25 | HostFlag = dubbo_provider_consumer_reg_table:get_host_flag(ProviderConfig),
26 | {ok, Pid} = dubbo_transport_pool_sup:add_children(ProviderConfig, Handler),
27 | logger:info("start provider ~p pid info ~p~n", [HostFlag, Pid]),
28 | {ok, #connection_info{pid = Pid, weight = get_weight(ProviderConfig), host_flag = HostFlag}}.
29 |
30 | get_weight(_ProviderConfig) ->
31 | 100.
--------------------------------------------------------------------------------
/src/dubbo_filter.erl:
--------------------------------------------------------------------------------
1 | %%------------------------------------------------------------------------------
2 | %% Licensed to the Apache Software Foundation (ASF) under one or more
3 | %% contributor license agreements. See the NOTICE file distributed with
4 | %% this work for additional information regarding copyright ownership.
5 | %% The ASF licenses this file to You under the Apache License, Version 2.0
6 | %% (the "License"); you may not use this file except in compliance with
7 | %% the License. You may obtain a copy of the License at
8 | %%
9 | %% http://www.apache.org/licenses/LICENSE-2.0
10 | %%
11 | %% Unless required by applicable law or agreed to in writing, software
12 | %% distributed under the License is distributed on an "AS IS" BASIS,
13 | %% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 | %% See the License for the specific language governing permissions and
15 | %% limitations under the License.
16 | %%------------------------------------------------------------------------------
17 | -module(dubbo_filter).
18 | -include("dubbo.hrl").
19 |
20 | -type filter_result() :: {ok, Invocation :: invocation(), Acc :: invoke_result()}|{stop, term()}.
21 |
22 | -callback(invoke(Invocation :: #dubbo_rpc_invocation{}, Acc :: invoke_result()) -> filter_result()).
23 |
24 | -callback(on_response(Invocation :: invocation(), Result :: invoke_result()) -> filter_result()).
25 |
26 |
27 |
28 |
--------------------------------------------------------------------------------
/src/dubbo_heartbeat.erl:
--------------------------------------------------------------------------------
1 | %%------------------------------------------------------------------------------
2 | %% Licensed to the Apache Software Foundation (ASF) under one or more
3 | %% contributor license agreements. See the NOTICE file distributed with
4 | %% this work for additional information regarding copyright ownership.
5 | %% The ASF licenses this file to You under the Apache License, Version 2.0
6 | %% (the "License"); you may not use this file except in compliance with
7 | %% the License. You may obtain a copy of the License at
8 | %%
9 | %% http://www.apache.org/licenses/LICENSE-2.0
10 | %%
11 | %% Unless required by applicable law or agreed to in writing, software
12 | %% distributed under the License is distributed on an "AS IS" BASIS,
13 | %% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 | %% See the License for the specific language governing permissions and
15 | %% limitations under the License.
16 | %%------------------------------------------------------------------------------
17 | -module(dubbo_heartbeat).
18 |
19 | -include("dubbo.hrl").
20 | %% API
21 | -export([generate_request/2]).
22 |
23 | -spec(generate_request(RequestId :: undefined|integer(), NeedResponse :: boolean()) -> {ok, binary()}).
24 | generate_request(undefined, NeedResponse) ->
25 | RequestId = dubbo_id_generator:gen_id(),
26 | generate_request(RequestId, NeedResponse);
27 | generate_request(RequestId, NeedResponse) ->
28 | Req = #dubbo_request{is_event = true, is_twoway = NeedResponse, mid = RequestId, data = undefined, mversion = <<"2.0.0">>},
29 | {ok, Bin} = dubbo_codec:encode_request(Req),
30 | {ok, Bin}.
--------------------------------------------------------------------------------
/src/dubbo_invoker.erl:
--------------------------------------------------------------------------------
1 | %%------------------------------------------------------------------------------
2 | %% Licensed to the Apache Software Foundation (ASF) under one or more
3 | %% contributor license agreements. See the NOTICE file distributed with
4 | %% this work for additional information regarding copyright ownership.
5 | %% The ASF licenses this file to You under the Apache License, Version 2.0
6 | %% (the "License"); you may not use this file except in compliance with
7 | %% the License. You may obtain a copy of the License at
8 | %%
9 | %% http://www.apache.org/licenses/LICENSE-2.0
10 | %%
11 | %% Unless required by applicable law or agreed to in writing, software
12 | %% distributed under the License is distributed on an "AS IS" BASIS,
13 | %% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 | %% See the License for the specific language governing permissions and
15 | %% limitations under the License.
16 | %%------------------------------------------------------------------------------
17 | -module(dubbo_invoker).
18 |
19 | -include("dubbo.hrl").
20 | %% API
21 | -export([]).
22 |
23 |
24 | %% API
25 | -export([invoke_request/2, invoke_request/3, invoke_request/5, invoke_response/2]).
26 |
27 | -spec invoke_request(Interface :: binary(), Request :: #dubbo_request{}) ->
28 | {ok, reference()}|
29 | {ok, reference(), Data :: any(), RpcContent :: list()}|
30 | {error, Reason :: timeout|no_provider|any()}.
31 | invoke_request(Interface, Request) ->
32 | invoke_request(Interface, Request, [], #{}, self()).
33 |
34 | -spec invoke_request(Interface :: binary(), Request :: #dubbo_request{}, RequestOption :: map()) ->
35 | {ok, reference()}|
36 | {ok, reference(), Data :: any(), RpcContent :: list()}|
37 | {error, Reason :: timeout|no_provider|any()}.
38 | invoke_request(Interface, Request, RequestOption) ->
39 | invoke_request(Interface, Request, RequestOption, self()).
40 |
41 |
42 | -spec invoke_request(Interface :: binary(), Request :: #dubbo_request{}, RpcContext :: list(), RequestState :: map(), CallBackPid :: pid()) ->
43 | {ok, reference()}|
44 | {ok, reference(), Data :: any(), RpcContent :: list()}|
45 | {error, Reason :: timeout|no_provider|request_full|any()}.
46 | invoke_request(Interface, Request, _RpcContext, _RequestState, CallBackPid) ->
47 | invoke_request(Interface,Request,#{},CallBackPid).
48 |
49 | invoke_request(Interface, Request, RequestOption, CallBackPid) ->
50 | case dubbo_provider_consumer_reg_table:get_interface_info(Interface) of
51 | undefined ->
52 | {error, no_provider};
53 | #interface_info{protocol = Protocol, loadbalance = LoadBalance} ->
54 | ReferenceConfig = #reference_config{sync = is_sync(RequestOption)},
55 | Ref = get_ref(RequestOption),
56 | RpcContext = get_ctx(RequestOption),
57 | Attachments = merge_attachments(Request,RpcContext),
58 | Invocation = Request#dubbo_request.data#dubbo_rpc_invocation{
59 | loadbalance = LoadBalance,
60 | call_ref = Ref,
61 | reference_ops = ReferenceConfig,
62 | source_pid = CallBackPid,
63 | attachments = Attachments
64 | },
65 | Result = dubbo_extension:invoke(filter, invoke, [Invocation], {ok, Ref}, [Protocol]),
66 | Result
67 | end.
68 |
69 | invoke_response(Invocation, Result) ->
70 | Result2 = dubbo_extension:invoke_foldr(filter, on_response, [Invocation], Result),
71 | gen_server:cast(Invocation#dubbo_rpc_invocation.source_pid, {response_process, Invocation#dubbo_rpc_invocation.call_ref, Invocation#dubbo_rpc_invocation.attachments, Result2}),
72 | ok.
73 |
74 | is_sync(Option) ->
75 | maps:is_key(sync, Option).
76 | get_ref(Option) ->
77 | maps:get(ref, Option, make_ref()).
78 | get_ctx(Option)->
79 | maps:get(ctx, Option, []).
80 |
81 | merge_attachments(Request, OptionAttachments) ->
82 | Attachments = Request#dubbo_request.data#dubbo_rpc_invocation.attachments,
83 | List = [
84 | {<<"version">>, <<"0.0.0">>}
85 | ],
86 | lists:merge3(Attachments, OptionAttachments, List).
87 |
--------------------------------------------------------------------------------
/src/dubbo_lists_util.erl:
--------------------------------------------------------------------------------
1 | %%------------------------------------------------------------------------------
2 | %% Licensed to the Apache Software Foundation (ASF) under one or more
3 | %% contributor license agreements. See the NOTICE file distributed with
4 | %% this work for additional information regarding copyright ownership.
5 | %% The ASF licenses this file to You under the Apache License, Version 2.0
6 | %% (the "License"); you may not use this file except in compliance with
7 | %% the License. You may obtain a copy of the License at
8 | %%
9 | %% http://www.apache.org/licenses/LICENSE-2.0
10 | %%
11 | %% Unless required by applicable law or agreed to in writing, software
12 | %% distributed under the License is distributed on an "AS IS" BASIS,
13 | %% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 | %% See the License for the specific language governing permissions and
15 | %% limitations under the License.
16 | %%------------------------------------------------------------------------------
17 | -module(dubbo_lists_util).
18 | %% API
19 | -export([join/2, del_duplicate/1]).
20 |
21 | -spec(join(List :: list(), Separator :: binary()) -> binary()).
22 | join(List, _Separator) when length(List) == 0 ->
23 | <<"">>;
24 | join(List, Separator) ->
25 | [First | Rst] = List,
26 | Acc2 = lists:foldl(fun(Item, Acc) ->
27 | if
28 | is_binary(Item) ->
29 | <>;
30 | is_list(Item) ->
31 | Item2 = list_to_binary(Item),
32 | <>;
33 | true ->
34 | Acc
35 | end
36 | end, First, Rst),
37 | Acc2.
38 |
39 |
40 | del_duplicate(List) ->
41 | lists:foldl(
42 | fun(X, List2) ->
43 | case lists:member(X, List2) of
44 | true ->
45 | List2;
46 | _ ->
47 | [X] ++ List2
48 | end
49 | end, [], List).
50 |
--------------------------------------------------------------------------------
/src/dubbo_loadbalance_random.erl:
--------------------------------------------------------------------------------
1 | %%------------------------------------------------------------------------------
2 | %% Licensed to the Apache Software Foundation (ASF) under one or more
3 | %% contributor license agreements. See the NOTICE file distributed with
4 | %% this work for additional information regarding copyright ownership.
5 | %% The ASF licenses this file to You under the Apache License, Version 2.0
6 | %% (the "License"); you may not use this file except in compliance with
7 | %% the License. You may obtain a copy of the License at
8 | %%
9 | %% http://www.apache.org/licenses/LICENSE-2.0
10 | %%
11 | %% Unless required by applicable law or agreed to in writing, software
12 | %% distributed under the License is distributed on an "AS IS" BASIS,
13 | %% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 | %% See the License for the specific language governing permissions and
15 | %% limitations under the License.
16 | %%------------------------------------------------------------------------------
17 | -module(dubbo_loadbalance_random).
18 |
19 | %% API
20 | -export([select/1]).
21 |
22 | select(List) ->
23 | RandNum = rand:uniform(65535),
24 | Len = length(List),
25 | RemNum = (RandNum rem Len) + 1,
26 | lists:nth(RemNum, List).
27 |
--------------------------------------------------------------------------------
/src/dubbo_network_tools.erl:
--------------------------------------------------------------------------------
1 | %%------------------------------------------------------------------------------
2 | %% Licensed to the Apache Software Foundation (ASF) under one or more
3 | %% contributor license agreements. See the NOTICE file distributed with
4 | %% this work for additional information regarding copyright ownership.
5 | %% The ASF licenses this file to You under the Apache License, Version 2.0
6 | %% (the "License"); you may not use this file except in compliance with
7 | %% the License. You may obtain a copy of the License at
8 | %%
9 | %% http://www.apache.org/licenses/LICENSE-2.0
10 | %%
11 | %% Unless required by applicable law or agreed to in writing, software
12 | %% distributed under the License is distributed on an "AS IS" BASIS,
13 | %% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 | %% See the License for the specific language governing permissions and
15 | %% limitations under the License.
16 | %%------------------------------------------------------------------------------
17 | -module(dubbo_network_tools).
18 |
19 | %% API
20 | -export([local_ip_v4/0, local_ipv4/0, local_ipv4_binary/0]).
21 |
22 |
23 | local_ip_v4() ->
24 | {ok, Addrs} = inet:getifaddrs(),
25 | hd([
26 | Addr || {_, Opts} <- Addrs, {addr, Addr} <- Opts,
27 | size(Addr) == 4, Addr =/= {127, 0, 0, 1}
28 | ]).
29 |
30 | local_ipv4_binary() ->
31 | {I1, I2, I3, I4} = local_ip_v4(),
32 | list_to_binary(io_lib:format("~p.~p.~p.~p", [I1, I2, I3, I4])).
33 | local_ipv4() ->
34 | {I1, I2, I3, I4} = local_ip_v4(),
35 | lists:flatten(io_lib:format("~p.~p.~p.~p", [I1, I2, I3, I4])).
36 |
--------------------------------------------------------------------------------
/src/dubbo_node_config_util.erl:
--------------------------------------------------------------------------------
1 | %%------------------------------------------------------------------------------
2 | %% Licensed to the Apache Software Foundation (ASF) under one or more
3 | %% contributor license agreements. See the NOTICE file distributed with
4 | %% this work for additional information regarding copyright ownership.
5 | %% The ASF licenses this file to You under the Apache License, Version 2.0
6 | %% (the "License"); you may not use this file except in compliance with
7 | %% the License. You may obtain a copy of the License at
8 | %%
9 | %% http://www.apache.org/licenses/LICENSE-2.0
10 | %%
11 | %% Unless required by applicable law or agreed to in writing, software
12 | %% distributed under the License is distributed on an "AS IS" BASIS,
13 | %% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 | %% See the License for the specific language governing permissions and
15 | %% limitations under the License.
16 | %%------------------------------------------------------------------------------
17 | -module(dubbo_node_config_util).
18 |
19 | -include("dubbo.hrl").
20 | -include("dubboerl.hrl").
21 | %% API
22 | -export([parse_provider_info/1, gen_provider_info/1]).
23 |
24 | parse_provider_info(#dubbo_url{scheme = Scheme, host = Host, port = Port, parameters = Parameters}) ->
25 | ProviderInfo = #provider_config{protocol = Scheme, host = Host, port = Port},
26 | maps:to_list(Parameters),
27 | ProviderConfig = maps:fold(
28 | fun(K, V, Acc1) ->
29 | parse_parameter(K, V, Acc1)
30 | end, ProviderInfo, Parameters),
31 | logger:debug("parse provider,result: ~p", [ProviderConfig]),
32 | {ok, ProviderConfig}.
33 |
34 | parse_parameter(<<"anyhost">>, Value, Config) ->
35 | Config#provider_config{anyhost = binary_to_existing_atom(Value, latin1)};
36 | parse_parameter(<<"application">>, Value, Config) ->
37 | Config#provider_config{application = Value};
38 | parse_parameter(<<"dubbo">>, Value, Config) ->
39 | Config#provider_config{dubbo = Value};
40 | parse_parameter(<<"executes">>, Value, Config) ->
41 | Config#provider_config{executes = binary_to_integer(Value)};
42 | parse_parameter(<<"interface">>, Value, Config) ->
43 | Config#provider_config{interface = Value};
44 | parse_parameter(<<"methods">>, Value, Config) ->
45 | MethodList = binary:split(Value, <<",">>, [global, trim_all]),
46 | Config#provider_config{methods = MethodList};
47 | parse_parameter(<<"side">>, Value, Config) ->
48 | Config#provider_config{side = Value};
49 | parse_parameter(_, _, Config) ->
50 | Config.
51 |
52 | gen_provider_info(ProviderConfig) ->
53 | Parameter = gen_provider_parameter(ProviderConfig),
54 | Info = io_lib:format("dubbo://~s:~p/~s?~s", [
55 | ProviderConfig#provider_config.host,
56 | ProviderConfig#provider_config.port,
57 | ProviderConfig#provider_config.interface,
58 | Parameter
59 | ]),
60 | list_to_binary(http_uri:encode(Info)).
61 |
62 | gen_provider_parameter(Providerconfig) ->
63 | Method = [binary_to_list(Item) || Item <- Providerconfig#provider_config.methods],
64 | Method2 = list_to_binary(string:join(Method, ",")),
65 | List = [
66 | {<<"interface">>, Providerconfig#provider_config.interface},
67 | {<<"application">>, Providerconfig#provider_config.application},
68 | {<<"anyhost">>, <<"true">>},
69 | {<<"dubbo">>, Providerconfig#provider_config.dubbo},
70 | {<<"executes">>, integer_to_binary(Providerconfig#provider_config.executes)},
71 | {<<"methods">>, Method2},
72 | {<<"side">>, Providerconfig#provider_config.side},
73 | {<<"timestamp">>, integer_to_binary(dubbo_time_util:timestamp_ms())}
74 | ],
75 | List2 = [io_lib:format("~ts=~ts", [Key, Value]) || {Key, Value} <- List],
76 | lists:flatten(string:join(List2, "&")).
--------------------------------------------------------------------------------
/src/dubbo_protocol.erl:
--------------------------------------------------------------------------------
1 | %%------------------------------------------------------------------------------
2 | %% Licensed to the Apache Software Foundation (ASF) under one or more
3 | %% contributor license agreements. See the NOTICE file distributed with
4 | %% this work for additional information regarding copyright ownership.
5 | %% The ASF licenses this file to You under the Apache License, Version 2.0
6 | %% (the "License"); you may not use this file except in compliance with
7 | %% the License. You may obtain a copy of the License at
8 | %%
9 | %% http://www.apache.org/licenses/LICENSE-2.0
10 | %%
11 | %% Unless required by applicable law or agreed to in writing, software
12 | %% distributed under the License is distributed on an "AS IS" BASIS,
13 | %% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 | %% See the License for the specific language governing permissions and
15 | %% limitations under the License.
16 | %%------------------------------------------------------------------------------
17 | -module(dubbo_protocol).
18 |
19 | -include("dubbo.hrl").
20 |
21 | -callback refer(Url :: binary(), Acc :: term()) -> {ok, Acc :: term()}.
22 |
23 | -callback export(Invoker :: #invoker{}, Acc :: term()) -> {ok, Acc :: term()}.
24 |
--------------------------------------------------------------------------------
/src/dubbo_provider_worker_sup.erl:
--------------------------------------------------------------------------------
1 | %%------------------------------------------------------------------------------
2 | %% Licensed to the Apache Software Foundation (ASF) under one or more
3 | %% contributor license agreements. See the NOTICE file distributed with
4 | %% this work for additional information regarding copyright ownership.
5 | %% The ASF licenses this file to You under the Apache License, Version 2.0
6 | %% (the "License"); you may not use this file except in compliance with
7 | %% the License. You may obtain a copy of the License at
8 | %%
9 | %% http://www.apache.org/licenses/LICENSE-2.0
10 | %%
11 | %% Unless required by applicable law or agreed to in writing, software
12 | %% distributed under the License is distributed on an "AS IS" BASIS,
13 | %% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 | %% See the License for the specific language governing permissions and
15 | %% limitations under the License.
16 | %%------------------------------------------------------------------------------
17 | -module(dubbo_provider_worker_sup).
18 |
19 | -behaviour(supervisor).
20 |
21 | %% API
22 | -export([start_link/0]).
23 |
24 | %% Supervisor callbacks
25 | -export([init/1]).
26 | -define(SERVER, ?MODULE).
27 |
28 | %%%===================================================================
29 | %%% API functions
30 | %%%===================================================================
31 |
32 | %%--------------------------------------------------------------------
33 | %% @doc
34 | %% Starts the supervisor
35 | %%
36 | %% @end
37 | %%--------------------------------------------------------------------
38 | -spec(start_link() ->
39 | {ok, Pid :: pid()} | ignore | {error, Reason :: term()}).
40 | start_link() ->
41 | supervisor:start_link({local, ?SERVER}, ?MODULE, []).
42 |
43 | %%%===================================================================
44 | %%% Supervisor callbacks
45 | %%%===================================================================
46 |
47 | %%--------------------------------------------------------------------
48 | %% @private
49 | %% @doc
50 | %% Whenever a supervisor is started using supervisor:start_link/[2,3],
51 | %% this function is called by the new process to find out about
52 | %% restart strategy, maximum restart frequency and child
53 | %% specifications.
54 | %%
55 | %% @end
56 | %%--------------------------------------------------------------------
57 | -spec(init(Args :: term()) ->
58 | {ok, {SupFlags :: {RestartStrategy :: supervisor:strategy(),
59 | MaxR :: non_neg_integer(), MaxT :: non_neg_integer()},
60 | [ChildSpec :: supervisor:child_spec()]
61 | }} |
62 | ignore |
63 | {error, Reason :: term()}).
64 | init([]) ->
65 | RestartStrategy = one_for_one,
66 | MaxRestarts = 1000,
67 | MaxSecondsBetweenRestarts = 3600,
68 |
69 | SupFlags = {RestartStrategy, MaxRestarts, MaxSecondsBetweenRestarts},
70 | PoolSize = application:get_env(dubbo, pool_size, 5),
71 | MaxOverflow = application:get_env(dubbo, max_overflow, 100),
72 | Strategy = application:get_env(dubbo, strategy, fifo),
73 | PoolArgs = [{name, {local, provider_worker}},
74 | {worker_module, dubbo_provider_worker},
75 | {size, PoolSize},
76 | {max_overflow, MaxOverflow},
77 | {strategy, Strategy}
78 | ],
79 | WorkerPool = poolboy:child_spec(provider_worker, PoolArgs, []),
80 | {ok, {SupFlags, [WorkerPool]}}.
81 |
82 | %%%===================================================================
83 | %%% Internal functions
84 | %%%===================================================================
85 | %%start_child(InterfaceList)->
86 | %% ChildSpec = {dubbo_provider_server,{dubbo_provider_server,start_link,[InterfaceList]},permanent,2000,worker},
87 | %% supervisor:start_child(?SERVER,ChildSpec),
88 | %% ok.
--------------------------------------------------------------------------------
/src/dubbo_reference_config.erl:
--------------------------------------------------------------------------------
1 | %%------------------------------------------------------------------------------
2 | %% Licensed to the Apache Software Foundation (ASF) under one or more
3 | %% contributor license agreements. See the NOTICE file distributed with
4 | %% this work for additional information regarding copyright ownership.
5 | %% The ASF licenses this file to You under the Apache License, Version 2.0
6 | %% (the "License"); you may not use this file except in compliance with
7 | %% the License. You may obtain a copy of the License at
8 | %%
9 | %% http://www.apache.org/licenses/LICENSE-2.0
10 | %%
11 | %% Unless required by applicable law or agreed to in writing, software
12 | %% distributed under the License is distributed on an "AS IS" BASIS,
13 | %% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 | %% See the License for the specific language governing permissions and
15 | %% limitations under the License.
16 | %%------------------------------------------------------------------------------
17 | -module(dubbo_reference_config).
18 |
19 | -include("dubbo.hrl").
20 | -include("dubboerl.hrl").
21 |
22 | -record(dubbo_interface_info, {}).
23 |
24 | %% API
25 | -export([init_reference/1]).
26 |
27 | init_reference(ConsumerInfo) ->
28 | %% InitConfigMap= #{
29 | %%
30 | %% },
31 | %% 组装各类需要数据
32 | create_proxy(ConsumerInfo),
33 | ok.
34 |
35 |
36 | create_proxy(ConsumerInfo) ->
37 |
38 | Para = gen_parameter(ConsumerInfo),
39 | Url = gen_registry_url(Para),
40 | ok = dubbo_extension:run_fold(protocol_wapper, refer, [Url], ok),
41 | ok.
42 |
43 | gen_registry_url(Para) ->
44 | {Host, Port} = dubbo_registry:get_registry_host_port(),
45 | UrlInfo = #dubbo_url{
46 | scheme = <<"registry">>,
47 | host = list_to_binary(Host),
48 | port = Port,
49 | path = <<"org.apache.dubbo.registry.RegistryService">>,
50 | parameters = Para
51 | },
52 | dubbo_common_fun:url_to_binary(UrlInfo).
53 |
54 | gen_parameter(ConsumerInfo) ->
55 | Para = #{
56 | <<"application">> => get_appname(ConsumerInfo),
57 | <<"dubbo">> => <<"2.0.2">>,
58 | <<"pid">> => list_to_binary(get_pid()),
59 | <<"refer">> => get_refinfo(ConsumerInfo),
60 | <<"registry">> => dubbo_registry:get_registry_type(),
61 | <<"release">> => <<"2.7.1">>,
62 | <<"timestamp">> => integer_to_binary(dubbo_time_util:timestamp_ms())
63 | },
64 | Para.
65 |
66 | get_appname(ConsumerInfo) ->
67 | ConsumerInfo#consumer_config.application.
68 | get_pid() ->
69 | os:getpid().
70 | get_refinfo(ConsumerInfo) ->
71 | KeyValues = [
72 | {"application", ConsumerInfo#consumer_config.application},
73 | {"default.check", atom_to_list(ConsumerInfo#consumer_config.check)},
74 | {"default.lazy", "false"},
75 | {"default.retries", "0"},
76 | {"default.sticky", "false"},
77 | {"default.timeout", "300000"},
78 | {"dubbo", "2.0.2"},
79 | {"interface", ConsumerInfo#consumer_config.interface},
80 | {"lazy", "false"},
81 | {"methods", string:join(ConsumerInfo#consumer_config.methods, ",")},
82 | {"register.ip", ConsumerInfo#consumer_config.application},
83 | {"release", "2.7.1"},
84 | {"pid", get_pid()},
85 | {"side", "consumer"},
86 | {"sticky", "false"},
87 | {"timestamp", integer_to_list(dubbo_time_util:timestamp_ms())}
88 | ],
89 | KeyValues2 = [io_lib:format("~s=~s", [Key, Value]) || {Key, Value} <- KeyValues],
90 | ParameterStr1 = string:join(KeyValues2, "&"),
91 | list_to_binary(http_uri:encode(ParameterStr1)).
92 | %% <<"application%3Dhello-world%26default.check%3Dfalse%26default.lazy%3Dfalse%26default.retries%3D0%26default.sticky%3Dfalse%26default.timeout%3D300000%26dubbo%3D2.0.2%26interface%3Dorg.apache.dubbo.erlang.sample.service.facade.UserOperator%26lazy%3Dfalse%26methods%3DqueryUserInfo%2CqueryUserList%2CgenUserId%2CgetUserInfo%26pid%3D68901%26register.ip%3D127..0.1%26release%3D2.7.1%26retries%3D0%26side%3Dconsumer%26sticky%3Dfalse%26timestamp%3D1559727789953">>.
93 |
94 |
95 |
--------------------------------------------------------------------------------
/src/dubbo_registry.erl:
--------------------------------------------------------------------------------
1 | %%------------------------------------------------------------------------------
2 | %% Licensed to the Apache Software Foundation (ASF) under one or more
3 | %% contributor license agreements. See the NOTICE file distributed with
4 | %% this work for additional information regarding copyright ownership.
5 | %% The ASF licenses this file to You under the Apache License, Version 2.0
6 | %% (the "License"); you may not use this file except in compliance with
7 | %% the License. You may obtain a copy of the License at
8 | %%
9 | %% http://www.apache.org/licenses/LICENSE-2.0
10 | %%
11 | %% Unless required by applicable law or agreed to in writing, software
12 | %% distributed under the License is distributed on an "AS IS" BASIS,
13 | %% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 | %% See the License for the specific language governing permissions and
15 | %% limitations under the License.
16 | %%------------------------------------------------------------------------------
17 | -module(dubbo_registry).
18 | -include("dubboerl.hrl").
19 |
20 | -callback start(Url :: binary) -> ok | {error,Reason::term()}.
21 | -callback register(Url :: binary()) -> ok | {error,Reason::term()}.
22 | -callback subscribe(SubcribeUrl :: binary(), NotifyFun :: function()) -> ok | {error,Reason::term()}.
23 |
24 | %% API
25 | -export([setup_register/1, register/2, unregister/2, get_registry_host_port/0, get_registry_type/0, get_registry_module/1]).
26 |
27 | -spec(setup_register(UrlInfo :: #dubbo_url{}) -> {ok, RegistryProcessName :: atom()}|{error, term()}).
28 | setup_register(UrlInfo) ->
29 | RegistryModuleName = get_registry_module(UrlInfo),
30 | case whereis(RegistryModuleName) of
31 | undefined ->
32 | apply(RegistryModuleName, start, [UrlInfo]),
33 | {ok, RegistryModuleName};
34 | _ ->
35 | {ok, RegistryModuleName}
36 | end.
37 |
38 | register(RegistryName, Url) ->
39 | logger:info("call ~p register url ~p", [RegistryName, Url]),
40 | Result = apply(RegistryName, register, [Url]),
41 | Result.
42 | unregister(RegistryName, Url) ->
43 | logger:info("call ~p unregister url ~p", [RegistryName, Url]),
44 | Result = apply(RegistryName, unregister, [Url]),
45 | Result.
46 |
47 | get_registry_module(Info) ->
48 | RegistryName = Info#dubbo_url.scheme,
49 | FullName = <<<<"dubbo_registry_">>/binary, RegistryName/binary>>,
50 | binary_to_existing_atom(FullName, latin1).
51 |
52 |
53 |
54 | get_registry_host_port() ->
55 | %% @todo need adapter other registry
56 | RegistryList = application:get_env(dubboerl, zookeeper_list, [{"127.0.0.1", 2181}]),
57 | [Item | _] = RegistryList,
58 | Item.
59 |
60 | get_registry_type() ->
61 | %%todo
62 | atom_to_binary(application:get_env(dubboerl, registry, zookeeper), utf8).
--------------------------------------------------------------------------------
/src/dubbo_registry_sup.erl:
--------------------------------------------------------------------------------
1 | %%------------------------------------------------------------------------------
2 | %% Licensed to the Apache Software Foundation (ASF) under one or more
3 | %% contributor license agreements. See the NOTICE file distributed with
4 | %% this work for additional information regarding copyright ownership.
5 | %% The ASF licenses this file to You under the Apache License, Version 2.0
6 | %% (the "License"); you may not use this file except in compliance with
7 | %% the License. You may obtain a copy of the License at
8 | %%
9 | %% http://www.apache.org/licenses/LICENSE-2.0
10 | %%
11 | %% Unless required by applicable law or agreed to in writing, software
12 | %% distributed under the License is distributed on an "AS IS" BASIS,
13 | %% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 | %% See the License for the specific language governing permissions and
15 | %% limitations under the License.
16 | %%------------------------------------------------------------------------------
17 | -module(dubbo_registry_sup).
18 |
19 | -behaviour(supervisor).
20 |
21 | %% API
22 | -export([start_link/0, start_child/3]).
23 |
24 | %% Supervisor callbacks
25 | -export([init/1]).
26 |
27 | -define(SERVER, ?MODULE).
28 |
29 | %%%===================================================================
30 | %%% API functions
31 | %%%===================================================================
32 |
33 | %%--------------------------------------------------------------------
34 | %% @doc
35 | %% Starts the supervisor
36 | %%
37 | %% @end
38 | %%--------------------------------------------------------------------
39 | -spec(start_link() ->
40 | {ok, Pid :: pid()} | ignore | {error, Reason :: term()}).
41 | start_link() ->
42 | supervisor:start_link({local, ?SERVER}, ?MODULE, []).
43 |
44 | %%%===================================================================
45 | %%% Supervisor callbacks
46 | %%%===================================================================
47 |
48 | %%--------------------------------------------------------------------
49 | %% @private
50 | %% @doc
51 | %% Whenever a supervisor is started using supervisor:start_link/[2,3],
52 | %% this function is called by the new process to find out about
53 | %% restart strategy, maximum restart frequency and child
54 | %% specifications.
55 | %%
56 | %% @end
57 | %%--------------------------------------------------------------------
58 | -spec(init(Args :: term()) ->
59 | {ok, {SupFlags :: {RestartStrategy :: supervisor:strategy(),
60 | MaxR :: non_neg_integer(), MaxT :: non_neg_integer()},
61 | [ChildSpec :: supervisor:child_spec()]
62 | }} |
63 | ignore |
64 | {error, Reason :: term()}).
65 | init([]) ->
66 | RestartStrategy = one_for_one,
67 | MaxRestarts = 1000,
68 | MaxSecondsBetweenRestarts = 3600,
69 |
70 | SupFlags = {RestartStrategy, MaxRestarts, MaxSecondsBetweenRestarts},
71 |
72 | %% AChild = {'AName', {'AModule', start_link, []}, Restart, Shutdown, Type, ['AModule']},
73 |
74 | {ok, {SupFlags, []}}.
75 |
76 | start_child(Id, StartSepc, Module) ->
77 | Restart = permanent,
78 | Shutdown = 2000,
79 | Type = worker,
80 |
81 | Child = {Id, StartSepc,
82 | Restart, Shutdown, Type, [Module]},
83 | supervisor:start_child(?MODULE, Child),
84 | ok.
85 | %%%===================================================================
86 | %%% Internal functions
87 | %%%===================================================================
88 |
--------------------------------------------------------------------------------
/src/dubbo_service_config.erl:
--------------------------------------------------------------------------------
1 | %%------------------------------------------------------------------------------
2 | %% Licensed to the Apache Software Foundation (ASF) under one or more
3 | %% contributor license agreements. See the NOTICE file distributed with
4 | %% this work for additional information regarding copyright ownership.
5 | %% The ASF licenses this file to You under the Apache License, Version 2.0
6 | %% (the "License"); you may not use this file except in compliance with
7 | %% the License. You may obtain a copy of the License at
8 | %%
9 | %% http://www.apache.org/licenses/LICENSE-2.0
10 | %%
11 | %% Unless required by applicable law or agreed to in writing, software
12 | %% distributed under the License is distributed on an "AS IS" BASIS,
13 | %% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 | %% See the License for the specific language governing permissions and
15 | %% limitations under the License.
16 | %%------------------------------------------------------------------------------
17 | -module(dubbo_service_config).
18 |
19 | -include("dubbo.hrl").
20 | -include("dubboerl.hrl").
21 | %% API
22 | -export([export/1]).
23 |
24 | -spec(export(#provider_config{}) -> ok).
25 | export(ProviderInfo) ->
26 | logger:debug("will export provider info ~p", [ProviderInfo]),
27 | do_export(ProviderInfo),
28 | ok.
29 |
30 | do_export(ProviderInfo) ->
31 | do_export_protocol(ProviderInfo),
32 | ok.
33 |
34 | do_export_protocol(ProviderInfo) ->
35 | Url = get_registry_url(ProviderInfo),
36 | logger:debug("do export protocol for url ~p", [Url]),
37 | Invoker = #invoker{url = Url, handler = ProviderInfo#provider_config.impl_handle},
38 | dubbo_extension:run_fold(protocol_wapper, export, [Invoker], ok),
39 | ok.
40 |
41 |
42 | get_registry_url(ProviderInfo) ->
43 | {Host, Port} = dubbo_registry:get_registry_host_port(),
44 | UrlInfo = #dubbo_url{
45 | scheme = <<"registry">>,
46 | host = list_to_binary(Host),
47 | port = Port,
48 | path = <<"org.apache.dubbo.registry.RegistryService">>,
49 | parameters = gen_registry_parameter(ProviderInfo)
50 | },
51 | dubbo_common_fun:url_to_binary(UrlInfo).
52 |
53 | gen_registry_parameter(ProviderInfo) ->
54 | Para = #{
55 | <<"application">> => ProviderInfo#provider_config.application,
56 | <<"dubbo">> => <<"2.0.2">>,
57 | <<"pid">> => list_to_binary(os:getpid()),
58 | <<"export">> => get_export_info(ProviderInfo),
59 | <<"registry">> => dubbo_registry:get_registry_type(),
60 | <<"release">> => <<"2.7.1">>,
61 | <<"timestamp">> => integer_to_binary(dubbo_time_util:timestamp_ms())
62 | },
63 | Para.
64 |
65 | get_export_info(ProviderInfo) ->
66 | Para = [
67 | {"anyhost", "true"},
68 | {"application", ProviderInfo#provider_config.application},
69 | {"bean.name", ProviderInfo#provider_config.interface},
70 | {"bind.ip", dubbo_common_fun:local_ip_v4_str()},
71 | {"bind.port", integer_to_list(ProviderInfo#provider_config.port)},
72 | {"default.deprecated", "false"},
73 | {"default.dynamic", "false"},
74 | {"default.register", "true"},
75 | {"deprecated", "false"},
76 | {"dynamic", "true"},
77 | {"generic", "false"},
78 | {"interface", ProviderInfo#provider_config.interface},
79 | {"methods", format_methods_str(ProviderInfo#provider_config.methods)},
80 | {"pid", os:getpid()},
81 | {"register", "true"},
82 | {"release", "2.7.1"},
83 | {"side", "provider"},
84 | {"dubbo", "2.0.2"},
85 | {"timestamp", integer_to_list(dubbo_time_util:timestamp_ms())}
86 | ],
87 | UrlInfo = #dubbo_url{
88 | scheme = ProviderInfo#provider_config.protocol,
89 | host = dubbo_common_fun:local_ip_v4_str(),
90 | port = ProviderInfo#provider_config.port,
91 | path = ProviderInfo#provider_config.interface,
92 | parameters = Para
93 | },
94 | Url = dubbo_common_fun:url_to_binary(UrlInfo),
95 | list_to_binary(http_uri:encode(binary_to_list(Url))).
96 |
97 | format_methods_str(Methods) ->
98 | Methods2 = [binary_to_list(Item) || Item <- Methods],
99 | string:join(Methods2, ",").
--------------------------------------------------------------------------------
/src/dubbo_time_util.erl:
--------------------------------------------------------------------------------
1 | %%------------------------------------------------------------------------------
2 | %% Licensed to the Apache Software Foundation (ASF) under one or more
3 | %% contributor license agreements. See the NOTICE file distributed with
4 | %% this work for additional information regarding copyright ownership.
5 | %% The ASF licenses this file to You under the Apache License, Version 2.0
6 | %% (the "License"); you may not use this file except in compliance with
7 | %% the License. You may obtain a copy of the License at
8 | %%
9 | %% http://www.apache.org/licenses/LICENSE-2.0
10 | %%
11 | %% Unless required by applicable law or agreed to in writing, software
12 | %% distributed under the License is distributed on an "AS IS" BASIS,
13 | %% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 | %% See the License for the specific language governing permissions and
15 | %% limitations under the License.
16 | %%------------------------------------------------------------------------------
17 | -module(dubbo_time_util).
18 |
19 | -include_lib("kernel/include/file.hrl").
20 |
21 |
22 | -export([
23 | get_cur_time/0, get_cur_time/1,
24 | format_time_to_str/1,
25 | timestamp/0, timestamp_ms/0,
26 | timestamp_to_datetime/1,
27 | timestamp_to_local_datetime/1,
28 | get_cur_date/0,
29 | datetime_to_timestamp/1]).
30 |
31 |
32 | get_cur_time() ->
33 | {{Year, Month, Day}, {Hour, Min, Second}} = calendar:now_to_local_time(os:timestamp()),
34 | io_lib:format("~4..0w-~2..0w-~2..0w ~2..0w:~2..0w:~2..0w", [Year, Month, Day, Hour, Min, Second]).
35 |
36 | get_cur_date() ->
37 | {{Year, Month, Day}, {_Hour, _Min, _Second}} = calendar:now_to_local_time(os:timestamp()),
38 | io_lib:format("~4..0w-~2..0w-~2..0w", [Year, Month, Day]).
39 |
40 | get_cur_time({{Year, Month, Day}, {Hour, Min, Second}}) ->
41 | io_lib:format("~4..0w-~2..0w-~2..0w ~2..0w:~2..0w:~2..0w", [Year, Month, Day, Hour, Min, Second]).
42 |
43 | format_time_to_str({{Year, Month, Day}, {Hour, Min, Second}}) ->
44 | io_lib:format("~4..0w-~2..0w-~2..0w ~2..0w:~2..0w:~2..0w", [Year, Month, Day, Hour, Min, Second]).
45 |
46 | timestamp() ->
47 | {M, S, _} = os:timestamp(),
48 | M * 1000000 + S.
49 | timestamp_ms() ->
50 | {M, S, W} = os:timestamp(),
51 | M * 1000000000 + S * 1000 + (W div 1000).
52 |
53 | timestamp_to_datetime(Timestamp) ->
54 | calendar:gregorian_seconds_to_datetime(Timestamp +
55 | calendar:datetime_to_gregorian_seconds({{1970, 1, 1}, {0, 0, 0}})).
56 | timestamp_to_local_datetime(Timestamp) ->
57 | Date = calendar:gregorian_seconds_to_datetime(Timestamp +
58 | calendar:datetime_to_gregorian_seconds({{1970, 1, 1}, {0, 0, 0}})),
59 | calendar:universal_time_to_local_time(Date).
60 |
61 | datetime_to_timestamp(Date) ->
62 | [{D, T}] = calendar:local_time_to_universal_time_dst(Date),
63 | S = calendar:datetime_to_gregorian_seconds({D, T}),
64 | S1 = calendar:datetime_to_gregorian_seconds({{1970, 1, 1}, {0, 0, 0}}),
65 | (S - S1).
66 |
--------------------------------------------------------------------------------
/src/dubbo_traffic_control.erl:
--------------------------------------------------------------------------------
1 | %%------------------------------------------------------------------------------
2 | %% Licensed to the Apache Software Foundation (ASF) under one or more
3 | %% contributor license agreements. See the NOTICE file distributed with
4 | %% this work for additional information regarding copyright ownership.
5 | %% The ASF licenses this file to You under the Apache License, Version 2.0
6 | %% (the "License"); you may not use this file except in compliance with
7 | %% the License. You may obtain a copy of the License at
8 | %%
9 | %% http://www.apache.org/licenses/LICENSE-2.0
10 | %%
11 | %% Unless required by applicable law or agreed to in writing, software
12 | %% distributed under the License is distributed on an "AS IS" BASIS,
13 | %% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 | %% See the License for the specific language governing permissions and
15 | %% limitations under the License.
16 | %%------------------------------------------------------------------------------
17 | -module(dubbo_traffic_control).
18 | -include("dubboerl.hrl").
19 | %% API
20 | -export([init/0, check_goon/2, decr_count/1]).
21 |
22 |
23 | init() ->
24 | case ets:info(?TRAFFIC_CONTROL) of
25 | undefined ->
26 | ets:new(?TRAFFIC_CONTROL, [public, named_table, {write_concurrency, true}]); %% public
27 | _ ->
28 | ets:delete(?TRAFFIC_CONTROL),
29 | ets:new(?TRAFFIC_CONTROL, [public, named_table, {write_concurrency, true}])
30 | end,
31 | ok.
32 |
33 |
34 | check_goon(Key, Max) ->
35 | try ets:update_counter(?TRAFFIC_CONTROL, Key, 1) of
36 | Value when Value > Max ->
37 | ets:update_counter(?TRAFFIC_CONTROL, Key, -1),
38 | full;
39 | _V ->
40 | ok
41 | catch
42 | _T:_R ->
43 | ets:insert(?TRAFFIC_CONTROL, {Key, 1}),
44 | ok
45 | end.
46 |
47 | decr_count(Key) ->
48 | try ets:update_counter(?TRAFFIC_CONTROL, Key, -1) of
49 | _V ->
50 | ok
51 | catch
52 | _T:_R ->
53 | ets:insert(?TRAFFIC_CONTROL, {Key, 0}),
54 | ok
55 | end.
--------------------------------------------------------------------------------
/src/dubbo_transport_pool_sup.erl:
--------------------------------------------------------------------------------
1 | %%------------------------------------------------------------------------------
2 | %% Licensed to the Apache Software Foundation (ASF) under one or more
3 | %% contributor license agreements. See the NOTICE file distributed with
4 | %% this work for additional information regarding copyright ownership.
5 | %% The ASF licenses this file to You under the Apache License, Version 2.0
6 | %% (the "License"); you may not use this file except in compliance with
7 | %% the License. You may obtain a copy of the License at
8 | %%
9 | %% http://www.apache.org/licenses/LICENSE-2.0
10 | %%
11 | %% Unless required by applicable law or agreed to in writing, software
12 | %% distributed under the License is distributed on an "AS IS" BASIS,
13 | %% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 | %% See the License for the specific language governing permissions and
15 | %% limitations under the License.
16 | %%------------------------------------------------------------------------------
17 | -module(dubbo_transport_pool_sup).
18 |
19 | -behaviour(supervisor).
20 |
21 | %% API
22 | -export([start_link/0, add_children/2, stop_children/1]).
23 |
24 | %% Supervisor callbacks
25 | -export([init/1]).
26 |
27 | -define(SERVER, ?MODULE).
28 |
29 | %%%===================================================================
30 | %%% API functions
31 | %%%===================================================================
32 |
33 | %%--------------------------------------------------------------------
34 | %% @doc
35 | %% Starts the supervisor
36 | %%
37 | %% @end
38 | %%--------------------------------------------------------------------
39 | -spec(start_link() ->
40 | {ok, Pid :: pid()} | ignore | {error, Reason :: term()}).
41 | start_link() ->
42 | supervisor:start_link({local, ?SERVER}, ?MODULE, []).
43 |
44 | %%%===================================================================
45 | %%% Supervisor callbacks
46 | %%%===================================================================
47 |
48 | %%--------------------------------------------------------------------
49 | %% @private
50 | %% @doc
51 | %% Whenever a supervisor is started using supervisor:start_link/[2,3],
52 | %% this function is called by the new process to find out about
53 | %% restart strategy, maximum restart frequency and child
54 | %% specifications.
55 | %%
56 | %% @end
57 | %%--------------------------------------------------------------------
58 | -spec(init(Args :: term()) ->
59 | {ok, {SupFlags :: {RestartStrategy :: supervisor:strategy(),
60 | MaxR :: non_neg_integer(), MaxT :: non_neg_integer()},
61 | [ChildSpec :: supervisor:child_spec()]
62 | }} |
63 | ignore |
64 | {error, Reason :: term()}).
65 | init([]) ->
66 | RestartStrategy = simple_one_for_one,
67 | MaxRestarts = 1000,
68 | MaxSecondsBetweenRestarts = 3600,
69 |
70 | SupFlags = {RestartStrategy, MaxRestarts, MaxSecondsBetweenRestarts},
71 | Child = {dubbo_client_default, {dubbo_client_default, start_link, []}, permanent, 2000, worker, [dubbo_client_default]},
72 | {ok, {SupFlags, [Child]}}.
73 |
74 |
75 | add_children(ProvideConfig, Handler) ->
76 | supervisor:start_child(?SERVER, [ProvideConfig, Handler]).
77 |
78 | stop_children(ChildID) ->
79 | supervisor:terminate_child(?SERVER, ChildID).
80 | %%%===================================================================
81 | %%% Internal functions
82 | %%%===================================================================
83 |
--------------------------------------------------------------------------------
/src/dubbo_type_encoding.erl:
--------------------------------------------------------------------------------
1 | % ---------------------------------------------------------------------------
2 | % Copyright (C) 2008 0x6e6562
3 | %
4 | % Licensed under the Apache License, Version 2.0 (the "License");
5 | % you may not use this file except in compliance with the License.
6 | % You may obtain a copy of the License at
7 | %
8 | % http://www.apache.org/licenses/LICENSE-2.0
9 | %
10 | % Unless required by applicable law or agreed to in writing, software
11 | % distributed under the License is distributed on an "AS IS" BASIS,
12 | % WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | % See the License for the specific language governing permissions and
14 | % limitations under the License.
15 | % ---------------------------------------------------------------------------
16 |
17 | -module(dubbo_type_encoding).
18 |
19 | -include("hessian.hrl").
20 |
21 | %% The encoding state contains all of the statically known tuple types.
22 | %% When a tuple is to be encoded at run-time, a lookup is performed against
23 | %% the type tag. This must resolve to some type definition,
24 | %% otherwise no type information can be encoded into the output stream.
25 | -record(encoding_state, {pool = dict:new(), count = -1}).
26 |
27 | -export([init/0]).
28 | -export([enlist/1, enlist/2]).
29 | -export([visit/2]).
30 |
31 | %% Facility to register a particular type to the pool of known types.
32 | %% Adds the type to the pool of known types if it doesn't already exist.
33 | init() ->
34 | #encoding_state{}.
35 |
36 | enlist(TypeDef) -> enlist(TypeDef, #encoding_state{}).
37 | enlist(TypeDef = #type_def{native_type = Key},
38 | State = #encoding_state{pool = OldPool}) ->
39 | case dict:is_key(Key, OldPool) of
40 | true ->
41 | State;
42 | false ->
43 | NewPool = dict:store(Key, {-1, TypeDef}, OldPool),
44 | State#encoding_state{pool = NewPool}
45 | end.
46 |
47 | %% Facility to record the fact that an instance of a type is about to be
48 | %% encoded into the stream. This needs to decide whether the hash of the
49 | %% type def has already been written or not.
50 | %%
51 | %% If not, a reference to this needs to be generated for future instances
52 | %% and the hash value of the type def needs to be written out.
53 | %%
54 | %% If it already has been written out, it must be back-referenced.
55 | visit(NativeType, State = #encoding_state{pool = Pool}) ->
56 | logger:debug("[encode] visit ~p", [NativeType]),
57 | case dict:find(NativeType, Pool) of
58 | {ok, {-1, TypeDef}} ->
59 | %% The type needs hashing and it's reference needs updating
60 | {Ref, NewTypeDef, NewState} = assign_reference(TypeDef, State),
61 | %% Hash = erlang:phash2(TypeDef),
62 | %%%%%%%%%%%%%%%%%%%%%%%%%%
63 | %% LOOK INTO THIS DEPENDENCY, MAYBE EXTRACT IT OUT
64 | %% type_decoding:hash_store(NewTypeDef,NewState), %% 貌似这个没用,可以去掉.
65 | %%%%%%%%%%%%%%%%%%%%%%%%%%
66 | {hash, Ref, NewTypeDef, NewState};
67 | {ok, {Ref, _TypeDef}} ->
68 | {ref, Ref};
69 | error ->
70 | case get_deftype_public_pool(NativeType) of
71 | undefined ->
72 | throw("unkonw native type " ++ atom_to_list(NativeType));
73 | TypeDefTmp ->
74 | State2 = enlist(TypeDefTmp, State),
75 | visit(NativeType, State2)
76 | end
77 | end.
78 |
79 | %% This increments the reference count for the current scope and updates the
80 | %% reference in the pool of known types
81 | assign_reference(TypeDef = #type_def{native_type = Key},
82 | #encoding_state{pool = OldPool, count = Count}) ->
83 | NewCount = Count + 1,
84 | NewTypeDef = TypeDef#type_def{defineNo = NewCount},
85 | Value = {NewCount, NewTypeDef},
86 | NewPool = dict:store(Key, Value, OldPool),
87 | logger:debug("[encode] assign_reference type ~p definedNo ~p", [Key, NewCount]),
88 | {NewCount, NewTypeDef, #encoding_state{pool = NewPool, count = NewCount}}.
89 |
90 | get_deftype_public_pool(NativeType) ->
91 | dubbo_type_register:lookup_native_type(NativeType).
--------------------------------------------------------------------------------
/src/dubbo_type_register.erl:
--------------------------------------------------------------------------------
1 | % ---------------------------------------------------------------------------
2 | % Copyright (C) 2008 0x6e6562
3 | %
4 | % Licensed under the Apache License, Version 2.0 (the "License");
5 | % you may not use this file except in compliance with the License.
6 | % You may obtain a copy of the License at
7 | %
8 | % http://www.apache.org/licenses/LICENSE-2.0
9 | %
10 | % Unless required by applicable law or agreed to in writing, software
11 | % distributed under the License is distributed on an "AS IS" BASIS,
12 | % WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | % See the License for the specific language governing permissions and
14 | % limitations under the License.
15 | % ---------------------------------------------------------------------------
16 |
17 | -module(dubbo_type_register).
18 | %% API
19 | -export([init/0, regiest_foreign_native/1, lookup_foreign_type/1, lookup_native_type/1]).
20 | -include("hessian.hrl").
21 | -define(FOREIGN_NATIVE_TABLE, foreign_native_table).
22 | -define(NATIVE_FOREIGN_TABLE, native_foreign_table).
23 |
24 | init() ->
25 | case ets:info(?FOREIGN_NATIVE_TABLE) of
26 | undefined ->
27 | ?FOREIGN_NATIVE_TABLE = ets:new(?FOREIGN_NATIVE_TABLE, [public, named_table]),
28 | logger:info("init decoding foreign_native_table table", []);
29 | _ ->
30 | ets:delete(?FOREIGN_NATIVE_TABLE),
31 | ?FOREIGN_NATIVE_TABLE = ets:new(?FOREIGN_NATIVE_TABLE, [public, named_table])
32 | end,
33 | case ets:info(?NATIVE_FOREIGN_TABLE) of
34 | undefined ->
35 | ?NATIVE_FOREIGN_TABLE = ets:new(?NATIVE_FOREIGN_TABLE, [public, named_table]); %% public
36 | _ ->
37 | ets:delete(?NATIVE_FOREIGN_TABLE),
38 | ?NATIVE_FOREIGN_TABLE = ets:new(?NATIVE_FOREIGN_TABLE, [public, named_table])
39 | end,
40 | ok.
41 |
42 |
43 | regiest_foreign_native(TypeDef) ->
44 | logger:debug("regiest foreign info ~p", [TypeDef]),
45 | ets:insert(?FOREIGN_NATIVE_TABLE, {TypeDef#type_def.foreign_type, TypeDef}),
46 | ets:insert(?NATIVE_FOREIGN_TABLE, {TypeDef#type_def.native_type, TypeDef}).
47 |
48 |
49 | lookup_foreign_type(ForeignType) ->
50 | case ets:lookup(?FOREIGN_NATIVE_TABLE, ForeignType) of
51 | [] ->
52 | undefined;
53 | [{_, TypeDef}] ->
54 | TypeDef
55 | end.
56 |
57 | lookup_native_type(NativeType) ->
58 | case ets:lookup(?NATIVE_FOREIGN_TABLE, NativeType) of
59 | [] ->
60 | undefined;
61 | [{_, TypeDef}] ->
62 | TypeDef
63 | end.
--------------------------------------------------------------------------------
/src/dubbo_type_transfer.erl:
--------------------------------------------------------------------------------
1 | %%------------------------------------------------------------------------------
2 | %% Licensed to the Apache Software Foundation (ASF) under one or more
3 | %% contributor license agreements. See the NOTICE file distributed with
4 | %% this work for additional information regarding copyright ownership.
5 | %% The ASF licenses this file to You under the Apache License, Version 2.0
6 | %% (the "License"); you may not use this file except in compliance with
7 | %% the License. You may obtain a copy of the License at
8 | %%
9 | %% http://www.apache.org/licenses/LICENSE-2.0
10 | %%
11 | %% Unless required by applicable law or agreed to in writing, software
12 | %% distributed under the License is distributed on an "AS IS" BASIS,
13 | %% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 | %% See the License for the specific language governing permissions and
15 | %% limitations under the License.
16 | %%------------------------------------------------------------------------------
17 | -module(dubbo_type_transfer).
18 | -include("hessian.hrl").
19 | -include("dubbo.hrl").
20 |
21 | %% API
22 | -export([java_to_native/2, pre_process_typedef/3, response_to_native/1, classobj_to_native/2, jsonobj_to_native/3]).
23 |
24 |
25 | response_to_native(Response) ->
26 | java_to_native(Response#dubbo_response.data, Response#dubbo_response.decode_state).
27 |
28 |
29 | classobj_to_native(Data, DecodeState) ->
30 | java_to_native(Data, DecodeState).
31 |
32 | java_to_native(#object{values = ForeignData} = Data, State) ->
33 | ForeignDataNew = [java_to_native(ValueItem, State) || ValueItem <- ForeignData],
34 |
35 | case cotton_hessian:get_deftype(Data#object.typeRef, State) of
36 | #type_def{fieldnames = ObjectFields, foreign_type = ForeignType} ->
37 | case get_deftype(ForeignType) of
38 | false ->
39 | error;
40 | #type_def{fieldnames = NativeFields, native_type = NativeTupeName} ->
41 | AsDict = dict:from_list(lists:zip(ObjectFields, ForeignDataNew)),
42 | NativeData = [dict:fetch(atom_to_binary(Key, utf8), AsDict) || Key <- NativeFields],
43 | list_to_tuple([NativeTupeName] ++ NativeData)
44 | end;
45 | Info ->
46 | logger:warning("java_to_native error:~p", [Info]),
47 | error
48 | end;
49 | java_to_native(#list{values = ForeignData} = Data, State) ->
50 | ForeignDataNew = [java_to_native(ValueItem, State) || ValueItem <- ForeignData],
51 | ForeignDataNew;
52 | java_to_native(Data, _) ->
53 | Data.
54 |
55 | get_deftype(ForeignType) ->
56 |
57 | case dubbo_type_register:lookup_foreign_type(ForeignType) of
58 | undefined ->
59 | logger:debug("get deftype undefined ~p", [ForeignType]),
60 | false;
61 | #type_def{} = TypeDef ->
62 | logger:debug("get deftype success ~p", [ForeignType]),
63 | TypeDef;
64 | _ ->
65 | logger:debug("get deftype undefined ~p", [ForeignType]),
66 | false
67 | end.
68 |
69 | pre_process_typedef(NativeType, ForeignType, FieldsNames) ->
70 | Type = #type_def{native_type = NativeType, foreign_type = ForeignType, fieldnames = FieldsNames},
71 | dubbo_type_register:regiest_foreign_native(Type),
72 | logger:debug("pre_process_typedef ~p,~p", [NativeType, ForeignType]),
73 | ok.
74 |
75 |
76 | jsonobj_to_native(Type, JsonObj, State) ->
77 | ClassName = java_desc_name_to_dot(Type),
78 | %% todo need recursion transfer
79 | case dubbo_type_register:lookup_foreign_type(ClassName) of
80 | undefined ->
81 | JsonObj;
82 | #type_def{fieldnames = Fields, native_type = NativeType} ->
83 | logger:debug("jsonobj_to_native ~p ~p ~p", [ClassName, Fields, JsonObj]),
84 | NativeData = [maps:get(atom_to_binary(Key, utf8), JsonObj, undefined) || Key <- Fields],
85 | list_to_tuple([NativeType] ++ NativeData)
86 | end.
87 |
88 |
89 |
90 | java_desc_name_to_dot(DescName) ->
91 | case DescName of
92 | <<$L, ClassName/binary>> ->
93 | binary:replace(ClassName, <<"/">>, <<".">>, [global]);
94 | _ ->
95 | DescName
96 | end.
97 |
98 |
--------------------------------------------------------------------------------
/src/dubboerl.app.src:
--------------------------------------------------------------------------------
1 | {application, dubboerl,
2 | [{description, "An OTP application"},
3 | {vsn, "0.3.0"},
4 | {registered, []},
5 | {mod, {dubboerl_app, []}},
6 | {applications,
7 | [kernel,
8 | stdlib, xmerl, ranch, erlzk, poolboy, inets
9 | ]},
10 | {env, []},
11 | {modules, []},
12 |
13 | {maintainers, []},
14 | {licenses, []},
15 | {links, [{"Github", "https://github.com/dubboerl/dubboerl"}]}
16 | ]}.
17 |
--------------------------------------------------------------------------------
/src/dubboerl.erl:
--------------------------------------------------------------------------------
1 | %%------------------------------------------------------------------------------
2 | %% Licensed to the Apache Software Foundation (ASF) under one or more
3 | %% contributor license agreements. See the NOTICE file distributed with
4 | %% this work for additional information regarding copyright ownership.
5 | %% The ASF licenses this file to You under the Apache License, Version 2.0
6 | %% (the "License"); you may not use this file except in compliance with
7 | %% the License. You may obtain a copy of the License at
8 | %%
9 | %% http://www.apache.org/licenses/LICENSE-2.0
10 | %%
11 | %% Unless required by applicable law or agreed to in writing, software
12 | %% distributed under the License is distributed on an "AS IS" BASIS,
13 | %% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 | %% See the License for the specific language governing permissions and
15 | %% limitations under the License.
16 | %%------------------------------------------------------------------------------
17 | -module(dubboerl).
18 |
19 | -include("dubboerl.hrl").
20 | -include("dubbo.hrl").
21 |
22 | %% API
23 | -export([init/0, start_consumer/0, start_provider/0]).
24 |
25 | init() ->
26 | ok = start_consumer(),
27 | ok = start_provider(),
28 | ok.
29 |
30 |
31 | start_consumer() ->
32 | ConsumerList = application:get_env(dubboerl, consumer, []),
33 | ApplicationName = application:get_env(dubboerl, application, <<"defaultApplication">>),
34 | lists:map(fun({Interface, Option}) ->
35 | ConsumerInfo = dubbo_config_util:gen_consumer(ApplicationName, Interface, Option),
36 | dubbo_reference_config:init_reference(ConsumerInfo),
37 | logger:info("consumer refer success ~p", [Interface])
38 | end, ConsumerList),
39 | ok.
40 |
41 | start_provider() ->
42 | ProviderList = application:get_env(dubboerl, provider, []),
43 | ApplicationName = application:get_env(dubboerl, application, <<"defaultApplication">>),
44 | DubboServerPort = application:get_env(dubboerl, port, ?DUBBO_DEFAULT_PORT),
45 |
46 | lists:map(
47 | fun({ImplModuleName, BehaviourModuleName, Interface, Option}) ->
48 | MethodList = apply(BehaviourModuleName, get_method_999_list, []),
49 | ProviderInfo = dubbo_config_util:gen_provider(ApplicationName, DubboServerPort, Interface, MethodList, ImplModuleName, Option),
50 | dubbo_service_config:export(ProviderInfo),
51 | logger:info("register provider success ~p ~p", [ImplModuleName, Interface])
52 | end, ProviderList),
53 | ok.
54 |
55 |
56 |
57 |
--------------------------------------------------------------------------------
/src/dubboerl_app.erl:
--------------------------------------------------------------------------------
1 | %%------------------------------------------------------------------------------
2 | %% Licensed to the Apache Software Foundation (ASF) under one or more
3 | %% contributor license agreements. See the NOTICE file distributed with
4 | %% this work for additional information regarding copyright ownership.
5 | %% The ASF licenses this file to You under the Apache License, Version 2.0
6 | %% (the "License"); you may not use this file except in compliance with
7 | %% the License. You may obtain a copy of the License at
8 | %%
9 | %% http://www.apache.org/licenses/LICENSE-2.0
10 | %%
11 | %% Unless required by applicable law or agreed to in writing, software
12 | %% distributed under the License is distributed on an "AS IS" BASIS,
13 | %% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 | %% See the License for the specific language governing permissions and
15 | %% limitations under the License.
16 | %%------------------------------------------------------------------------------
17 | -module(dubboerl_app).
18 |
19 | -behaviour(application).
20 |
21 | -include("dubboerl.hrl").
22 | %% Application callbacks
23 | -export([start/2, stop/1, env_init/0]).
24 |
25 | %%====================================================================
26 | %% API
27 | %%====================================================================
28 |
29 | start(_StartType, _StartArgs) ->
30 | logger:info("[START] dubbo framework server start"),
31 | case dubboerl_sup:start_link() of
32 | {ok, Pid} ->
33 | init_default_hooks(),
34 | {ok, Pid};
35 | Result ->
36 | Result
37 | end.
38 |
39 | %%--------------------------------------------------------------------
40 | stop(_State) ->
41 | ok.
42 |
43 | %%====================================================================
44 | %% Internal functions
45 | %%====================================================================
46 | init_default_hooks() ->
47 | dubbo_extension:register(protocol, dubbo_protocol_dubbo, 10),
48 | dubbo_extension:register(protocol_wapper, dubbo_protocol_registry, 10),
49 | dubbo_extension:register(filter, application:get_env(dubboerl, cluster, dubbo_cluster_failfast), 1),
50 | init_filter_hooks(),
51 | ok.
52 |
53 | init_filter_hooks() ->
54 | FilterList = application:get_env(dubboerl, filter, []),
55 | lists:mapfoldl(
56 | fun(Filter,Acc) ->
57 | dubbo_extension:register(filter, Filter, Acc),
58 | Acc +1
59 | end,100,FilterList
60 | ),
61 | ok.
62 |
63 | env_init() ->
64 | ets:new(?PROVIDER_IMPL_TABLE, [public, named_table]),
65 | ets:new(?SERVICE_EXPORT_TABLE, [public, named_table]),
66 | dubbo_traffic_control:init(),
67 | dubbo_type_register:init(),
68 | register_type_list().
69 |
70 |
71 | register_type_list() ->
72 | List = dubbo_java_type_defined:get_list(),
73 | lists:map(
74 | fun({NativeType, ForeignType, Fields}) ->
75 | dubbo_type_transfer:pre_process_typedef(NativeType, ForeignType, Fields)
76 | end, List),
77 | ok.
--------------------------------------------------------------------------------
/src/dubboerl_sup.erl:
--------------------------------------------------------------------------------
1 | %%------------------------------------------------------------------------------
2 | %% Licensed to the Apache Software Foundation (ASF) under one or more
3 | %% contributor license agreements. See the NOTICE file distributed with
4 | %% this work for additional information regarding copyright ownership.
5 | %% The ASF licenses this file to You under the Apache License, Version 2.0
6 | %% (the "License"); you may not use this file except in compliance with
7 | %% the License. You may obtain a copy of the License at
8 | %%
9 | %% http://www.apache.org/licenses/LICENSE-2.0
10 | %%
11 | %% Unless required by applicable law or agreed to in writing, software
12 | %% distributed under the License is distributed on an "AS IS" BASIS,
13 | %% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 | %% See the License for the specific language governing permissions and
15 | %% limitations under the License.
16 | %%------------------------------------------------------------------------------
17 | -module(dubboerl_sup).
18 |
19 | -behaviour(supervisor).
20 |
21 | -include("common.hrl").
22 | %% API
23 | -export([start_link/0]).
24 |
25 | %% Supervisor callbacks
26 | -export([init/1]).
27 |
28 | -define(SERVER, ?MODULE).
29 |
30 | %%====================================================================
31 | %% API functions
32 | %%====================================================================
33 |
34 | start_link() ->
35 | supervisor:start_link({local, ?SERVER}, ?MODULE, []).
36 |
37 | %%====================================================================
38 | %% Supervisor callbacks
39 | %%====================================================================
40 |
41 | %% Child :: {Id,StartFunc,Restart,Shutdown,Type,Modules}
42 | init([]) ->
43 | dubboerl_app:env_init(),
44 | RegistrySup = {dubbo_registry_sup, {dubbo_registry_sup, start_link, []}, transient, 5000, supervisor, [dubbo_registry_sup]},
45 | ExtensionSer = {dubbo_extension, {dubbo_extension, start_link, []}, transient, 5000, worker, [dubbo_extension]},
46 | Id_count = {dubbo_id_generator, {dubbo_id_generator, start_link, []}, transient, 5000, worker, [dubbo_id_generator]},
47 | ProviderPoolSup = {dubbo_provider_worker_sup, {dubbo_provider_worker_sup, start_link, []}, transient, 5000, supervisor, [dubbo_provider_worker_sup]},
48 | ConsumerPoolSup = {dubbo_transport_pool_sup, {dubbo_transport_pool_sup, start_link, []}, transient, 5000, supervisor, [dubbo_transport_pool_sup]},
49 | ConsumerPool = {dubbo_provider_consumer_reg_table, {dubbo_provider_consumer_reg_table, start_link, []}, transient, 5000, worker, [dubbo_provider_consumer_reg_table]},
50 | ShutdownSer = {dubbo_shutdown, {dubbo_shutdown, start_link, []}, transient, 10000, worker, [dubbo_shutdown]},
51 |
52 | ListNew = [Id_count, ExtensionSer, RegistrySup, ConsumerPool, ConsumerPoolSup, ProviderPoolSup, ShutdownSer],
53 | {ok, {{one_for_one, 60, 10}, ListNew}}.
54 |
55 | %%====================================================================
56 | %% Internal functions
57 | %%====================================================================
58 |
--------------------------------------------------------------------------------
/test/de_codec_tests.erl:
--------------------------------------------------------------------------------
1 | %%------------------------------------------------------------------------------
2 | %% Licensed to the Apache Software Foundation (ASF) under one or more
3 | %% contributor license agreements. See the NOTICE file distributed with
4 | %% this work for additional information regarding copyright ownership.
5 | %% The ASF licenses this file to You under the Apache License, Version 2.0
6 | %% (the "License"); you may not use this file except in compliance with
7 | %% the License. You may obtain a copy of the License at
8 | %%
9 | %% http://www.apache.org/licenses/LICENSE-2.0
10 | %%
11 | %% Unless required by applicable law or agreed to in writing, software
12 | %% distributed under the License is distributed on an "AS IS" BASIS,
13 | %% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 | %% See the License for the specific language governing permissions and
15 | %% limitations under the License.
16 | %%------------------------------------------------------------------------------
17 | -module(de_codec_tests).
18 | -include_lib("eunit/include/eunit.hrl").
19 | -include("dubbo.hrl").
20 |
21 | -record(databaseOperateRequest, {
22 | param}).
23 |
24 |
25 | simple_test() ->
26 | ?assert(true).
27 |
--------------------------------------------------------------------------------
/test/dubbo_adapter_tests.erl:
--------------------------------------------------------------------------------
1 | %%------------------------------------------------------------------------------
2 | %% Licensed to the Apache Software Foundation (ASF) under one or more
3 | %% contributor license agreements. See the NOTICE file distributed with
4 | %% this work for additional information regarding copyright ownership.
5 | %% The ASF licenses this file to You under the Apache License, Version 2.0
6 | %% (the "License"); you may not use this file except in compliance with
7 | %% the License. You may obtain a copy of the License at
8 | %%
9 | %% http://www.apache.org/licenses/LICENSE-2.0
10 | %%
11 | %% Unless required by applicable law or agreed to in writing, software
12 | %% distributed under the License is distributed on an "AS IS" BASIS,
13 | %% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 | %% See the License for the specific language governing permissions and
15 | %% limitations under the License.
16 | %%------------------------------------------------------------------------------
17 | -module(dubbo_adapter_tests).
18 | -include("dubbo.hrl").
19 | -include_lib("eunit/include/eunit.hrl").
20 |
21 | reference_test() ->
22 | dubbo_id_generator:start_link(),
23 | Invocation = #dubbo_rpc_invocation{
24 | className = <<"testname">>,
25 | classVersion = <<"testversion">>,
26 | methodName = <<"getUserInfo">>,
27 | parameterDesc = <<"Ljava/lang/String;"/utf8>>,
28 | parameterTypes = [
29 | #type_def{foreign_type = <<"java.lang.String">>,
30 | native_type = string,
31 | fieldnames = []}
32 | ],
33 | parameters = [
34 | <<"test">>
35 | ],
36 | attachments = [
37 | {<<"path">>, <<"testname">>},
38 | {<<"interface">>, <<"testname">>}
39 | ]
40 | },
41 | Request = dubbo_adapter:reference(Invocation),
42 | ?assert(is_record(Request, dubbo_request)).
43 |
--------------------------------------------------------------------------------
/test/dubbo_common_fun_tests.erl:
--------------------------------------------------------------------------------
1 | %%------------------------------------------------------------------------------
2 | %% Licensed to the Apache Software Foundation (ASF) under one or more
3 | %% contributor license agreements. See the NOTICE file distributed with
4 | %% this work for additional information regarding copyright ownership.
5 | %% The ASF licenses this file to You under the Apache License, Version 2.0
6 | %% (the "License"); you may not use this file except in compliance with
7 | %% the License. You may obtain a copy of the License at
8 | %%
9 | %% http://www.apache.org/licenses/LICENSE-2.0
10 | %%
11 | %% Unless required by applicable law or agreed to in writing, software
12 | %% distributed under the License is distributed on an "AS IS" BASIS,
13 | %% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 | %% See the License for the specific language governing permissions and
15 | %% limitations under the License.
16 | %%------------------------------------------------------------------------------
17 | -module(dubbo_common_fun_tests).
18 | -include_lib("eunit/include/eunit.hrl").
19 |
20 | request_gen_test() ->
21 | dubbo_id_generator:init([]),
22 | Id = dubbo_id_generator:gen_id(),
23 | ?assert(is_integer(Id)).
24 |
25 | string_join_test() ->
26 | Result1 = dubbo_lists_util:join([<<"a">>, <<"b">>], <<",">>),
27 | ?assertEqual(Result1, <<"a,b">>),
28 |
29 | Result2 = dubbo_lists_util:join([], <<",">>),
30 | ?assertEqual(Result2, <<"">>),
31 |
32 | Result3 = dubbo_lists_util:join([<<"a">>, "b", ttt], <<",">>),
33 | ?assertEqual(Result3, <<"a,b">>),
34 | ok.
35 |
36 | list_dup_test() ->
37 | R = dubbo_lists_util:del_duplicate([a, b, a]),
38 | ?assertEqual(length(R), 2).
39 |
40 |
41 | ip_v4_test()->
42 | Result = dubbo_network_tools:local_ipv4(),
43 | ?assertEqual(true,is_list(Result)).
--------------------------------------------------------------------------------
/test/dubbo_config_parser_tests.erl:
--------------------------------------------------------------------------------
1 | %%------------------------------------------------------------------------------
2 | %% Licensed to the Apache Software Foundation (ASF) under one or more
3 | %% contributor license agreements. See the NOTICE file distributed with
4 | %% this work for additional information regarding copyright ownership.
5 | %% The ASF licenses this file to You under the Apache License, Version 2.0
6 | %% (the "License"); you may not use this file except in compliance with
7 | %% the License. You may obtain a copy of the License at
8 | %%
9 | %% http://www.apache.org/licenses/LICENSE-2.0
10 | %%
11 | %% Unless required by applicable law or agreed to in writing, software
12 | %% distributed under the License is distributed on an "AS IS" BASIS,
13 | %% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 | %% See the License for the specific language governing permissions and
15 | %% limitations under the License.
16 | %%------------------------------------------------------------------------------
17 | -module(dubbo_config_parser_tests).
18 | -include_lib("eunit/include/eunit.hrl").
19 | -include("dubbo.hrl").
20 |
21 | gen_provice_config_test() ->
22 | ProviderConfigInfo = dubbo_config_util:gen_provider(<<"defaultApp">>, 20880, <<"org.apache.dubbo.test.interface">>, [method1], dubbo_service_user_impl, []),
23 | ProvideNode = dubbo_node_config_util:gen_provider_info(ProviderConfigInfo),
24 | ?assert(is_binary(ProvideNode)).
25 |
26 |
27 | provider_parse_test() ->
28 | {ok, ProviderUrlInfo} = dubbo_common_fun:parse_url(<<"dubbo://127.0.0.1:20880/org.apache.dubbo.test.interface?interface=org.apache.dubbo.test.interface&application=defaultApp&anyhost=true&dubbo=2.5.3&executes=10&methods=method1&side=provider×tamp=1556095933071">>),
29 | {ok, ProviderConfig} = dubbo_node_config_util:parse_provider_info(ProviderUrlInfo),
30 | ?assertEqual(ProviderConfig#provider_config.protocol, <<"dubbo">>),
31 | ?assertEqual(ProviderConfig#provider_config.host, <<"127.0.0.1">>),
32 | ?assertEqual(ProviderConfig#provider_config.port, 20880),
33 | ?assertEqual(ProviderConfig#provider_config.interface, <<"org.apache.dubbo.test.interface">>),
34 | ?assert(true).
35 |
36 |
--------------------------------------------------------------------------------
/test/dubbo_consumer_pool_tests.erl:
--------------------------------------------------------------------------------
1 | %%------------------------------------------------------------------------------
2 | %% Licensed to the Apache Software Foundation (ASF) under one or more
3 | %% contributor license agreements. See the NOTICE file distributed with
4 | %% this work for additional information regarding copyright ownership.
5 | %% The ASF licenses this file to You under the Apache License, Version 2.0
6 | %% (the "License"); you may not use this file except in compliance with
7 | %% the License. You may obtain a copy of the License at
8 | %%
9 | %% http://www.apache.org/licenses/LICENSE-2.0
10 | %%
11 | %% Unless required by applicable law or agreed to in writing, software
12 | %% distributed under the License is distributed on an "AS IS" BASIS,
13 | %% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 | %% See the License for the specific language governing permissions and
15 | %% limitations under the License.
16 | %%------------------------------------------------------------------------------
17 | -module(dubbo_consumer_pool_tests).
18 |
19 | -include_lib("eunit/include/eunit.hrl").
20 | -include("dubbo.hrl").
21 |
22 | update_readonly_test() ->
23 | dubbo_provider_consumer_reg_table:start_link(),
24 | InterfaceName= <<"testinterfacename">>,
25 | HostFalg= <<"127.0.0.1/20880">>,
26 | ConnectionList = [
27 | #connection_info{pid= testpid,weight = 30,host_flag = HostFalg},
28 | #connection_info{pid= testpid2,weight = 30,host_flag = HostFalg}
29 | ],
30 | dubbo_provider_consumer_reg_table:update_connection_info(InterfaceName,HostFalg,ConnectionList,true),
31 | {ok,Size} = dubbo_provider_consumer_reg_table:update_connection_readonly(testpid,false),
32 | ?assertEqual(1,Size).
33 |
--------------------------------------------------------------------------------
/test/dubbo_extension_tests.erl:
--------------------------------------------------------------------------------
1 | %%------------------------------------------------------------------------------
2 | %% Licensed to the Apache Software Foundation (ASF) under one or more
3 | %% contributor license agreements. See the NOTICE file distributed with
4 | %% this work for additional information regarding copyright ownership.
5 | %% The ASF licenses this file to You under the Apache License, Version 2.0
6 | %% (the "License"); you may not use this file except in compliance with
7 | %% the License. You may obtain a copy of the License at
8 | %%
9 | %% http://www.apache.org/licenses/LICENSE-2.0
10 | %%
11 | %% Unless required by applicable law or agreed to in writing, software
12 | %% distributed under the License is distributed on an "AS IS" BASIS,
13 | %% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 | %% See the License for the specific language governing permissions and
15 | %% limitations under the License.
16 | %%------------------------------------------------------------------------------
17 | -module(dubbo_extension_tests).
18 |
19 |
20 | -include_lib("eunit/include/eunit.hrl").
21 | -include("dubbo.hrl").
22 |
23 | invoker_test()->
24 | {ok,_Pid} = dubbo_extension:start_link(),
25 |
26 | ok = dubbo_extension:register(filter, dubbo_filter_test1, 100),
27 | Invocation = #dubbo_rpc_invocation{},
28 | Ref = make_ref(),
29 | {ok,Ref} = dubbo_extension:invoke(filter, invoke, [Invocation], {ok, Ref}, []),
30 | ok.
31 |
32 | %%on_response_test() ->
33 |
34 |
35 |
36 |
--------------------------------------------------------------------------------
/test/dubbo_filter_test1.erl:
--------------------------------------------------------------------------------
1 | %%------------------------------------------------------------------------------
2 | %% Licensed to the Apache Software Foundation (ASF) under one or more
3 | %% contributor license agreements. See the NOTICE file distributed with
4 | %% this work for additional information regarding copyright ownership.
5 | %% The ASF licenses this file to You under the Apache License, Version 2.0
6 | %% (the "License"); you may not use this file except in compliance with
7 | %% the License. You may obtain a copy of the License at
8 | %%
9 | %% http://www.apache.org/licenses/LICENSE-2.0
10 | %%
11 | %% Unless required by applicable law or agreed to in writing, software
12 | %% distributed under the License is distributed on an "AS IS" BASIS,
13 | %% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 | %% See the License for the specific language governing permissions and
15 | %% limitations under the License.
16 | %%------------------------------------------------------------------------------
17 | -module(dubbo_filter_test1).
18 | -behaviour(dubbo_filter).
19 |
20 | %% API
21 | -export([invoke/2, on_response/2]).
22 |
23 | invoke(Invocation, Acc) ->
24 | io:format(user,"test filter invoke sucess~n",[]),
25 | {ok, Invocation, Acc}.
26 |
27 | on_response(Invocation, Result) ->
28 | io:format(user,"test filter on_response sucess~n",[]),
29 | {ok, Invocation, Result}.
--------------------------------------------------------------------------------
/test/dubbo_heartbeat_tests.erl:
--------------------------------------------------------------------------------
1 | %%------------------------------------------------------------------------------
2 | %% Licensed to the Apache Software Foundation (ASF) under one or more
3 | %% contributor license agreements. See the NOTICE file distributed with
4 | %% this work for additional information regarding copyright ownership.
5 | %% The ASF licenses this file to You under the Apache License, Version 2.0
6 | %% (the "License"); you may not use this file except in compliance with
7 | %% the License. You may obtain a copy of the License at
8 | %%
9 | %% http://www.apache.org/licenses/LICENSE-2.0
10 | %%
11 | %% Unless required by applicable law or agreed to in writing, software
12 | %% distributed under the License is distributed on an "AS IS" BASIS,
13 | %% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 | %% See the License for the specific language governing permissions and
15 | %% limitations under the License.
16 | %%------------------------------------------------------------------------------
17 | -module(dubbo_heartbeat_tests).
18 | -include_lib("eunit/include/eunit.hrl").
19 |
20 | heartbeat1_test() ->
21 | dubbo_id_generator:start_link(),
22 | {ok, Data} = dubbo_heartbeat:generate_request(undefined, false),
23 | ?assert(is_binary(Data)).
24 |
25 | simple_test() ->
26 | ?assert(true).
27 |
--------------------------------------------------------------------------------
/test/dubbo_sample_service.hrl:
--------------------------------------------------------------------------------
1 |
2 | -record(userInfoRequest,{
3 | requestId ::list(),
4 | username ::list()}).
5 |
6 | -record(userRes,{
7 | userlist ::[]}).
8 |
9 | -record(userInfo,{
10 | userName ::list(),
11 | userAge ::integer(),
12 | userId ::list()}).
13 |
14 |
--------------------------------------------------------------------------------
/test/dubbo_sample_service_app.erl:
--------------------------------------------------------------------------------
1 | %%%-------------------------------------------------------------------
2 | %% @doc dubbo_sample_service public API
3 | %% @end
4 | %%%-------------------------------------------------------------------
5 |
6 | -module(dubbo_sample_service_app).
7 |
8 | -behaviour(application).
9 |
10 | %% Application callbacks
11 | -export([start/2, stop/1]).
12 |
13 | -include("dubbo_sample_service.hrl").
14 | -export([register_type_list/0]).
15 |
16 | %%====================================================================
17 | %% API
18 | %%====================================================================
19 |
20 | start(_StartType, _StartArgs) ->
21 | register_type_list(),
22 | dubbo_sample_service_sup:start_link().
23 |
24 | %%--------------------------------------------------------------------
25 | stop(_State) ->
26 | ok.
27 |
28 | %%====================================================================
29 | %% Internal functions
30 | %%====================================================================
31 |
32 |
33 | register_type_list()->
34 | List = dubbo_sample_service_type_list:get_list(),
35 | lists:map(
36 | fun({NativeType,ForeignType,Fields}) ->
37 | dubbo_type_transfer:pre_process_typedef(NativeType,ForeignType,Fields)
38 | end,List),
39 | ok.
--------------------------------------------------------------------------------
/test/dubbo_sample_service_sup.erl:
--------------------------------------------------------------------------------
1 | %%%-------------------------------------------------------------------
2 | %% @doc dubbo_sample_service top level supervisor.
3 | %% @end
4 | %%%-------------------------------------------------------------------
5 |
6 | -module(dubbo_sample_service_sup).
7 |
8 | -behaviour(supervisor).
9 |
10 | %% API
11 | -export([start_link/0]).
12 |
13 | %% Supervisor callbacks
14 | -export([init/1]).
15 |
16 | -define(SERVER, ?MODULE).
17 |
18 | %%====================================================================
19 | %% API functions
20 | %%====================================================================
21 |
22 | start_link() ->
23 | supervisor:start_link({local, ?SERVER}, ?MODULE, []).
24 |
25 | %%====================================================================
26 | %% Supervisor callbacks
27 | %%====================================================================
28 |
29 | %% Child :: {Id,StartFunc,Restart,Shutdown,Type,Modules}
30 | init([]) ->
31 | {ok, { {one_for_all, 0, 1}, []} }.
32 |
33 | %%====================================================================
34 | %% Internal functions
35 | %%====================================================================
36 |
--------------------------------------------------------------------------------
/test/dubbo_sample_service_type_list.erl:
--------------------------------------------------------------------------------
1 | -module(dubbo_sample_service_type_list).
2 |
3 | %% API
4 | -export([register_type_list/0,get_list/0]).
5 |
6 | -include("dubbo_sample_service.hrl").
7 |
8 | get_list()->
9 | [
10 | {userInfoRequest,<<"org.apache.dubbo.erlang.sample.service.bean.UserInfoRequest">>,record_info(fields,userInfoRequest)},
11 | {userRes,<<"org.apache.dubbo.erlang.sample.service.bean.UserRes">>,record_info(fields,userRes)},
12 | {userInfo,<<"org.apache.dubbo.erlang.sample.service.bean.UserInfo">>,record_info(fields,userInfo)} ].
13 |
14 | register_type_list()->
15 | ok.
--------------------------------------------------------------------------------
/test/dubbo_service_config_SUITE.erl:
--------------------------------------------------------------------------------
1 | %%------------------------------------------------------------------------------
2 | %% Licensed to the Apache Software Foundation (ASF) under one or more
3 | %% contributor license agreements. See the NOTICE file distributed with
4 | %% this work for additional information regarding copyright ownership.
5 | %% The ASF licenses this file to You under the Apache License, Version 2.0
6 | %% (the "License"); you may not use this file except in compliance with
7 | %% the License. You may obtain a copy of the License at
8 | %%
9 | %% http://www.apache.org/licenses/LICENSE-2.0
10 | %%
11 | %% Unless required by applicable law or agreed to in writing, software
12 | %% distributed under the License is distributed on an "AS IS" BASIS,
13 | %% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 | %% See the License for the specific language governing permissions and
15 | %% limitations under the License.
16 | %%------------------------------------------------------------------------------
17 | -module(dubbo_service_config_SUITE).
18 |
19 | -compile(export_all).
20 |
21 | suite() ->
22 | [{timetrap, {seconds, 60}}].
23 |
24 |
25 |
26 | init_per_suite(Config) ->
27 | logger:add_handler(testttt, logger_std_h, #{
28 | level => all
29 | }),
30 | Start = application:ensure_all_started(dubboerl),
31 | %% dubboerl:init(),
32 | io:format(user, "test case start dubboerl info ~p~n", [Start]),
33 | [].
34 |
35 | %%--------------------------------------------------------------------
36 | %% Function: end_per_suite(Config0) -> term() | {save_config,Config1}
37 | %% Config0 = Config1 = [tuple()]
38 | %%--------------------------------------------------------------------
39 | end_per_suite(_Config) ->
40 | application:stop(dubboerl),
41 | timer:sleep(1000),
42 | ok.
43 |
44 | %%--------------------------------------------------------------------
45 | %% Function: init_per_group(GroupName, Config0) ->
46 | %% Config1 | {skip,Reason} | {skip_and_save,Reason,Config1}
47 | %% GroupName = atom()
48 | %% Config0 = Config1 = [tuple()]
49 | %% Reason = term()
50 | %%--------------------------------------------------------------------
51 | init_per_group(_GroupName, Config) ->
52 | Config.
53 |
54 | %%--------------------------------------------------------------------
55 | %% Function: end_per_group(GroupName, Config0) ->
56 | %% term() | {save_config,Config1}
57 | %% GroupName = atom()
58 | %% Config0 = Config1 = [tuple()]
59 | %%--------------------------------------------------------------------
60 | end_per_group(_GroupName, _Config) ->
61 | ok.
62 |
63 | %%--------------------------------------------------------------------
64 | %% Function: init_per_testcase(TestCase, Config0) ->
65 | %% Config1 | {skip,Reason} | {skip_and_save,Reason,Config1}
66 | %% TestCase = atom()
67 | %% Config0 = Config1 = [tuple()]
68 | %% Reason = term()
69 | %%--------------------------------------------------------------------
70 | init_per_testcase(_TestCase, Config) ->
71 | Config.
72 |
73 | %%--------------------------------------------------------------------
74 | %% Function: end_per_testcase(TestCase, Config0) ->
75 | %% term() | {save_config,Config1} | {fail,Reason}
76 | %% TestCase = atom()
77 | %% Config0 = Config1 = [tuple()]
78 | %% Reason = term()
79 | %%--------------------------------------------------------------------
80 | end_per_testcase(_TestCase, _Config) ->
81 | ok.
82 |
83 | %%--------------------------------------------------------------------
84 | %% Function: groups() -> [Group]
85 | %% Group = {GroupName,Properties,GroupsAndTestCases}
86 | %% GroupName = atom()
87 | %% Properties = [parallel | sequence | Shuffle | {RepeatType,N}]
88 | %% GroupsAndTestCases = [Group | {group,GroupName} | TestCase]
89 | %% TestCase = atom()
90 | %% Shuffle = shuffle | {shuffle,{integer(),integer(),integer()}}
91 | %% RepeatType = repeat | repeat_until_all_ok | repeat_until_all_fail |
92 | %% repeat_until_any_ok | repeat_until_any_fail
93 | %% N = integer() | forever
94 | %%--------------------------------------------------------------------
95 | groups() ->
96 | [
97 | {service_test, [sequence], [export_interface]}
98 | ].
99 |
100 | %%--------------------------------------------------------------------
101 | %% Function: all() -> GroupsAndTestCases | {skip,Reason}
102 | %% GroupsAndTestCases = [{group,GroupName} | TestCase]
103 | %% GroupName = atom()
104 | %% TestCase = atom()
105 | %% Reason = term()
106 | %%--------------------------------------------------------------------
107 | all() ->
108 | [{group, service_test}].
109 |
110 |
111 | export_interface(_Config) ->
112 | MethodList = apply(userOperator, get_method_999_list, []),
113 | ProviderInfo = dubbo_config_util:gen_provider(<<"test-application">>, 20880, <<"org.apache.dubbo.erlang.sample.service.facade.UserOperator">>, MethodList, dubbo_service_user_impl, []),
114 | dubbo_service_config:export(ProviderInfo),
115 | ok.
--------------------------------------------------------------------------------
/test/dubbo_service_user_impl.erl:
--------------------------------------------------------------------------------
1 | %%------------------------------------------------------------------------------
2 | %% Licensed to the Apache Software Foundation (ASF) under one or more
3 | %% contributor license agreements. See the NOTICE file distributed with
4 | %% this work for additional information regarding copyright ownership.
5 | %% The ASF licenses this file to You under the Apache License, Version 2.0
6 | %% (the "License"); you may not use this file except in compliance with
7 | %% the License. You may obtain a copy of the License at
8 | %%
9 | %% http://www.apache.org/licenses/LICENSE-2.0
10 | %%
11 | %% Unless required by applicable law or agreed to in writing, software
12 | %% distributed under the License is distributed on an "AS IS" BASIS,
13 | %% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 | %% See the License for the specific language governing permissions and
15 | %% limitations under the License.
16 | %%------------------------------------------------------------------------------
17 | -module(dubbo_service_user_impl).
18 |
19 |
20 | -behaviour(userOperator).
21 |
22 | -include_lib("dubbo_sample_service.hrl").
23 | -include_lib("dubboerl/include/hessian.hrl").
24 | -include_lib("dubboerl/include/dubbo.hrl").
25 | %% API
26 | -export([getUserInfo/1, queryUserList/1, genUserId/0, queryUserInfo/1]).
27 |
28 | genUserId() ->
29 | "newid".
30 |
31 | getUserInfo(Args) ->
32 | io:format(user, "do invokeWs ~p", [Args]),
33 | #userInfo{userAge = 88, userName = "one", userId = "id123"}.
34 |
35 | queryUserList(Args) ->
36 | User = #userInfo{userAge = 88, userName = "two", userId = "id123"},
37 | List = #list{len = 1, type = "java.util.ArrayList", values = [User]},
38 |
39 | Res = #userRes{
40 | userlist = List
41 | },
42 | Res.
43 |
44 |
45 | queryUserInfo(Arg0) ->
46 | io:format(user, "do invoker queryUserInfo ~p", [Arg0]),
47 | #userInfo{userName = "uuname", userAge = 10, userId = "44"}.
--------------------------------------------------------------------------------
/test/dubbo_traffic_control_tests.erl:
--------------------------------------------------------------------------------
1 | %%------------------------------------------------------------------------------
2 | %% Licensed to the Apache Software Foundation (ASF) under one or more
3 | %% contributor license agreements. See the NOTICE file distributed with
4 | %% this work for additional information regarding copyright ownership.
5 | %% The ASF licenses this file to You under the Apache License, Version 2.0
6 | %% (the "License"); you may not use this file except in compliance with
7 | %% the License. You may obtain a copy of the License at
8 | %%
9 | %% http://www.apache.org/licenses/LICENSE-2.0
10 | %%
11 | %% Unless required by applicable law or agreed to in writing, software
12 | %% distributed under the License is distributed on an "AS IS" BASIS,
13 | %% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 | %% See the License for the specific language governing permissions and
15 | %% limitations under the License.
16 | %%------------------------------------------------------------------------------
17 | -module(dubbo_traffic_control_tests).
18 | -include_lib("eunit/include/eunit.hrl").
19 |
20 | init_test() ->
21 | dubbo_traffic_control:init(),
22 | dubbo_traffic_control:init(),
23 | ?assert(true).
24 |
25 | goon_test() ->
26 | dubbo_traffic_control:init(),
27 | ?assertEqual(dubbo_traffic_control:check_goon(key1, 2), ok),
28 | ?assertEqual(dubbo_traffic_control:check_goon(key1, 2), ok),
29 | ?assertEqual(dubbo_traffic_control:check_goon(key1, 2), full),
30 | ?assertEqual(dubbo_traffic_control:check_goon(key1, 2), full),
31 | ?assertEqual(dubbo_traffic_control:decr_count(key1), ok),
32 | ok.
33 |
--------------------------------------------------------------------------------
/test/hessian_encode_tests.erl:
--------------------------------------------------------------------------------
1 | %%------------------------------------------------------------------------------
2 | %% Licensed to the Apache Software Foundation (ASF) under one or more
3 | %% contributor license agreements. See the NOTICE file distributed with
4 | %% this work for additional information regarding copyright ownership.
5 | %% The ASF licenses this file to You under the Apache License, Version 2.0
6 | %% (the "License"); you may not use this file except in compliance with
7 | %% the License. You may obtain a copy of the License at
8 | %%
9 | %% http://www.apache.org/licenses/LICENSE-2.0
10 | %%
11 | %% Unless required by applicable law or agreed to in writing, software
12 | %% distributed under the License is distributed on an "AS IS" BASIS,
13 | %% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 | %% See the License for the specific language governing permissions and
15 | %% limitations under the License.
16 | %%------------------------------------------------------------------------------
17 | -module(hessian_encode_tests).
18 | -include("hessian.hrl").
19 | -include_lib("eunit/include/eunit.hrl").
20 | %% API
21 | -export([object_test/0]).
22 |
23 | -record(de_TestReq, {name, nick, age}).
24 | -record(de_reg2, {reqinfo, age}).
25 |
26 | object_test() ->
27 | ForeignTypeA = <<"com.ifcoder.demo.bean.UserInfoRequest">>,
28 | TypeDefA = #type_def{foreign_type = ForeignTypeA,
29 | native_type = de_TestReq,
30 | fieldnames = record_info(fields, de_TestReq)},
31 | EncodingState0 = dubbo_type_encoding:enlist(TypeDefA),
32 | RequestArg0 = #de_TestReq{name = <<"nameinfo">>, nick = <<"nickname">>, age = 10},
33 |
34 | {Bin, State0} = cotton_hessian:encode(RequestArg0, EncodingState0),
35 |
36 | dubbo_type_register:init(),
37 | dubbo_type_transfer:pre_process_typedef(de_TestReq, <<"com.ifcoder.demo.bean.UserInfoRequest">>, record_info(fields, de_TestReq)),
38 | {<<>>, Data, State2} = cotton_hessian:decode(Bin, cotton_hessian:init()),
39 | DecodeResult = dubbo_type_transfer:java_to_native(Data, State2),
40 | ?assert(is_record(DecodeResult, de_TestReq)),
41 | ?assertEqual(DecodeResult#de_TestReq.name, <<"nameinfo">>),
42 | ?assertEqual(DecodeResult#de_TestReq.nick, <<"nickname">>),
43 | ?assertEqual(DecodeResult#de_TestReq.age, 10),
44 | ?debugFmt("get decode info ~p", [DecodeResult]),
45 | ok.
46 |
--------------------------------------------------------------------------------
/tools/erlanalysis/.gitignore:
--------------------------------------------------------------------------------
1 | _*
2 | .eunit
3 | *.o
4 | *.beam
5 | *.plt
6 | *.swp
7 | *.swo
8 | .erlang.cookie
9 | ebin
10 | log
11 | erl_crash.dump
12 | .rebar
13 | logs
14 | _build
15 | .idea
16 | .rebar
17 | target
18 | genProjectDir
19 | mavenDown
20 | *.log
21 |
--------------------------------------------------------------------------------
/tools/erlanalysis/README.md:
--------------------------------------------------------------------------------
1 | # erlanalysis
2 | parse dubbo interface to erlang lib
3 |
4 | ## Usage
5 |
6 | ### Step1
7 | mvn pacakge -Dmaven.skip.test=true
8 |
9 | ### Steps2
10 | ```
11 | java -jar target/erlanalysis-1.0.jar groupId artifactId version
12 | ## example:
13 | ## java -jar target/erlanalysis-1.0.jar org.apache.dubbo.erlang dubbo-sample-service 1.3
14 | ```
--------------------------------------------------------------------------------
/tools/erlanalysis/pom.xml:
--------------------------------------------------------------------------------
1 |
3 | 4.0.0
4 |
5 | org.apache.dubbo.erlang
6 | erlanalysis
7 | 1.0
8 | jar
9 |
10 | erlanalysis
11 | https://github.com/apache/incubator-dubbo-erlang
12 |
13 | UTF-8
14 |
15 |
16 |
17 |
18 | junit
19 | junit
20 | 3.8.1
21 | test
22 |
23 |
24 | com.caucho
25 | hessian
26 | 3.1.5
27 |
28 |
29 |
30 | org.slf4j
31 | slf4j-log4j12
32 | 1.7.25
33 |
34 |
35 | org.slf4j
36 | slf4j-api
37 | 1.7.25
38 |
39 |
40 | org.apache.maven.shared
41 | maven-invoker
42 | 2.2
43 |
44 |
45 | log4j
46 | log4j
47 | 1.2.16
48 |
49 |
50 | org.ow2.asm
51 | asm-all
52 | 5.2
53 |
54 |
55 |
56 | org.apache.velocity
57 | velocity
58 | 1.7
59 |
60 |
61 |
62 |
63 |
64 |
65 | org.apache.maven.plugins
66 | maven-compiler-plugin
67 |
68 | 8
69 | 8
70 |
71 |
72 |
73 | maven-assembly-plugin
74 |
75 | false
76 |
77 | jar-with-dependencies
78 |
79 |
80 |
81 | org.apache.dubbo.erlang.analysis.Start
82 |
83 |
84 |
85 |
86 |
87 | make-assembly
88 | package
89 |
90 | assembly
91 |
92 |
93 |
94 |
95 |
96 |
97 |
98 |
--------------------------------------------------------------------------------
/tools/erlanalysis/src/main/java/org/apache/dubbo/erlang/analysis/App.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Licensed to the Apache Software Foundation (ASF) under one or more
3 | * contributor license agreements. See the NOTICE file distributed with
4 | * this work for additional information regarding copyright ownership.
5 | * The ASF licenses this file to You under the Apache License, Version 2.0
6 | * (the "License"); you may not use this file except in compliance with
7 | * the License. You may obtain a copy of the License at
8 | *
9 | * http://www.apache.org/licenses/LICENSE-2.0
10 | *
11 | * Unless required by applicable law or agreed to in writing, software
12 | * distributed under the License is distributed on an "AS IS" BASIS,
13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 | * See the License for the specific language governing permissions and
15 | * limitations under the License.
16 | */
17 |
18 | package org.apache.dubbo.erlang.analysis;
19 |
20 | import com.caucho.hessian.io.HessianInput;
21 | import com.caucho.hessian.io.HessianOutput;
22 | import org.apache.dubbo.erlang.analysis.parse.InterfaceParse;
23 | import org.apache.dubbo.erlang.analysis.erltool.UserInfo;
24 |
25 | import java.io.*;
26 |
27 | import static java.lang.System.exit;
28 |
29 | public class App {
30 | public static void writesome() throws IOException {
31 | UserInfo user = new UserInfo();
32 | user.setAge(10);
33 | user.setUsername("userabc");
34 | user.setPassword("password");
35 |
36 | ByteArrayOutputStream os = new ByteArrayOutputStream();
37 | HessianOutput ho = new HessianOutput(os);
38 | ho.writeObject(user);
39 |
40 | FileOutputStream out = new FileOutputStream("/tmp/hessian.data");
41 | out.write(os.toByteArray());
42 | out.flush();
43 | out.close();
44 |
45 | }
46 |
47 | public static void readsome() throws IOException {
48 | FileInputStream input = new FileInputStream("/tmp/hessianw.data");
49 | byte[] buffer = new byte[input.available()];
50 | input.read(buffer);
51 |
52 | ByteArrayInputStream is = new ByteArrayInputStream(buffer);
53 | HessianInput hi = new HessianInput(is);
54 | Object obj = hi.readObject();
55 | System.out.println("obj:" + obj);
56 | UserInfo user = (UserInfo) obj;
57 | System.out.println("user:" + user);
58 | }
59 |
60 | public static void main(String[] args) {
61 | if (args.length < 3) {
62 | System.out.println("please input args: group artifactid version");
63 | exit(1);
64 | }
65 | String group = args[0];
66 | String artifactid = args[1];
67 | String version = args[2];
68 | System.out.println("will parse facade " + group + ":" + artifactid + ":" + version);
69 | InterfaceParse parser = new InterfaceParse();
70 | parser.parse(group, artifactid, version);
71 | //
72 | // try {
73 | //// readsome();
74 | // writesome();
75 | // } catch (IOException e) {
76 | // e.printStackTrace();
77 | // }
78 | // System.out.println( "Hello World!" );
79 | }
80 | }
81 |
--------------------------------------------------------------------------------
/tools/erlanalysis/src/main/java/org/apache/dubbo/erlang/analysis/Start.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Licensed to the Apache Software Foundation (ASF) under one or more
3 | * contributor license agreements. See the NOTICE file distributed with
4 | * this work for additional information regarding copyright ownership.
5 | * The ASF licenses this file to You under the Apache License, Version 2.0
6 | * (the "License"); you may not use this file except in compliance with
7 | * the License. You may obtain a copy of the License at
8 | *
9 | * http://www.apache.org/licenses/LICENSE-2.0
10 | *
11 | * Unless required by applicable law or agreed to in writing, software
12 | * distributed under the License is distributed on an "AS IS" BASIS,
13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 | * See the License for the specific language governing permissions and
15 | * limitations under the License.
16 | */
17 |
18 | package org.apache.dubbo.erlang.analysis;
19 |
20 | import org.apache.dubbo.erlang.analysis.parse.InterfaceParse;
21 |
22 | public class Start {
23 |
24 |
25 | public static void main(String[] args) {
26 | if (args.length < 3) {
27 | System.out.println("please input groupId artifactId version");
28 | return;
29 | }
30 | String groupId = args[0];
31 | String artifactId = args[1];
32 | String version = args[2];
33 | InterfaceParse parser = new InterfaceParse();
34 | parser.parse(groupId, artifactId, version);
35 | }
36 | }
37 |
--------------------------------------------------------------------------------
/tools/erlanalysis/src/main/java/org/apache/dubbo/erlang/analysis/erltool/UserInfo.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Licensed to the Apache Software Foundation (ASF) under one or more
3 | * contributor license agreements. See the NOTICE file distributed with
4 | * this work for additional information regarding copyright ownership.
5 | * The ASF licenses this file to You under the Apache License, Version 2.0
6 | * (the "License"); you may not use this file except in compliance with
7 | * the License. You may obtain a copy of the License at
8 | *
9 | * http://www.apache.org/licenses/LICENSE-2.0
10 | *
11 | * Unless required by applicable law or agreed to in writing, software
12 | * distributed under the License is distributed on an "AS IS" BASIS,
13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 | * See the License for the specific language governing permissions and
15 | * limitations under the License.
16 | */
17 |
18 | package org.apache.dubbo.erlang.analysis.erltool;
19 |
20 | import java.io.Serializable;
21 |
22 | public class UserInfo implements Serializable {
23 | private String username;
24 | private Integer age;
25 | private String password;
26 |
27 | public UserInfo() {
28 |
29 | }
30 |
31 | public String getUsername() {
32 | return username;
33 | }
34 |
35 | public void setUsername(String username) {
36 | this.username = username;
37 | }
38 |
39 | public Integer getAge() {
40 | return age;
41 | }
42 |
43 | public void setAge(Integer age) {
44 | this.age = age;
45 | }
46 |
47 | public String getPassword() {
48 | return password;
49 | }
50 |
51 | public void setPassword(String password) {
52 | this.password = password;
53 | }
54 | }
55 |
--------------------------------------------------------------------------------
/tools/erlanalysis/src/main/java/org/apache/dubbo/erlang/analysis/generater/ProjectInfo.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Licensed to the Apache Software Foundation (ASF) under one or more
3 | * contributor license agreements. See the NOTICE file distributed with
4 | * this work for additional information regarding copyright ownership.
5 | * The ASF licenses this file to You under the Apache License, Version 2.0
6 | * (the "License"); you may not use this file except in compliance with
7 | * the License. You may obtain a copy of the License at
8 | *
9 | * http://www.apache.org/licenses/LICENSE-2.0
10 | *
11 | * Unless required by applicable law or agreed to in writing, software
12 | * distributed under the License is distributed on an "AS IS" BASIS,
13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 | * See the License for the specific language governing permissions and
15 | * limitations under the License.
16 | */
17 |
18 | package org.apache.dubbo.erlang.analysis.generater;
19 |
20 | public class ProjectInfo {
21 | private String appName;
22 | private String appVersion;
23 | private String prefix;
24 |
25 | public String getAppName() {
26 | return appName.replace("-", "_");
27 | }
28 |
29 | public void setAppName(String appName) {
30 | this.appName = appName.replace("-", "_");
31 | }
32 |
33 | public String getPrefix() {
34 | return prefix;
35 | }
36 |
37 | public void setPrefix(String prefix) {
38 | this.prefix = prefix;
39 | }
40 |
41 | public String getAppVersion() {
42 | return appVersion;
43 | }
44 |
45 | public void setAppVersion(String appVersion) {
46 | this.appVersion = appVersion;
47 | }
48 | }
49 |
--------------------------------------------------------------------------------
/tools/erlanalysis/src/main/java/org/apache/dubbo/erlang/analysis/parse/CommonTypeFieldInfo.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Licensed to the Apache Software Foundation (ASF) under one or more
3 | * contributor license agreements. See the NOTICE file distributed with
4 | * this work for additional information regarding copyright ownership.
5 | * The ASF licenses this file to You under the Apache License, Version 2.0
6 | * (the "License"); you may not use this file except in compliance with
7 | * the License. You may obtain a copy of the License at
8 | *
9 | * http://www.apache.org/licenses/LICENSE-2.0
10 | *
11 | * Unless required by applicable law or agreed to in writing, software
12 | * distributed under the License is distributed on an "AS IS" BASIS,
13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 | * See the License for the specific language governing permissions and
15 | * limitations under the License.
16 | */
17 |
18 | package org.apache.dubbo.erlang.analysis.parse;
19 |
20 | import org.apache.dubbo.erlang.analysis.utils.ErlTypeTransformUtil;
21 |
22 | public class CommonTypeFieldInfo {
23 | private String fieldName;
24 | private Class> fieldType;
25 |
26 | public String getFieldName() {
27 | return ErlTypeTransformUtil.stringFirstToLower(fieldName);
28 | }
29 |
30 | public void setFieldName(String fieldName) {
31 | this.fieldName = fieldName;
32 | }
33 |
34 | public Class> getFieldType() {
35 | return fieldType;
36 | }
37 |
38 | public void setFieldType(Class> fieldType) {
39 | this.fieldType = fieldType;
40 | }
41 |
42 | public String getFieldErlType() {
43 | return ErlTypeTransformUtil.fullClassNameToErlType(fieldType.getName());
44 | }
45 | }
46 |
--------------------------------------------------------------------------------
/tools/erlanalysis/src/main/java/org/apache/dubbo/erlang/analysis/parse/CommonTypeItem.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Licensed to the Apache Software Foundation (ASF) under one or more
3 | * contributor license agreements. See the NOTICE file distributed with
4 | * this work for additional information regarding copyright ownership.
5 | * The ASF licenses this file to You under the Apache License, Version 2.0
6 | * (the "License"); you may not use this file except in compliance with
7 | * the License. You may obtain a copy of the License at
8 | *
9 | * http://www.apache.org/licenses/LICENSE-2.0
10 | *
11 | * Unless required by applicable law or agreed to in writing, software
12 | * distributed under the License is distributed on an "AS IS" BASIS,
13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 | * See the License for the specific language governing permissions and
15 | * limitations under the License.
16 | */
17 |
18 | package org.apache.dubbo.erlang.analysis.parse;
19 |
20 | import org.apache.dubbo.erlang.analysis.utils.ErlTypeTransformUtil;
21 |
22 | import java.util.HashSet;
23 | import java.util.Set;
24 |
25 | public class CommonTypeItem {
26 | private String className;
27 | private Set fields = new HashSet();
28 |
29 | public String getClassName() {
30 | return className;
31 | }
32 |
33 | public void setClassName(String className) {
34 | this.className = className;
35 | }
36 |
37 | public Set getFields() {
38 | return fields;
39 | }
40 |
41 | public void setFields(Set fields) {
42 | this.fields = fields;
43 | }
44 |
45 | public void addField(CommonTypeFieldInfo field) {
46 | fields.add(field);
47 | }
48 |
49 | /**
50 | * 获取类型名称
51 | *
52 | * @return
53 | */
54 | public String getTypeName() {
55 | return ErlTypeTransformUtil.fullClassNameToLowerShortName(className);
56 | }
57 |
58 | public CommonTypeFieldInfo[] getFieldList() {
59 | CommonTypeFieldInfo[] ret = new CommonTypeFieldInfo[fields.size()];
60 | fields.toArray(ret);
61 | return ret;
62 | }
63 | }
64 |
--------------------------------------------------------------------------------
/tools/erlanalysis/src/main/java/org/apache/dubbo/erlang/analysis/parse/InterfaceInfo.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Licensed to the Apache Software Foundation (ASF) under one or more
3 | * contributor license agreements. See the NOTICE file distributed with
4 | * this work for additional information regarding copyright ownership.
5 | * The ASF licenses this file to You under the Apache License, Version 2.0
6 | * (the "License"); you may not use this file except in compliance with
7 | * the License. You may obtain a copy of the License at
8 | *
9 | * http://www.apache.org/licenses/LICENSE-2.0
10 | *
11 | * Unless required by applicable law or agreed to in writing, software
12 | * distributed under the License is distributed on an "AS IS" BASIS,
13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 | * See the License for the specific language governing permissions and
15 | * limitations under the License.
16 | */
17 |
18 | package org.apache.dubbo.erlang.analysis.parse;
19 |
20 | import java.util.ArrayList;
21 | import java.util.List;
22 |
23 | public class InterfaceInfo {
24 | private String interfaceName;
25 | private List methods = new ArrayList();
26 |
27 | public String getInterfaceName() {
28 | return interfaceName;
29 | }
30 |
31 | public String getModuleName() {
32 | String moduleName = interfaceName.substring(interfaceName.lastIndexOf(".") + 1);
33 | moduleName = moduleName.substring(0, 1).toLowerCase() + moduleName.substring(1);
34 | moduleName = moduleName.replace('-', '_');
35 | return moduleName;
36 | }
37 |
38 | public void setInterfaceName(String interfaceName) {
39 | this.interfaceName = interfaceName;
40 | }
41 |
42 |
43 | public List getMethods() {
44 | return methods;
45 | }
46 |
47 | public void getMethodExportList() {
48 |
49 | }
50 |
51 | public void addMethods(MethodInfo method) {
52 | this.methods.add(method);
53 | }
54 | }
55 |
--------------------------------------------------------------------------------
/tools/erlanalysis/src/main/java/org/apache/dubbo/erlang/analysis/parse/InterfaceParse.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Licensed to the Apache Software Foundation (ASF) under one or more
3 | * contributor license agreements. See the NOTICE file distributed with
4 | * this work for additional information regarding copyright ownership.
5 | * The ASF licenses this file to You under the Apache License, Version 2.0
6 | * (the "License"); you may not use this file except in compliance with
7 | * the License. You may obtain a copy of the License at
8 | *
9 | * http://www.apache.org/licenses/LICENSE-2.0
10 | *
11 | * Unless required by applicable law or agreed to in writing, software
12 | * distributed under the License is distributed on an "AS IS" BASIS,
13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 | * See the License for the specific language governing permissions and
15 | * limitations under the License.
16 | */
17 |
18 | package org.apache.dubbo.erlang.analysis.parse;
19 |
20 | import org.apache.dubbo.erlang.analysis.generater.ErlProjectGenerater;
21 | import org.apache.dubbo.erlang.analysis.generater.ProjectInfo;
22 | import org.apache.dubbo.erlang.analysis.utils.MavenJarUtil;
23 | import org.slf4j.Logger;
24 | import org.slf4j.LoggerFactory;
25 |
26 | import java.io.File;
27 |
28 | import java.net.MalformedURLException;
29 | import java.net.URL;
30 | import java.net.URLClassLoader;
31 | import java.util.ArrayList;
32 | import java.util.List;
33 |
34 | public class InterfaceParse {
35 | private final static Logger logger = LoggerFactory.getLogger(InterfaceParse.class);
36 |
37 | public void parse(String group, String artifactid, String version) {
38 |
39 |
40 | MavenJarUtil mavenInfo = new MavenJarUtil(group, artifactid, version);
41 | if (!mavenInfo.copyDependence()) {
42 | logger.error("download maven jar error");
43 | }
44 | String parserJarPath = mavenInfo.getMainJarPath();
45 | logger.info("parse main jar " + parserJarPath);
46 | loadDependencyJar(mavenInfo.getRootDir() + File.separator + "lib");
47 | ParseJarInterfaceInfo parser = new ParseJarInterfaceInfo();
48 | List interfaceList = parser.parseJar(parserJarPath);
49 |
50 | ProjectInfo projectInfo = new ProjectInfo();
51 | projectInfo.setAppName(mavenInfo.getArtifactId());
52 | projectInfo.setAppVersion(mavenInfo.getVersion());
53 | projectInfo.setPrefix("test_");
54 |
55 | ErlProjectGenerater generater = new ErlProjectGenerater(projectInfo);
56 | generater.genProject(interfaceList);
57 | }
58 |
59 |
60 | private boolean loadDependencyJar(String rootPath) {
61 | File jarPathFile = new File(rootPath);
62 | if (!jarPathFile.exists() || jarPathFile.isFile()) {
63 | logger.error("load dependency error target dir unexist {}", rootPath);
64 | return false;
65 | }
66 | List urlList = new ArrayList();
67 | File[] fileList = jarPathFile.listFiles();
68 | for (int i = 0; i < fileList.length; i++) {
69 | File item = fileList[i];
70 | if (item.isDirectory()) {
71 | continue;
72 | }
73 | try {
74 | if (item.getAbsolutePath().endsWith(".jar")) {
75 | urlList.add(item.toURI().toURL());
76 | logger.debug("url class load add lib {}", item.getAbsolutePath());
77 | }
78 | } catch (MalformedURLException e) {
79 | logger.error("get jar list error ", e);
80 | }
81 | }
82 |
83 | URL[] urls = new URL[urlList.size()];
84 | urlList.toArray(urls);
85 | URLClassLoader cl = new URLClassLoader(urls, Thread.currentThread().getContextClassLoader());
86 | Thread.currentThread().setContextClassLoader(cl);
87 | return true;
88 | }
89 |
90 |
91 | }
92 |
--------------------------------------------------------------------------------
/tools/erlanalysis/src/main/java/org/apache/dubbo/erlang/analysis/parse/MethodInfo.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Licensed to the Apache Software Foundation (ASF) under one or more
3 | * contributor license agreements. See the NOTICE file distributed with
4 | * this work for additional information regarding copyright ownership.
5 | * The ASF licenses this file to You under the Apache License, Version 2.0
6 | * (the "License"); you may not use this file except in compliance with
7 | * the License. You may obtain a copy of the License at
8 | *
9 | * http://www.apache.org/licenses/LICENSE-2.0
10 | *
11 | * Unless required by applicable law or agreed to in writing, software
12 | * distributed under the License is distributed on an "AS IS" BASIS,
13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 | * See the License for the specific language governing permissions and
15 | * limitations under the License.
16 | */
17 |
18 | package org.apache.dubbo.erlang.analysis.parse;
19 |
20 |
21 | import org.apache.dubbo.erlang.analysis.utils.ErlTypeTransformUtil;
22 | import org.objectweb.asm.Type;
23 |
24 | import java.util.*;
25 |
26 | public class MethodInfo {
27 | private String name;
28 |
29 | private String methodDescriptor;
30 | private String argsType;
31 | private int argsLength;
32 | private String returnType;
33 | private String[] parameterName;
34 |
35 | public String getName() {
36 | return name;
37 | }
38 |
39 | public void setName(String name) {
40 | this.name = name;
41 | }
42 |
43 | public String getArgsType() {
44 | return argsType;
45 | }
46 |
47 | public void setArgsType(String argsType) {
48 | this.argsType = argsType;
49 | }
50 |
51 | public String getReturnType() {
52 | return returnType;
53 | }
54 |
55 | public void setReturnType(String returnType) {
56 | this.returnType = returnType;
57 | }
58 |
59 |
60 | public String getParameterNameString() {
61 | return String.join(",", parameterName);
62 | }
63 |
64 | public void setParameterName(String[] parameterName) {
65 | for (int i = 0; i < parameterName.length; i++) {
66 | parameterName[i] = parameterName[i].substring(0, 1).toUpperCase() + parameterName[i].substring(1);
67 | }
68 | this.parameterName = parameterName;
69 | }
70 |
71 | public String getParameterTypeDef() {
72 | ArrayList retList = new ArrayList<>();
73 | Type[] types = Type.getArgumentTypes(methodDescriptor);
74 | for (int i = 0; i < types.length; i++) {
75 | String def = ErlTypeTransformUtil.fullClassNameToTypeDef(types[i].getClassName());
76 | retList.add(def);
77 | }
78 | return String.join(",\n", retList);
79 | }
80 |
81 | public Map getParameterTypeList() {
82 | Type[] types = Type.getArgumentTypes(methodDescriptor);
83 | Map retInfo = new LinkedHashMap<>();
84 | for (int i = 0; i < types.length; i++) {
85 | String def = ErlTypeTransformUtil.fullClassNameToErlType(types[i].getClassName());
86 | retInfo.put(parameterName[i], def);
87 | }
88 | return retInfo;
89 | }
90 |
91 | /**
92 | * get -spec return type
93 | *
94 | * @return
95 | */
96 | public String getReturnErlType() {
97 | Type types = Type.getReturnType(methodDescriptor);
98 | return ErlTypeTransformUtil.fullClassNameToErlType(types.getClassName());
99 | }
100 |
101 | public String getResponseTypeDef() {
102 | Type types = Type.getReturnType(methodDescriptor);
103 | return ErlTypeTransformUtil.fullClassNameToTypeDef(types.getClassName());
104 | }
105 |
106 | public String getMethodDescriptor() {
107 | return methodDescriptor;
108 | }
109 |
110 | public void setMethodDescriptor(String methodDescriptor) {
111 | this.methodDescriptor = methodDescriptor;
112 | }
113 |
114 |
115 | public int getArgsLength() {
116 | return argsLength;
117 | }
118 |
119 | public void setArgsLength(int argsLength) {
120 | this.argsLength = argsLength;
121 | }
122 | }
123 |
--------------------------------------------------------------------------------
/tools/erlanalysis/src/main/java/org/apache/dubbo/erlang/analysis/utils/ErlTypeTransformUtil.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Licensed to the Apache Software Foundation (ASF) under one or more
3 | * contributor license agreements. See the NOTICE file distributed with
4 | * this work for additional information regarding copyright ownership.
5 | * The ASF licenses this file to You under the Apache License, Version 2.0
6 | * (the "License"); you may not use this file except in compliance with
7 | * the License. You may obtain a copy of the License at
8 | *
9 | * http://www.apache.org/licenses/LICENSE-2.0
10 | *
11 | * Unless required by applicable law or agreed to in writing, software
12 | * distributed under the License is distributed on an "AS IS" BASIS,
13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 | * See the License for the specific language governing permissions and
15 | * limitations under the License.
16 | */
17 |
18 | package org.apache.dubbo.erlang.analysis.utils;
19 |
20 | import java.util.List;
21 | import java.util.Map;
22 | import java.util.Set;
23 |
24 | public class ErlTypeTransformUtil {
25 |
26 | public static String fullClassNameToTypeDef(String fullClassName) {
27 | String className = fullClassName.substring(fullClassName.lastIndexOf(".") + 1);
28 | className = className.substring(0, 1).toLowerCase() + className.substring(1);
29 | String fieldNames = "";
30 | switch (className) {
31 | case "string":
32 | fieldNames = "[]";
33 | break;
34 | default:
35 | fieldNames = String.format("record_info(fields,%s)", className);
36 | }
37 | return String.format("#type_def{foreign_type = <<\"%s\">>,\n" +
38 | " native_type = %s,\n" +
39 | " fieldnames = %s}", fullClassName, className, fieldNames);
40 | }
41 |
42 | public static String fullClassNameToLowerShortName(String fullClassName) {
43 | String className = fullClassName.substring(fullClassName.lastIndexOf(".") + 1);
44 | className = className.substring(0, 1).toLowerCase() + className.substring(1);
45 | return className;
46 | }
47 |
48 | public static String stringFirstToLower(String str) {
49 | str = str.substring(0, 1).toLowerCase() + str.substring(1);
50 | return str;
51 | }
52 |
53 | public static String fullClassNameToErlType(String fullClassName) {
54 | try {
55 | String type = null;
56 | if (fullClassName.startsWith("java.lang") || fullClassName.equals("int") || fullClassName.equals("double") || fullClassName.equals("float")) {
57 | switch (fullClassName) {
58 | case "java.lang.String":
59 | type = "list()";
60 | break;
61 | case "java.lang.Integer":
62 | type = "integer()";
63 | break;
64 | case "java.lang.Boolean":
65 | type = "boolean()";
66 | break;
67 | case "java.lang.Float":
68 | type = "float()";
69 | break;
70 | case "int":
71 | type = "integer()";
72 | break;
73 | case "double":
74 | type = "float()";
75 | break;
76 | default:
77 | return "unkonw";
78 | }
79 |
80 | return type;
81 | }
82 | Class> classInfo = Class.forName(fullClassName, false, Thread.currentThread().getContextClassLoader());
83 |
84 | if (classInfo.isAssignableFrom(List.class)) {
85 | type = "[]";
86 | } else if (classInfo.isAssignableFrom(Map.class)) {
87 | type = "Map";
88 | } else if (classInfo.isAssignableFrom(Set.class)) {
89 | type = "Set";
90 | } else {
91 | type = "#" + fullClassNameToLowerShortName(fullClassName) + "{}";
92 | }
93 | return type;
94 | } catch (ClassNotFoundException e) {
95 | e.printStackTrace();
96 | }
97 | return null;
98 | }
99 | }
100 |
--------------------------------------------------------------------------------
/tools/erlanalysis/src/main/java/org/apache/dubbo/erlang/analysis/utils/MethodParseUtil.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Licensed to the Apache Software Foundation (ASF) under one or more
3 | * contributor license agreements. See the NOTICE file distributed with
4 | * this work for additional information regarding copyright ownership.
5 | * The ASF licenses this file to You under the Apache License, Version 2.0
6 | * (the "License"); you may not use this file except in compliance with
7 | * the License. You may obtain a copy of the License at
8 | *
9 | * http://www.apache.org/licenses/LICENSE-2.0
10 | *
11 | * Unless required by applicable law or agreed to in writing, software
12 | * distributed under the License is distributed on an "AS IS" BASIS,
13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 | * See the License for the specific language governing permissions and
15 | * limitations under the License.
16 | */
17 |
18 | package org.apache.dubbo.erlang.analysis.utils;
19 |
20 | import org.objectweb.asm.*;
21 |
22 |
23 | import java.io.IOException;
24 | import java.lang.reflect.Method;
25 | import java.lang.reflect.Modifier;
26 |
27 | public class MethodParseUtil {
28 | public static String[] getMethodParamNames(final Method method) throws IOException {
29 |
30 | final String methodName = method.getName();
31 | final Class>[] methodParameterTypes = method.getParameterTypes();
32 | final int methodParameterCount = methodParameterTypes.length;
33 | final String className = method.getDeclaringClass().getName();
34 | final boolean isStatic = Modifier.isStatic(method.getModifiers());
35 | final String[] methodParametersNames = new String[methodParameterCount];
36 |
37 | ClassReader cr = new ClassReader(Thread.currentThread().getContextClassLoader().getResourceAsStream(className.replace('.', '/') + ".class"));
38 | ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS);
39 | cr.accept(new ClassVisitor(Opcodes.ASM5, cw) {
40 | public MethodVisitor visitMethod(int access, String name, String desc, String signature, String[] exceptions) {
41 |
42 | MethodVisitor mv = super.visitMethod(access, name, desc, signature, exceptions);
43 |
44 | final Type[] argTypes = Type.getArgumentTypes(desc);
45 |
46 | //参数类型不一致
47 | if (!methodName.equals(name) || !matchTypes(argTypes, methodParameterTypes)) {
48 | return mv;
49 | }
50 |
51 | return new MethodVisitor(Opcodes.ASM5, mv) {
52 | public void visitLocalVariable(String name, String desc, String signature, Label start, Label end, int index) {
53 | //如果是静态方法,第一个参数就是方法参数,非静态方法,则第一个参数是 this ,然后才是方法的参数
54 | int methodParameterIndex = isStatic ? index : index - 1;
55 | if (0 <= methodParameterIndex && methodParameterIndex < methodParameterCount) {
56 | methodParametersNames[methodParameterIndex] = name;
57 | }
58 | super.visitLocalVariable(name, desc, signature, start, end, index);
59 | }
60 | };
61 | }
62 | }, 0);
63 | return methodParametersNames;
64 | }
65 |
66 | private static boolean matchTypes(Type[] types, Class>[] parameterTypes) {
67 | if (types.length != parameterTypes.length) {
68 | return false;
69 | }
70 | for (int i = 0; i < types.length; i++) {
71 | if (!Type.getType(parameterTypes[i]).equals(types[i])) {
72 | return false;
73 | }
74 | }
75 | return true;
76 | }
77 | }
78 |
--------------------------------------------------------------------------------
/tools/erlanalysis/src/main/resources/log4j.properties:
--------------------------------------------------------------------------------
1 | log4j.rootLogger=DEBUG,console
2 | log4j.appender.console=org.apache.log4j.ConsoleAppender
3 | log4j.appender.console.Threshold=DEBUG
4 | #log4j.appender.console.ImmediateFlush=true
5 | #log4j.appender.console.Target=System.err
6 | log4j.appender.console.layout=org.apache.log4j.PatternLayout
7 | log4j.appender.console.layout.ConversionPattern=%-d{yyyy-MM-dd HH\:mm\:ss} [%c]-[%p] %m%n
8 |
--------------------------------------------------------------------------------
/tools/erlanalysis/src/main/resources/templates/app.vm:
--------------------------------------------------------------------------------
1 | %%%-------------------------------------------------------------------
2 | %% @doc ${appName} public API
3 | %% @end
4 | %%%-------------------------------------------------------------------
5 |
6 | -module(${appName}_app).
7 |
8 | -behaviour(application).
9 |
10 | %% Application callbacks
11 | -export([start/2, stop/1]).
12 |
13 | -include("${appName}.hrl").
14 |
15 |
16 | %%====================================================================
17 | %% API
18 | %%====================================================================
19 |
20 | start(_StartType, _StartArgs) ->
21 | register_type_list(),
22 | ${appName}_sup:start_link().
23 |
24 | %%--------------------------------------------------------------------
25 | stop(_State) ->
26 | ok.
27 |
28 | %%====================================================================
29 | %% Internal functions
30 | %%====================================================================
31 |
32 |
33 | register_type_list()->
34 | List = ${appName}_type_list:get_list(),
35 | lists:map(
36 | fun({NativeType,ForeignType,Fields}) ->
37 | dubbo_type_transfer:pre_process_typedef(NativeType,ForeignType,Fields)
38 | end,List),
39 | ok.
--------------------------------------------------------------------------------
/tools/erlanalysis/src/main/resources/templates/app_src.vm:
--------------------------------------------------------------------------------
1 | {application, ${appName},
2 | [
3 | {description, "An OTP application"},
4 | {vsn, "${appVersion}"},
5 | {registered, []},
6 | {mod, { ${appName}_app, []}},
7 | {applications,
8 | [kernel,
9 | stdlib,
10 | dubboerl
11 | ]},
12 | {env,[]},
13 | {modules, []},
14 | {maintainers, []},
15 | {licenses, []},
16 | {links, []}
17 | ]}.
18 |
--------------------------------------------------------------------------------
/tools/erlanalysis/src/main/resources/templates/app_sup.vm:
--------------------------------------------------------------------------------
1 | %%%-------------------------------------------------------------------
2 | %% @doc ${appName} top level supervisor.
3 | %% @end
4 | %%%-------------------------------------------------------------------
5 |
6 | -module(${appName}_sup).
7 |
8 | -behaviour(supervisor).
9 |
10 | %% API
11 | -export([start_link/0]).
12 |
13 | %% Supervisor callbacks
14 | -export([init/1]).
15 |
16 | -define(SERVER, ?MODULE).
17 |
18 | %%====================================================================
19 | %% API functions
20 | %%====================================================================
21 |
22 | start_link() ->
23 | supervisor:start_link({local, ?SERVER}, ?MODULE, []).
24 |
25 | %%====================================================================
26 | %% Supervisor callbacks
27 | %%====================================================================
28 |
29 | %% Child :: {Id,StartFunc,Restart,Shutdown,Type,Modules}
30 | init([]) ->
31 | {ok, { {one_for_all, 0, 1}, []} }.
32 |
33 | %%====================================================================
34 | %% Internal functions
35 | %%====================================================================
36 |
--------------------------------------------------------------------------------
/tools/erlanalysis/src/main/resources/templates/app_type_include.vm:
--------------------------------------------------------------------------------
1 |
2 | #foreach($typeItem in $typeList)
3 | -record(${typeItem.getTypeName()},{
4 | #foreach($fieldItem in ${typeItem.getFieldList()})
5 | ${fieldItem.getFieldName()} ::${fieldItem.getFieldErlType()}#if($foreach.hasNext),
6 | #end
7 | #end
8 | }).
9 |
10 | #end
--------------------------------------------------------------------------------
/tools/erlanalysis/src/main/resources/templates/app_type_list.vm:
--------------------------------------------------------------------------------
1 | -module(${appName}_type_list).
2 |
3 | %% API
4 | -export([register_type_list/0,get_list/0]).
5 |
6 | -include("${appName}.hrl").
7 |
8 | get_list()->
9 | [
10 | #foreach($typeItem in $typeList)
11 | {${typeItem.getTypeName()},<<"${typeItem.getClassName()}">>,record_info(fields,${typeItem.getTypeName()})}#if($foreach.hasNext),
12 | #end
13 | #end
14 | ].
15 |
16 | register_type_list()->
17 | ok.
--------------------------------------------------------------------------------
/tools/erlanalysis/src/main/resources/templates/interface.vm:
--------------------------------------------------------------------------------
1 | -module(${moduleName}).
2 |
3 | -include_lib("dubboerl/include/dubbo.hrl").
4 | -include_lib("dubboerl/include/hessian.hrl").
5 |
6 | -define(CURRENT_CLASS_NAME,<<"${className}"/utf8>>).
7 | -define(CURRENT_CLASS_VERSION,<<"0.0.0"/utf8>>).
8 |
9 | -include("${appName}.hrl").
10 |
11 |
12 |
13 |
14 | %% API
15 | -export([
16 | #foreach($methodItem in $methodList)
17 | #set($argsLength=${methodItem.getArgsLength()} + 1 )
18 | ${methodItem.getName()}/${methodItem.getArgsLength()},
19 | ${methodItem.getName()}/${argsLength}#if($foreach.hasNext),
20 | #end
21 | #end
22 | ]).
23 |
24 | -export([get_method_999_list/0]).
25 |
26 | %% behaviour
27 | #foreach($methodItem in $methodList)
28 | -callback ${methodItem.getName()}(##
29 | #foreach($argsItemEntry in $methodItem.getParameterTypeList().entrySet())##
30 | ${argsItemEntry.key}::${argsItemEntry.value}#if($foreach.hasNext),
31 | #end##
32 | #end)-> ${methodItem.getReturnErlType()}.
33 | #end
34 |
35 | get_method_999_list()->
36 | [
37 | #foreach($methodItem in $methodList)
38 | ${methodItem.getName()}#if($foreach.hasNext),
39 | #end
40 | #end].
41 |
42 |
43 | #foreach($methodItem in $methodList)
44 | #*
45 | 方法申明
46 | *#
47 | -spec ${methodItem.getName()}(##
48 | #foreach($argsItemEntry in $methodItem.getParameterTypeList().entrySet())
49 | ${argsItemEntry.key}::${argsItemEntry.value}#if($foreach.hasNext),##
50 | #end
51 | #end)->
52 | {ok,reference()}|
53 | {ok,reference(),Data::${methodItem.getReturnErlType()},RpcContent::list()}|
54 | {error,Reason::timeout|no_provider|any()}.
55 | ${methodItem.getName()}(${methodItem.getParameterNameString()})->
56 | ${methodItem.getName()}(${methodItem.getParameterNameString()} #if($methodItem.getParameterNameString().length()>0),#end#{}).
57 |
58 | ${methodItem.getName()}(${methodItem.getParameterNameString()}#if($methodItem.getParameterNameString().length()>0),#end RequestOption)->
59 | #*
60 | ResponseTypeList=[
61 | ${methodItem.getResponseTypeDef()}
62 | ],
63 | *#
64 | Data = #dubbo_rpc_invocation{
65 | className = ?CURRENT_CLASS_NAME,
66 | classVersion = ?CURRENT_CLASS_VERSION,
67 | methodName = <<"${methodItem.getName()}">>,
68 | parameterDesc = <<"${methodItem.getArgsType()}"/utf8>>,
69 | parameterTypes = [
70 | ${methodItem.getParameterTypeDef()}
71 | ],
72 | parameters = [
73 | ${methodItem.getParameterNameString()}
74 | ],
75 | attachments = [
76 | {<<"path">>, ?CURRENT_CLASS_NAME},
77 | {<<"interface">> , ?CURRENT_CLASS_NAME}
78 | ]
79 | },
80 | Request = dubbo_adapter:reference(Data),
81 | dubbo_invoker:invoke_request(?CURRENT_CLASS_NAME,Request,RequestOption).
82 |
83 | #end
--------------------------------------------------------------------------------
/tools/erlanalysis/src/test/java/org/apache/dubbo/erlang/analysis/parse/InterfaceParseTest.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Licensed to the Apache Software Foundation (ASF) under one or more
3 | * contributor license agreements. See the NOTICE file distributed with
4 | * this work for additional information regarding copyright ownership.
5 | * The ASF licenses this file to You under the Apache License, Version 2.0
6 | * (the "License"); you may not use this file except in compliance with
7 | * the License. You may obtain a copy of the License at
8 | *
9 | * http://www.apache.org/licenses/LICENSE-2.0
10 | *
11 | * Unless required by applicable law or agreed to in writing, software
12 | * distributed under the License is distributed on an "AS IS" BASIS,
13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 | * See the License for the specific language governing permissions and
15 | * limitations under the License.
16 | */
17 |
18 | package org.apache.dubbo.erlang.analysis.parse;
19 |
20 | import junit.framework.TestCase;
21 |
22 | public class InterfaceParseTest extends TestCase {
23 | public void testParse() throws Exception {
24 | InterfaceParse parser = new InterfaceParse();
25 | parser.parse("org.apache.dubbo.erlang", "dubbo-sample-service", "1.3");
26 | }
27 | }
--------------------------------------------------------------------------------