Merge pull request #5 from DLive/master
Add license header to source code
diff --git a/Developer.md b/Developer.md
deleted file mode 100644
index 7fb83d3..0000000
--- a/Developer.md
+++ /dev/null
@@ -1,45 +0,0 @@
-## 开发
-
-```
- ./rebar3 eunit -m dubbo_zookeeper_tests
-
- dubbo_zookeeper:register_consumer(<<"com.ifcoder.demo.facade.User">>,[]).
-
- iProcessData:call_object().
-
-
- scherdule:call_object().
-
-
- ./rebar3 shell --apps "testdubboerl"
- dubboerl:init().
-
-```
-### eunit Test
- ./rebar3 eunit -m dubbo_zookeeper_tests
- ./rebar3 eunit -m de_codec_tests
-
-## 服务注册流程
-
-### 消费者注册
-
-
-
-### 生产者注册
-
-
-
-### 消费者调用
-
-```
- Option=[
- sync,
- {timeout,5000}
- {attachments,[{<<"a">>,<<"b">>}]}
- ]
-```
-
-
-
-
-## Develop Log
diff --git a/include/common.hrl b/include/common.hrl
index 70768b7..32f843c 100644
--- a/include/common.hrl
+++ b/include/common.hrl
@@ -1,13 +1,19 @@
-%%%-------------------------------------------------------------------
-%%% @author dlive
-%%% @copyright (C) 2016, <COMPANY>
-%%% @doc
-%%%
-%%% @end
-%%% Created : 14. 十月 2016 下午4:29
-%%%-------------------------------------------------------------------
--author("dlive").
-
+%%------------------------------------------------------------------------------
+%% Licensed to the Apache Software Foundation (ASF) under one or more
+%% contributor license agreements. See the NOTICE file distributed with
+%% this work for additional information regarding copyright ownership.
+%% The ASF licenses this file to You under the Apache License, Version 2.0
+%% (the "License"); you may not use this file except in compliance with
+%% the License. You may obtain a copy of the License at
+%%
+%% http://www.apache.org/licenses/LICENSE-2.0
+%%
+%% Unless required by applicable law or agreed to in writing, software
+%% distributed under the License is distributed on an "AS IS" BASIS,
+%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+%% See the License for the specific language governing permissions and
+%% limitations under the License.
+%%------------------------------------------------------------------------------
-ifdef(DEBUG).
-define(RELOADER,true).
-else.
diff --git a/include/dubbo.hrl b/include/dubbo.hrl
index 611eb69..ffd494e 100644
--- a/include/dubbo.hrl
+++ b/include/dubbo.hrl
@@ -1,13 +1,19 @@
-%%%-------------------------------------------------------------------
-%%% @author dlive
-%%% @copyright (C) 2016, <COMPANY>
-%%% @doc
-%%%
-%%% @end
-%%% Created : 16. 十月 2016 下午11:38
-%%%-------------------------------------------------------------------
--author("dlive").
-
+%%------------------------------------------------------------------------------
+%% Licensed to the Apache Software Foundation (ASF) under one or more
+%% contributor license agreements. See the NOTICE file distributed with
+%% this work for additional information regarding copyright ownership.
+%% The ASF licenses this file to You under the Apache License, Version 2.0
+%% (the "License"); you may not use this file except in compliance with
+%% the License. You may obtain a copy of the License at
+%%
+%% http://www.apache.org/licenses/LICENSE-2.0
+%%
+%% Unless required by applicable law or agreed to in writing, software
+%% distributed under the License is distributed on an "AS IS" BASIS,
+%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+%% See the License for the specific language governing permissions and
+%% limitations under the License.
+%%------------------------------------------------------------------------------
-include("hessian.hrl").
-define(DUBBO_VERSION,<<"2.6.0">>).
diff --git a/include/dubbo_type.hrl b/include/dubbo_type.hrl
index cd9972a..c09e0fa 100644
--- a/include/dubbo_type.hrl
+++ b/include/dubbo_type.hrl
@@ -1,13 +1,18 @@
-%%%-------------------------------------------------------------------
-%%% @author dlive
-%%% @copyright (C) 2018, <COMPANY>
-%%% @doc
-%%%
-%%% @end
-%%% Created : 15. Apr 2018 9:10 PM
-%%%-------------------------------------------------------------------
--author("dlive").
-
-
+%%------------------------------------------------------------------------------
+%% Licensed to the Apache Software Foundation (ASF) under one or more
+%% contributor license agreements. See the NOTICE file distributed with
+%% this work for additional information regarding copyright ownership.
+%% The ASF licenses this file to You under the Apache License, Version 2.0
+%% (the "License"); you may not use this file except in compliance with
+%% the License. You may obtain a copy of the License at
+%%
+%% http://www.apache.org/licenses/LICENSE-2.0
+%%
+%% Unless required by applicable law or agreed to in writing, software
+%% distributed under the License is distributed on an "AS IS" BASIS,
+%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+%% See the License for the specific language governing permissions and
+%% limitations under the License.
+%%------------------------------------------------------------------------------
-type response_content() :: binary().
diff --git a/include/dubboerl.hrl b/include/dubboerl.hrl
index baf4c25..31204a5 100644
--- a/include/dubboerl.hrl
+++ b/include/dubboerl.hrl
@@ -1,14 +1,19 @@
-%%%-------------------------------------------------------------------
-%%% @author dlive
-%%% @copyright (C) 2018, <COMPANY>
-%%% @doc
-%%%
-%%% @end
-%%% Created : 22. Mar 2018 6:53 PM
-%%%-------------------------------------------------------------------
--author("dlive").
-
-
+%%------------------------------------------------------------------------------
+%% Licensed to the Apache Software Foundation (ASF) under one or more
+%% contributor license agreements. See the NOTICE file distributed with
+%% this work for additional information regarding copyright ownership.
+%% The ASF licenses this file to You under the Apache License, Version 2.0
+%% (the "License"); you may not use this file except in compliance with
+%% the License. You may obtain a copy of the License at
+%%
+%% http://www.apache.org/licenses/LICENSE-2.0
+%%
+%% Unless required by applicable law or agreed to in writing, software
+%% distributed under the License is distributed on an "AS IS" BASIS,
+%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+%% See the License for the specific language governing permissions and
+%% limitations under the License.
+%%------------------------------------------------------------------------------
-define(PROVIDER_IMPL_TABLE,provider_impl_table).
-define(PROVIDER_WORKER,provider_worker).
diff --git a/include/hessian.hrl b/include/hessian.hrl
index 46ea79e..4b8206d 100755
--- a/include/hessian.hrl
+++ b/include/hessian.hrl
@@ -1,3 +1,18 @@
+% ---------------------------------------------------------------------------
+% Copyright (C) 2008 0x6e6562
+%
+% Licensed under the Apache License, Version 2.0 (the "License");
+% you may not use this file except in compliance with the License.
+% You may obtain a copy of the License at
+%
+% http://www.apache.org/licenses/LICENSE-2.0
+%
+% Unless required by applicable law or agreed to in writing, software
+% distributed under the License is distributed on an "AS IS" BASIS,
+% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+% See the License for the specific language governing permissions and
+% limitations under the License.
+% ---------------------------------------------------------------------------
-ifndef(HESSIAN_H).
-define(HESSIAN_H,1).
diff --git a/include/java_type.hrl b/include/java_type.hrl
index e85e3a7..a7d0f4c 100644
--- a/include/java_type.hrl
+++ b/include/java_type.hrl
@@ -1,13 +1,19 @@
-%%%-------------------------------------------------------------------
-%%% @author dlive
-%%% @copyright (C) 2018, <COMPANY>
-%%% @doc
-%%%
-%%% @end
-%%% Created : 09. Mar 2018 11:10 PM
-%%%-------------------------------------------------------------------
--author("dlive").
-
+%%------------------------------------------------------------------------------
+%% Licensed to the Apache Software Foundation (ASF) under one or more
+%% contributor license agreements. See the NOTICE file distributed with
+%% this work for additional information regarding copyright ownership.
+%% The ASF licenses this file to You under the Apache License, Version 2.0
+%% (the "License"); you may not use this file except in compliance with
+%% the License. You may obtain a copy of the License at
+%%
+%% http://www.apache.org/licenses/LICENSE-2.0
+%%
+%% Unless required by applicable law or agreed to in writing, software
+%% distributed under the License is distributed on an "AS IS" BASIS,
+%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+%% See the License for the specific language governing permissions and
+%% limitations under the License.
+%%------------------------------------------------------------------------------
-record(null_pointer_exception,{detailMessage,cause,stackTrace,suppressedExceptions}).
-record(stack_stack_trace_element,{declaringClass,methodName,fileName,lineNumber}).
\ No newline at end of file
diff --git a/samples/dubbo-sample-service/src/main/java/org/apache/dubbo/erlang/sample/service/App.java b/samples/dubbo-sample-service/src/main/java/org/apache/dubbo/erlang/sample/service/App.java
index a7a34d1..dc6deb1 100644
--- a/samples/dubbo-sample-service/src/main/java/org/apache/dubbo/erlang/sample/service/App.java
+++ b/samples/dubbo-sample-service/src/main/java/org/apache/dubbo/erlang/sample/service/App.java
@@ -1,3 +1,20 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
package org.apache.dubbo.erlang.sample.service;
import org.apache.dubbo.erlang.sample.service.bean.UserInfo;
@@ -8,14 +25,12 @@
/**
* Hello world!
- *
*/
-public class App
-{
- public static void main( String[] args ) throws IOException {
+public class App {
+ public static void main(String[] args) throws IOException {
System.out.println("将要监听服务");
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(
- new String[] { "applicationProvider.xml" });
+ new String[]{"applicationProvider.xml"});
context.start();
UserOperator userOperator = (UserOperator) context.getBean("userInterface");
UserInfo result = userOperator.getUserInfo("hh-bb");
diff --git a/samples/dubbo-sample-service/src/main/java/org/apache/dubbo/erlang/sample/service/AppListMain.java b/samples/dubbo-sample-service/src/main/java/org/apache/dubbo/erlang/sample/service/AppListMain.java
index 68f128c..81ee14e 100644
--- a/samples/dubbo-sample-service/src/main/java/org/apache/dubbo/erlang/sample/service/AppListMain.java
+++ b/samples/dubbo-sample-service/src/main/java/org/apache/dubbo/erlang/sample/service/AppListMain.java
@@ -1,12 +1,26 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
package org.apache.dubbo.erlang.sample.service;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import java.io.IOException;
-/**
- * Created by dlive on 2018/9/12.
- */
public class AppListMain {
public static void main( String[] args ) throws IOException {
@@ -14,9 +28,6 @@
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(
new String[] { "applicationProvider.xml" });
context.start();
-// UserOperator user = (UserOperator) context.getBean("userInterface");
-// UserRes result = user.queryUserList("listquery");
-// System.out.println("result:" + result.getUserlist().get(0).getUserName());
System.out.println("按任意键退出");
System.in.read();
diff --git a/samples/dubbo-sample-service/src/main/java/org/apache/dubbo/erlang/sample/service/bean/UserInfo.java b/samples/dubbo-sample-service/src/main/java/org/apache/dubbo/erlang/sample/service/bean/UserInfo.java
index 0c6725f..d489f2d 100644
--- a/samples/dubbo-sample-service/src/main/java/org/apache/dubbo/erlang/sample/service/bean/UserInfo.java
+++ b/samples/dubbo-sample-service/src/main/java/org/apache/dubbo/erlang/sample/service/bean/UserInfo.java
@@ -1,3 +1,20 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
package org.apache.dubbo.erlang.sample.service.bean;
import java.io.Serializable;
diff --git a/samples/dubbo-sample-service/src/main/java/org/apache/dubbo/erlang/sample/service/bean/UserInfoRequest.java b/samples/dubbo-sample-service/src/main/java/org/apache/dubbo/erlang/sample/service/bean/UserInfoRequest.java
index 3afbea4..56315c2 100644
--- a/samples/dubbo-sample-service/src/main/java/org/apache/dubbo/erlang/sample/service/bean/UserInfoRequest.java
+++ b/samples/dubbo-sample-service/src/main/java/org/apache/dubbo/erlang/sample/service/bean/UserInfoRequest.java
@@ -1,8 +1,22 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
package org.apache.dubbo.erlang.sample.service.bean;
-/**
- * Created by dlive on 2018/9/12.
- */
public class UserInfoRequest {
public String requestId;
public String username;
diff --git a/samples/dubbo-sample-service/src/main/java/org/apache/dubbo/erlang/sample/service/bean/UserRes.java b/samples/dubbo-sample-service/src/main/java/org/apache/dubbo/erlang/sample/service/bean/UserRes.java
index 9a22786..b566cdf 100644
--- a/samples/dubbo-sample-service/src/main/java/org/apache/dubbo/erlang/sample/service/bean/UserRes.java
+++ b/samples/dubbo-sample-service/src/main/java/org/apache/dubbo/erlang/sample/service/bean/UserRes.java
@@ -1,10 +1,24 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
package org.apache.dubbo.erlang.sample.service.bean;
import java.util.List;
-/**
- * Created by dlive on 2018/9/12.
- */
public class UserRes {
private String message;
private Integer code;
diff --git a/samples/dubbo-sample-service/src/main/java/org/apache/dubbo/erlang/sample/service/facade/UserOperator.java b/samples/dubbo-sample-service/src/main/java/org/apache/dubbo/erlang/sample/service/facade/UserOperator.java
index a9439d8..74c26c1 100644
--- a/samples/dubbo-sample-service/src/main/java/org/apache/dubbo/erlang/sample/service/facade/UserOperator.java
+++ b/samples/dubbo-sample-service/src/main/java/org/apache/dubbo/erlang/sample/service/facade/UserOperator.java
@@ -1,3 +1,20 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
package org.apache.dubbo.erlang.sample.service.facade;
import org.apache.dubbo.erlang.sample.service.bean.UserInfo;
@@ -6,8 +23,11 @@
public interface UserOperator {
public String genUserId();
+
public UserInfo getUserInfo(String userid);
+
public UserInfo queryUserInfo(UserInfoRequest request);
+
public UserRes queryUserList(String info);
}
diff --git a/samples/dubbo-sample-service/src/main/java/org/apache/dubbo/erlang/sample/service/impl/UserOperatorImpl.java b/samples/dubbo-sample-service/src/main/java/org/apache/dubbo/erlang/sample/service/impl/UserOperatorImpl.java
index e482c5b..c62913d 100644
--- a/samples/dubbo-sample-service/src/main/java/org/apache/dubbo/erlang/sample/service/impl/UserOperatorImpl.java
+++ b/samples/dubbo-sample-service/src/main/java/org/apache/dubbo/erlang/sample/service/impl/UserOperatorImpl.java
@@ -1,3 +1,20 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
package org.apache.dubbo.erlang.sample.service.impl;
import org.apache.dubbo.erlang.sample.service.bean.UserInfo;
@@ -24,7 +41,7 @@
@Override
public UserInfo queryUserInfo(UserInfoRequest request) {
- System.out.println("request:"+request.getRequestId());
+ System.out.println("request:" + request.getRequestId());
UserInfo info = new UserInfo();
info.setUserAge(99);
info.setUserId("id123");
diff --git a/samples/dubbo-sample-service/src/main/resources/applicationProvider.xml b/samples/dubbo-sample-service/src/main/resources/applicationProvider.xml
index f6991ce..974fabc 100644
--- a/samples/dubbo-sample-service/src/main/resources/applicationProvider.xml
+++ b/samples/dubbo-sample-service/src/main/resources/applicationProvider.xml
@@ -1,18 +1,17 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xmlns:dubbo="http://code.alibabatech.com/schema/dubbo"
- xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://code.alibabatech.com/schema/dubbo http://code.alibabatech.com/schema/dubbo/dubbo.xsd">
- <dubbo:application name="hello-world" /><!-- 注册地址 -->
- <dubbo:registry address="zookeeper://127.0.0.1:2181" />
- <dubbo:protocol name="dubbo" port="20880" />
-
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xmlns:dubbo="http://code.alibabatech.com/schema/dubbo"
+ xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://code.alibabatech.com/schema/dubbo http://code.alibabatech.com/schema/dubbo/dubbo.xsd">
+ <dubbo:application name="hello-world"/><!-- 注册地址 -->
+ <dubbo:registry address="zookeeper://127.0.0.1:2181"/>
+ <dubbo:protocol name="dubbo" port="20880"/>
<dubbo:consumer check="false" timeout="300000" id="dubboConsumerConfig" retries="0"/>
- <bean id="userService" class="org.apache.dubbo.erlang.sample.service.impl.UserOperatorImpl" />
- <dubbo:service interface="org.apache.dubbo.erlang.sample.service.facade.UserOperator" ref="userService"/>
+ <bean id="userService" class="org.apache.dubbo.erlang.sample.service.impl.UserOperatorImpl"/>
+ <dubbo:service interface="org.apache.dubbo.erlang.sample.service.facade.UserOperator" ref="userService"/>
-<!-- <dubbo:reference id="userInterface" interface="UserOperator" retries="0" />-->
+ <!-- <dubbo:reference id="userInterface" interface="UserOperator" retries="0" />-->
</beans>
diff --git a/samples/dubbo-sample-service/src/main/resources/log4j.properties b/samples/dubbo-sample-service/src/main/resources/log4j.properties
index d6e4cfe..6b34c8a 100644
--- a/samples/dubbo-sample-service/src/main/resources/log4j.properties
+++ b/samples/dubbo-sample-service/src/main/resources/log4j.properties
@@ -1,5 +1,4 @@
log4j.rootLogger=DEBUG,console
-
log4j.appender.console=org.apache.log4j.ConsoleAppender
log4j.appender.console.Threshold=DEBUG
#log4j.appender.console.ImmediateFlush=true
diff --git a/samples/dubbo-sample-service/src/test/java/org/apache/dubbo/erlang/sample/service/AppTest.java b/samples/dubbo-sample-service/src/test/java/org/apache/dubbo/erlang/sample/service/AppTest.java
index 93788df..b797f88 100644
--- a/samples/dubbo-sample-service/src/test/java/org/apache/dubbo/erlang/sample/service/AppTest.java
+++ b/samples/dubbo-sample-service/src/test/java/org/apache/dubbo/erlang/sample/service/AppTest.java
@@ -1,3 +1,20 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
package org.apache.dubbo.erlang.sample.service;
import static org.junit.Assert.assertTrue;
@@ -7,14 +24,12 @@
/**
* Unit test for simple App.
*/
-public class AppTest
-{
+public class AppTest {
/**
* Rigorous Test :-)
*/
@Test
- public void shouldAnswerWithTrue()
- {
- assertTrue( true );
+ public void shouldAnswerWithTrue() {
+ assertTrue(true);
}
}
diff --git a/src/dubbo_adapter.erl b/src/dubbo_adapter.erl
index e3e6be4..00d628f 100644
--- a/src/dubbo_adapter.erl
+++ b/src/dubbo_adapter.erl
@@ -1,30 +1,37 @@
-%%%-------------------------------------------------------------------
-%%% @author dlive
-%%% @copyright (C) 2019, <COMPANY>
-%%% @doc
-%%%
-%%% @end
-%%% Created : 07. May 2019 00:27
-%%%-------------------------------------------------------------------
+%%------------------------------------------------------------------------------
+%% Licensed to the Apache Software Foundation (ASF) under one or more
+%% contributor license agreements. See the NOTICE file distributed with
+%% this work for additional information regarding copyright ownership.
+%% The ASF licenses this file to You under the Apache License, Version 2.0
+%% (the "License"); you may not use this file except in compliance with
+%% the License. You may obtain a copy of the License at
+%%
+%% http://www.apache.org/licenses/LICENSE-2.0
+%%
+%% Unless required by applicable law or agreed to in writing, software
+%% distributed under the License is distributed on an "AS IS" BASIS,
+%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+%% See the License for the specific language governing permissions and
+%% limitations under the License.
+%%------------------------------------------------------------------------------
-module(dubbo_adapter).
--author("dlive").
-include("dubbo.hrl").
%% API
-export([reference/1]).
--spec(reference(Data::#dubbo_rpc_invocation{}) -> dubbo_request()).
-reference(Data)->
- #dubbo_request{
- is_event = false,
- is_twoway = true,
- mid = dubbo_id_generator:gen_id(),
- data = Data,
- mversion= <<"0.0.0">>,
- serialize_type = serialize_value(application:get_env(dubboerl,protocol,hessian))
- }.
+-spec(reference(Data :: #dubbo_rpc_invocation{}) -> dubbo_request()).
+reference(Data) ->
+ #dubbo_request{
+ is_event = false,
+ is_twoway = true,
+ mid = dubbo_id_generator:gen_id(),
+ data = Data,
+ mversion = <<"0.0.0">>,
+ serialize_type = serialize_value(application:get_env(dubboerl, protocol, hessian))
+ }.
-serialize_value(json)->
- ?SERIALIZATION_FASTJSON;
-serialize_value(_)->
- ?SERIALIZATION_HESSIAN.
+serialize_value(json) ->
+ ?SERIALIZATION_FASTJSON;
+serialize_value(_) ->
+ ?SERIALIZATION_HESSIAN.
diff --git a/src/dubbo_codec.erl b/src/dubbo_codec.erl
index ace771c..c3e241f 100644
--- a/src/dubbo_codec.erl
+++ b/src/dubbo_codec.erl
@@ -1,13 +1,20 @@
-%%%-------------------------------------------------------------------
-%%% @author dlive
-%%% @copyright (C) 2016, <COMPANY>
-%%% @doc
-%%%
-%%% @end
-%%% Created : 20. 十月 2016 下午6:21
-%%%-------------------------------------------------------------------
+%%------------------------------------------------------------------------------
+%% Licensed to the Apache Software Foundation (ASF) under one or more
+%% contributor license agreements. See the NOTICE file distributed with
+%% this work for additional information regarding copyright ownership.
+%% The ASF licenses this file to You under the Apache License, Version 2.0
+%% (the "License"); you may not use this file except in compliance with
+%% the License. You may obtain a copy of the License at
+%%
+%% http://www.apache.org/licenses/LICENSE-2.0
+%%
+%% Unless required by applicable law or agreed to in writing, software
+%% distributed under the License is distributed on an "AS IS" BASIS,
+%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+%% See the License for the specific language governing permissions and
+%% limitations under the License.
+%%------------------------------------------------------------------------------
-module(dubbo_codec).
--author("dlive").
-include("dubbo.hrl").
-include("hessian.hrl").
@@ -16,7 +23,7 @@
-compile(export_all).
-endif.
%% API
--export([encode_request/1,encode_response/1]).
+-export([encode_request/1, encode_response/1]).
-export([decode_header/1]).
-export([decode_response/2]).
@@ -24,84 +31,84 @@
--spec encode_request(#dubbo_request{})->{ok,binary()} | {error,term()}.
-encode_request(Request)->
- {ok,RequestData} = encode_request_data(Request#dubbo_request.serialize_type,Request),
+-spec encode_request(#dubbo_request{}) -> {ok, binary()} | {error, term()}.
+encode_request(Request) ->
+ {ok, RequestData} = encode_request_data(Request#dubbo_request.serialize_type, Request),
Size = byte_size(RequestData),
- Header = encode_header(Request,Size,0),
- RequestContent = <<Header/binary,RequestData/binary>>,
- {ok,RequestContent}.
+ Header = encode_header(Request, Size, 0),
+ RequestContent = <<Header/binary, RequestData/binary>>,
+ {ok, RequestContent}.
-encode_header(Request,DataLen,RequestState)->
- Header2=-128 bor Request#dubbo_request.serialize_type,
- Header21=case Request#dubbo_request.is_twoway of
- true -> Header2 bor 64;
- false-> Header2
- end,
- Header22=case Request#dubbo_request.is_event of
- true -> Header21 bor 32;
- false-> Header21
- end,
+encode_header(Request, DataLen, RequestState) ->
+ Header2 = -128 bor Request#dubbo_request.serialize_type,
+ Header21 = case Request#dubbo_request.is_twoway of
+ true -> Header2 bor 64;
+ false -> Header2
+ end,
+ Header22 = case Request#dubbo_request.is_event of
+ true -> Header21 bor 32;
+ false -> Header21
+ end,
RequestId = Request#dubbo_request.mid,
- Header = << ?DUBBO_MEGIC:16,Header22:8,RequestState:8,RequestId:64,DataLen:32>>,
+ Header = <<?DUBBO_MEGIC:16, Header22:8, RequestState:8, RequestId:64, DataLen:32>>,
Header.
-encode_request_data(?SERIALIZATION_FASTJSON,Request)->
+encode_request_data(?SERIALIZATION_FASTJSON, Request) ->
dubbo_serializa_json:encode_request_data(Request);
-encode_request_data(?SERIALIZATION_HESSIAN,Request)->
+encode_request_data(?SERIALIZATION_HESSIAN, Request) ->
dubbo_serializa_hessian:encode_request_data(Request).
--spec encode_response(#dubbo_response{})-> {ok,term()}.
-encode_response(Response)->
- {ok,ResponseData} = encode_response_data(Response#dubbo_response.serialize_type,Response),
+-spec encode_response(#dubbo_response{}) -> {ok, term()}.
+encode_response(Response) ->
+ {ok, ResponseData} = encode_response_data(Response#dubbo_response.serialize_type, Response),
Size = byte_size(ResponseData),
- Header = encode_response_header(Response,Size,?RESPONSE_STATE_OK),
- ResponseContent = <<Header/binary,ResponseData/binary>>,
+ Header = encode_response_header(Response, Size, ?RESPONSE_STATE_OK),
+ ResponseContent = <<Header/binary, ResponseData/binary>>,
{ok, ResponseContent}.
-encode_response_data(?SERIALIZATION_FASTJSON,Response)->
- {ok,Bin} = dubbo_serializa_json:encode_response_data(Response),
- {ok,Bin};
-encode_response_data(?SERIALIZATION_HESSIAN,Response)->
+encode_response_data(?SERIALIZATION_FASTJSON, Response) ->
+ {ok, Bin} = dubbo_serializa_json:encode_response_data(Response),
+ {ok, Bin};
+encode_response_data(?SERIALIZATION_HESSIAN, Response) ->
- {ok,Bin} = dubbo_serializa_hessian:encode_response_data(Response),
- {ok,Bin}.
+ {ok, Bin} = dubbo_serializa_hessian:encode_response_data(Response),
+ {ok, Bin}.
-encode_response_header(Response,DataLen, ResponseState)->
- Header2= Response#dubbo_response.serialize_type,
- Header21=case Response#dubbo_response.is_twoway of
- true -> Header2 bor 64;
- false-> Header2
- end,
- Header22=case Response#dubbo_response.is_event of
- true -> Header21 bor 32;
- false-> Header21
- end,
+encode_response_header(Response, DataLen, ResponseState) ->
+ Header2 = Response#dubbo_response.serialize_type,
+ Header21 = case Response#dubbo_response.is_twoway of
+ true -> Header2 bor 64;
+ false -> Header2
+ end,
+ Header22 = case Response#dubbo_response.is_event of
+ true -> Header21 bor 32;
+ false -> Header21
+ end,
RequestId = Response#dubbo_response.mid,
- Header = << ?DUBBO_MEGIC:16,Header22:8, ResponseState:8,RequestId:64,DataLen:32>>,
+ Header = <<?DUBBO_MEGIC:16, Header22:8, ResponseState:8, RequestId:64, DataLen:32>>,
Header.
--spec(decode_header(Header::binary())-> {State::ok|error,Type::request|response,Data::dubbo_response()|dubbo_request()}).
-decode_header(Header)->
- <<?DUBBO_MEGIC_HIGH,?DUBBO_MEGIC_LOW,Flag:8,State:8,Mid:64,DataLen:32>> = Header,
+-spec(decode_header(Header :: binary()) -> {State :: ok|error, Type :: request|response, Data :: dubbo_response()|dubbo_request()}).
+decode_header(Header) ->
+ <<?DUBBO_MEGIC_HIGH, ?DUBBO_MEGIC_LOW, Flag:8, State:8, Mid:64, DataLen:32>> = Header,
if
(Flag band 16#80) == 0 ->
- {DecodeState,Res} = decode_header(response,Flag,State,Mid,DataLen),
- {DecodeState,response,Res};
+ {DecodeState, Res} = decode_header(response, Flag, State, Mid, DataLen),
+ {DecodeState, response, Res};
true ->
- {DecodeState,Req} = decode_header(request,Flag,State,Mid,DataLen),
- {DecodeState,request,Req}
+ {DecodeState, Req} = decode_header(request, Flag, State, Mid, DataLen),
+ {DecodeState, request, Req}
end.
-decode_header(request,Flag,_State,Mid,_DataLen)->
+decode_header(request, Flag, _State, Mid, _DataLen) ->
SerializeType = Flag band 16#1f,
IsTwoWay = if
- (Flag band 16#40) /=0 -> true;
+ (Flag band 16#40) /= 0 -> true;
true -> false
- end,
+ end,
IsEvent = if
- (Flag band 16#20) /=0 -> true;
+ (Flag band 16#20) /= 0 -> true;
true -> false
end,
Req = #dubbo_request{
@@ -111,35 +118,35 @@
mversion = <<"2.0.0">>,
serialize_type = SerializeType
},
- {ok,Req};
-decode_header(response,Flag,State,Mid,_DataLen)->
+ {ok, Req};
+decode_header(response, Flag, State, Mid, _DataLen) ->
SerializeType = Flag band 16#1f,
IsEvent = if
- (Flag band 16#20) /= 0 -> true;
- true -> false
- end,
+ (Flag band 16#20) /= 0 -> true;
+ true -> false
+ end,
Res = #dubbo_response{is_event = IsEvent,
serialize_type = SerializeType,
state = State,
mid = Mid
},
- {ok,Res}.
+ {ok, Res}.
--spec decode_response(#dubbo_response{},binary())-> {ok,#dubbo_response{}}.
-decode_response(Res,Data)->
+-spec decode_response(#dubbo_response{}, binary()) -> {ok, #dubbo_response{}}.
+decode_response(Res, Data) ->
case Res#dubbo_response.serialize_type of
?SERIALIZATION_FASTJSON ->
- dubbo_serializa_json:decode_response(Res,Data);
+ dubbo_serializa_json:decode_response(Res, Data);
?SERIALIZATION_HESSIAN ->
- dubbo_serializa_hessian:decode_response(Res,Data)
+ dubbo_serializa_hessian:decode_response(Res, Data)
end.
--spec decode_request(#dubbo_request{},binary())-> {ok,#dubbo_request{}}.
-decode_request(Req,Data)->
+-spec decode_request(#dubbo_request{}, binary()) -> {ok, #dubbo_request{}}.
+decode_request(Req, Data) ->
case Req#dubbo_request.serialize_type of
?SERIALIZATION_FASTJSON ->
- dubbo_serializa_json:decode_request(Req,Data);
+ dubbo_serializa_json:decode_request(Req, Data);
?SERIALIZATION_HESSIAN ->
- dubbo_serializa_hessian:decode_request(Req,Data)
+ dubbo_serializa_hessian:decode_request(Req, Data)
end.
\ No newline at end of file
diff --git a/src/dubbo_common.erl b/src/dubbo_common.erl
index 11abb42..1a35b58 100644
--- a/src/dubbo_common.erl
+++ b/src/dubbo_common.erl
@@ -1,13 +1,20 @@
-%%%-------------------------------------------------------------------
-%%% @author dlive
-%%% @copyright (C) 2016, <COMPANY>
-%%% @doc
-%%%
-%%% @end
-%%% Created : 17. 十月 2016 上午12:23
-%%%-------------------------------------------------------------------
+%%------------------------------------------------------------------------------
+%% Licensed to the Apache Software Foundation (ASF) under one or more
+%% contributor license agreements. See the NOTICE file distributed with
+%% this work for additional information regarding copyright ownership.
+%% The ASF licenses this file to You under the Apache License, Version 2.0
+%% (the "License"); you may not use this file except in compliance with
+%% the License. You may obtain a copy of the License at
+%%
+%% http://www.apache.org/licenses/LICENSE-2.0
+%%
+%% Unless required by applicable law or agreed to in writing, software
+%% distributed under the License is distributed on an "AS IS" BASIS,
+%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+%% See the License for the specific language governing permissions and
+%% limitations under the License.
+%%------------------------------------------------------------------------------
-module(dubbo_common).
--author("dlive").
%% API
-export([]).
diff --git a/src/dubbo_common_fun.erl b/src/dubbo_common_fun.erl
index 665d390..6744171 100644
--- a/src/dubbo_common_fun.erl
+++ b/src/dubbo_common_fun.erl
@@ -1,24 +1,31 @@
-%%%-------------------------------------------------------------------
-%%% @author dlive
-%%% @copyright (C) 2017, <COMPANY>
-%%% @doc
-%%%
-%%% @end
-%%% Created : 27. Dec 2017 3:01 PM
-%%%-------------------------------------------------------------------
+%%------------------------------------------------------------------------------
+%% Licensed to the Apache Software Foundation (ASF) under one or more
+%% contributor license agreements. See the NOTICE file distributed with
+%% this work for additional information regarding copyright ownership.
+%% The ASF licenses this file to You under the Apache License, Version 2.0
+%% (the "License"); you may not use this file except in compliance with
+%% the License. You may obtain a copy of the License at
+%%
+%% http://www.apache.org/licenses/LICENSE-2.0
+%%
+%% Unless required by applicable law or agreed to in writing, software
+%% distributed under the License is distributed on an "AS IS" BASIS,
+%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+%% See the License for the specific language governing permissions and
+%% limitations under the License.
+%%------------------------------------------------------------------------------
-module(dubbo_common_fun).
--author("dlive").
%% API
--export([local_ip_v4/0,local_ip_v4_str/0]).
+-export([local_ip_v4/0, local_ip_v4_str/0]).
local_ip_v4() ->
{ok, Addrs} = inet:getifaddrs(),
hd([
Addr || {_, Opts} <- Addrs, {addr, Addr} <- Opts,
- size(Addr) == 4, Addr =/= {127,0,0,1}
+ size(Addr) == 4, Addr =/= {127, 0, 0, 1}
]).
-local_ip_v4_str()->
- {V1,V2,V3,V4} =local_ip_v4(),
- list_to_binary(io_lib:format("~p.~p.~p.~p",[V1,V2,V3,V4])).
+local_ip_v4_str() ->
+ {V1, V2, V3, V4} = local_ip_v4(),
+ list_to_binary(io_lib:format("~p.~p.~p.~p", [V1, V2, V3, V4])).
diff --git a/src/dubbo_config_util.erl b/src/dubbo_config_util.erl
index 1f1a47e..4db73d0 100644
--- a/src/dubbo_config_util.erl
+++ b/src/dubbo_config_util.erl
@@ -1,43 +1,50 @@
-%%%-------------------------------------------------------------------
-%%% @author dlive
-%%% @copyright (C) 2018, <COMPANY>
-%%% @doc
-%%%
-%%% @end
-%%% Created : 05. Jan 2018 12:21 AM
-%%%-------------------------------------------------------------------
+%%------------------------------------------------------------------------------
+%% Licensed to the Apache Software Foundation (ASF) under one or more
+%% contributor license agreements. See the NOTICE file distributed with
+%% this work for additional information regarding copyright ownership.
+%% The ASF licenses this file to You under the Apache License, Version 2.0
+%% (the "License"); you may not use this file except in compliance with
+%% the License. You may obtain a copy of the License at
+%%
+%% http://www.apache.org/licenses/LICENSE-2.0
+%%
+%% Unless required by applicable law or agreed to in writing, software
+%% distributed under the License is distributed on an "AS IS" BASIS,
+%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+%% See the License for the specific language governing permissions and
+%% limitations under the License.
+%%------------------------------------------------------------------------------
-module(dubbo_config_util).
--author("dlive").
-include("dubbo.hrl").
%% API
--export([gen_consumer/3,gen_provider/5]).
+-export([gen_consumer/3, gen_provider/5]).
-gen_consumer(Application,Interface,Option)->
+gen_consumer(Application, Interface, Option) ->
#consumer_config{
interface = Interface,
application = Application,
- category = <<"consumers">> ,
- check=false,
- default_timeout = proplists:get_value(default_timeout,Option,500),
- dubbo_version= proplists:get_value(dubbo_version,Option,?DUBBO_VERSION),
- methods=[],
- revision= <<"">>,
- side= <<"consumers">>
+ category = <<"consumers">>,
+ check = false,
+ default_timeout = proplists:get_value(default_timeout, Option, 500),
+ dubbo_version = proplists:get_value(dubbo_version, Option, ?DUBBO_VERSION),
+ methods = [],
+ revision = <<"">>,
+ side = <<"consumers">>
}.
-gen_provider(Application,Port,Interface,MethodList,Option)->
+gen_provider(Application, Port, Interface, MethodList, Option) ->
Host = dubbo_network_tools:local_ipv4_binary(),
- MethodList2= [atom_to_binary(Item,utf8) || Item <- MethodList ],
+ MethodList2 = [atom_to_binary(Item, utf8) || Item <- MethodList],
#provider_config{
- protocol= <<"dubbo">>,
- host= Host,
+ protocol = <<"dubbo">>,
+ host = Host,
port = Port,
- interface=Interface,
- anyhost=true,
- executes=10,
- application=Application,
+ interface = Interface,
+ anyhost = true,
+ executes = 10,
+ application = Application,
methods = MethodList2,
- side= <<"provider">>
+ side = <<"provider">>
}.
\ No newline at end of file
diff --git a/src/dubbo_consumer_pool.erl b/src/dubbo_consumer_pool.erl
index a0ff016..aba36b1 100644
--- a/src/dubbo_consumer_pool.erl
+++ b/src/dubbo_consumer_pool.erl
@@ -1,13 +1,20 @@
-%%%-------------------------------------------------------------------
-%%% @author dlive
-%%% @copyright (C) 2017, <COMPANY>
-%%% @doc
-%%%
-%%% @end
-%%% Created : 28. Dec 2017 7:34 PM
-%%%-------------------------------------------------------------------
+%%------------------------------------------------------------------------------
+%% Licensed to the Apache Software Foundation (ASF) under one or more
+%% contributor license agreements. See the NOTICE file distributed with
+%% this work for additional information regarding copyright ownership.
+%% The ASF licenses this file to You under the Apache License, Version 2.0
+%% (the "License"); you may not use this file except in compliance with
+%% the License. You may obtain a copy of the License at
+%%
+%% http://www.apache.org/licenses/LICENSE-2.0
+%%
+%% Unless required by applicable law or agreed to in writing, software
+%% distributed under the License is distributed on an "AS IS" BASIS,
+%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+%% See the License for the specific language governing permissions and
+%% limitations under the License.
+%%------------------------------------------------------------------------------
-module(dubbo_consumer_pool).
--author("dlive").
-behaviour(gen_server).
@@ -22,18 +29,17 @@
terminate/2,
code_change/3]).
--export([select_connection/1,select_connection/2]).
+-export([select_connection/1, select_connection/2]).
-include("dubbo.hrl").
-define(SERVER, ?MODULE).
--define(INTERFCE_LIST_TABLE,interface_list).
--define(PROVIDER_NODE_LIST_TABLE,provider_node_list).
+-define(INTERFCE_LIST_TABLE, interface_list).
+-define(PROVIDER_NODE_LIST_TABLE, provider_node_list).
-record(state, {}).
-
%%%===================================================================
%%% API
%%%===================================================================
@@ -70,21 +76,21 @@
init([]) ->
init_ets_table(),
{ok, #state{}}.
-init_ets_table()->
- try ets:new(?INTERFCE_LIST_TABLE, [bag,public,named_table,{keypos,2}]) of
+init_ets_table() ->
+ try ets:new(?INTERFCE_LIST_TABLE, [bag, public, named_table, {keypos, 2}]) of
?INTERFCE_LIST_TABLE ->
ok
catch
_Type:Reason ->
- logger:error("new ets table error ~p",[Reason]),
+ logger:error("new ets table error ~p", [Reason]),
error
end,
- try ets:new(?PROVIDER_NODE_LIST_TABLE, [bag,public,named_table,{keypos,2}]) of
+ try ets:new(?PROVIDER_NODE_LIST_TABLE, [bag, public, named_table, {keypos, 2}]) of
?PROVIDER_NODE_LIST_TABLE ->
ok
catch
_Type1:Reason1 ->
- logger:error("new ets table error ~p",[Reason1]),
+ logger:error("new ets table error ~p", [Reason1]),
error
end,
ok.
@@ -104,10 +110,10 @@
{stop, Reason :: term(), Reply :: term(), NewState :: #state{}} |
{stop, Reason :: term(), NewState :: #state{}}).
-handle_call({add_consumer,Interface,ProviderNodeList}, _From, State) ->
+handle_call({add_consumer, Interface, ProviderNodeList}, _From, State) ->
OldProviderList = get_interface_provider_node(Interface),
- NewProviderList = add_consumer(ProviderNodeList,[]),
+ NewProviderList = add_consumer(ProviderNodeList, []),
DeleteProverList = OldProviderList -- NewProviderList,
clean_invalid_provider(DeleteProverList),
{reply, ok, State};
@@ -175,108 +181,108 @@
code_change(_OldVsn, State, _Extra) ->
{ok, State}.
-start_consumer(Interface,ProviderNodeInfo)->
- gen_server:call(?SERVER,{add_consumer,Interface,ProviderNodeInfo}).
+start_consumer(Interface, ProviderNodeInfo) ->
+ gen_server:call(?SERVER, {add_consumer, Interface, ProviderNodeInfo}).
%%%===================================================================
%%% Internal functions
%%%===================================================================
-add_consumer([],RegisterList)->
+add_consumer([], RegisterList) ->
RegisterList;
-add_consumer([ProviderNodeInfo|ProviderList],RegisterList)->
+add_consumer([ProviderNodeInfo | ProviderList], RegisterList) ->
case dubbo_node_config_util:parse_provider_info(ProviderNodeInfo) of
- {ok,ProviderConfig} ->
- HostFlag=get_host_flag(ProviderConfig),
- case ets:lookup(?PROVIDER_NODE_LIST_TABLE,HostFlag) of
- []->
- ConnectionList = start_provider_process(HostFlag,30,ProviderConfig),
- ok = update_connection_info(ProviderConfig#provider_config.interface,HostFlag,ConnectionList,true),
+ {ok, ProviderConfig} ->
+ HostFlag = get_host_flag(ProviderConfig),
+ case ets:lookup(?PROVIDER_NODE_LIST_TABLE, HostFlag) of
+ [] ->
+ ConnectionList = start_provider_process(HostFlag, 30, ProviderConfig),
+ ok = update_connection_info(ProviderConfig#provider_config.interface, HostFlag, ConnectionList, true),
ok;
List ->
- List2 = lists:map(fun(#provider_node_list{connection_info = ConnectionItem })->
+ List2 = lists:map(fun(#provider_node_list{connection_info = ConnectionItem}) ->
ConnectionItem
- end,List),
- ok = update_connection_info(ProviderConfig#provider_config.interface,HostFlag,List2,false),
+ end, List),
+ ok = update_connection_info(ProviderConfig#provider_config.interface, HostFlag, List2, false),
ok
end,
- add_consumer(ProviderList,[HostFlag]++RegisterList);
- {error,R1} ->
- logger:error("parse provider info error reason ~p",[R1]),
- add_consumer(ProviderList,RegisterList)
+ add_consumer(ProviderList, [HostFlag] ++ RegisterList);
+ {error, R1} ->
+ logger:error("parse provider info error reason ~p", [R1]),
+ add_consumer(ProviderList, RegisterList)
end.
-start_provider_process(HostFlag,Weight,ProviderConfig) ->
- ExecutesList=lists:seq(1,ProviderConfig#provider_config.executes),
- ConnectionList= lists:map(fun(Item) ->
- ConnectionFlag= << HostFlag/binary,(integer_to_binary(Item))/binary >>,
- ConnectionFlagTerm= binary_to_atom(ConnectionFlag,utf8),
- AChild = {ConnectionFlagTerm,{dubbo_netty_client, start_link, [ConnectionFlagTerm,HostFlag,ProviderConfig,Item]}, permanent, 2000, worker, [dubbo_netty_client]},
- {ok,Pid} = dubbo_consumer_pool_sup:add_children(AChild),
- logger:info("start provider ~p pid info ~p~n",[HostFlag,Pid]),
- #connection_info{connection_id = ConnectionFlagTerm,pid = Pid,weight = Weight,host_flag = HostFlag}
- end,ExecutesList),
+start_provider_process(HostFlag, Weight, ProviderConfig) ->
+ ExecutesList = lists:seq(1, ProviderConfig#provider_config.executes),
+ ConnectionList = lists:map(fun(Item) ->
+ ConnectionFlag = <<HostFlag/binary, (integer_to_binary(Item))/binary>>,
+ ConnectionFlagTerm = binary_to_atom(ConnectionFlag, utf8),
+ AChild = {ConnectionFlagTerm, {dubbo_netty_client, start_link, [ConnectionFlagTerm, HostFlag, ProviderConfig, Item]}, permanent, 2000, worker, [dubbo_netty_client]},
+ {ok, Pid} = dubbo_consumer_pool_sup:add_children(AChild),
+ logger:info("start provider ~p pid info ~p~n", [HostFlag, Pid]),
+ #connection_info{connection_id = ConnectionFlagTerm, pid = Pid, weight = Weight, host_flag = HostFlag}
+ end, ExecutesList),
ConnectionList.
-get_host_flag(ProviderConfig)->
- HostFlag= << (list_to_binary(ProviderConfig#provider_config.host))/binary,<<"_">>/binary,(integer_to_binary(ProviderConfig#provider_config.port))/binary>>,
+get_host_flag(ProviderConfig) ->
+ HostFlag = <<(list_to_binary(ProviderConfig#provider_config.host))/binary, <<"_">>/binary, (integer_to_binary(ProviderConfig#provider_config.port))/binary>>,
HostFlag.
-update_connection_info(Interface,HostFlag,ConnectionList,IsUpdateProvideNode)->
+update_connection_info(Interface, HostFlag, ConnectionList, IsUpdateProvideNode) ->
lists:map(fun(Item) ->
- I1 = ets:insert(?INTERFCE_LIST_TABLE,#interface_list{interface = Interface,connection_info = Item}),
- logger:debug("save INTERFCE_LIST_TABLE ~p info:~p",[Interface,I1]),
+ I1 = ets:insert(?INTERFCE_LIST_TABLE, #interface_list{interface = Interface, connection_info = Item}),
+ logger:debug("save INTERFCE_LIST_TABLE ~p info:~p", [Interface, I1]),
case IsUpdateProvideNode of
- true->
- I2 = ets:insert(?PROVIDER_NODE_LIST_TABLE,#provider_node_list{host_flag = HostFlag,connection_info = Item }),
- logger:debug("save PROVIDER_NODE_LIST_TABLE ~p info:~p",[HostFlag,I2]);
- false->
+ true ->
+ I2 = ets:insert(?PROVIDER_NODE_LIST_TABLE, #provider_node_list{host_flag = HostFlag, connection_info = Item}),
+ logger:debug("save PROVIDER_NODE_LIST_TABLE ~p info:~p", [HostFlag, I2]);
+ false ->
ok
end,
ok
- end,ConnectionList),
+ end, ConnectionList),
ok.
-get_interface_provider_node(Interface)->
- case ets:lookup(?INTERFCE_LIST_TABLE,Interface) of
- []->
+get_interface_provider_node(Interface) ->
+ case ets:lookup(?INTERFCE_LIST_TABLE, Interface) of
+ [] ->
[];
- List->
+ List ->
ListRet = [Item#interface_list.connection_info#connection_info.host_flag || Item <- List],
lists_util:del_duplicate(ListRet)
end.
-select_connection(Interface)->
+select_connection(Interface) ->
RandNum = rand:uniform(2048),
- select_connection(Interface,RandNum).
-select_connection(Interface,RandNum)->
- case ets:lookup(?INTERFCE_LIST_TABLE,Interface) of
- []->
- {error,none};
- List->
+ select_connection(Interface, RandNum).
+select_connection(Interface, RandNum) ->
+ case ets:lookup(?INTERFCE_LIST_TABLE, Interface) of
+ [] ->
+ {error, none};
+ List ->
Len = length(List),
- RemNum = (RandNum rem Len)+1,
- InterfaceListItem = lists:nth(RemNum,List),
- {ok,InterfaceListItem#interface_list.connection_info}
+ RemNum = (RandNum rem Len) + 1,
+ InterfaceListItem = lists:nth(RemNum, List),
+ {ok, InterfaceListItem#interface_list.connection_info}
end.
-clean_invalid_provider([])->
+clean_invalid_provider([]) ->
ok;
-clean_invalid_provider([HostFlag | DeleteProverList])->
- case ets:lookup(?PROVIDER_NODE_LIST_TABLE,HostFlag) of
- []->
+clean_invalid_provider([HostFlag | DeleteProverList]) ->
+ case ets:lookup(?PROVIDER_NODE_LIST_TABLE, HostFlag) of
+ [] ->
ok;
- ProviderNodeList->
+ ProviderNodeList ->
ProviderNodeList1 = lists_util:del_duplicate(ProviderNodeList),
clean_connection_info(ProviderNodeList1)
end,
clean_invalid_provider(DeleteProverList).
-clean_connection_info(ProviderNodeList)->
- lists:map(fun(Item)->
- Pid=Item#provider_node_list.connection_info#connection_info.pid,
- ConnectionId=Item#provider_node_list.connection_info#connection_info.connection_id,
- Pattern=#interface_list{pid=Pid,_='_'},
- ets:delete_object(?INTERFCE_LIST_TABLE,Pattern),
+clean_connection_info(ProviderNodeList) ->
+ lists:map(fun(Item) ->
+ Pid = Item#provider_node_list.connection_info#connection_info.pid,
+ ConnectionId = Item#provider_node_list.connection_info#connection_info.connection_id,
+ Pattern = #interface_list{pid = Pid, _ = '_'},
+ ets:delete_object(?INTERFCE_LIST_TABLE, Pattern),
dubbo_consumer_pool_sup:stop_children(ConnectionId)
- end,ProviderNodeList),
+ end, ProviderNodeList),
ok.
\ No newline at end of file
diff --git a/src/dubbo_consumer_pool_sup.erl b/src/dubbo_consumer_pool_sup.erl
index a79d780..77a6dbe 100644
--- a/src/dubbo_consumer_pool_sup.erl
+++ b/src/dubbo_consumer_pool_sup.erl
@@ -1,18 +1,25 @@
-%%%-------------------------------------------------------------------
-%%% @author dlive
-%%% @copyright (C) 2017, <COMPANY>
-%%% @doc
-%%%
-%%% @end
-%%% Created : 30. Dec 2017 9:58 AM
-%%%-------------------------------------------------------------------
+%%------------------------------------------------------------------------------
+%% Licensed to the Apache Software Foundation (ASF) under one or more
+%% contributor license agreements. See the NOTICE file distributed with
+%% this work for additional information regarding copyright ownership.
+%% The ASF licenses this file to You under the Apache License, Version 2.0
+%% (the "License"); you may not use this file except in compliance with
+%% the License. You may obtain a copy of the License at
+%%
+%% http://www.apache.org/licenses/LICENSE-2.0
+%%
+%% Unless required by applicable law or agreed to in writing, software
+%% distributed under the License is distributed on an "AS IS" BASIS,
+%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+%% See the License for the specific language governing permissions and
+%% limitations under the License.
+%%------------------------------------------------------------------------------
-module(dubbo_consumer_pool_sup).
--author("dlive").
-behaviour(supervisor).
%% API
--export([start_link/0,add_children/1,stop_children/1]).
+-export([start_link/0, add_children/1, stop_children/1]).
%% Supervisor callbacks
-export([init/1]).
@@ -65,10 +72,10 @@
{ok, {SupFlags, []}}.
-add_children(ChildSpec)->
- supervisor:start_child(?SERVER,ChildSpec).
-stop_children(ChildID)->
- supervisor:terminate_child(?SERVER,ChildID).
+add_children(ChildSpec) ->
+ supervisor:start_child(?SERVER, ChildSpec).
+stop_children(ChildID) ->
+ supervisor:terminate_child(?SERVER, ChildID).
%%%===================================================================
%%% Internal functions
%%%===================================================================
diff --git a/src/dubbo_heartbeat.erl b/src/dubbo_heartbeat.erl
index e84deed..eb11fc6 100644
--- a/src/dubbo_heartbeat.erl
+++ b/src/dubbo_heartbeat.erl
@@ -1,23 +1,30 @@
-%%%-------------------------------------------------------------------
-%%% @author dlive
-%%% @copyright (C) 2016, <COMPANY>
-%%% @doc
-%%%
-%%% @end
-%%% Created : 20. 十月 2016 下午5:55
-%%%-------------------------------------------------------------------
+%%------------------------------------------------------------------------------
+%% Licensed to the Apache Software Foundation (ASF) under one or more
+%% contributor license agreements. See the NOTICE file distributed with
+%% this work for additional information regarding copyright ownership.
+%% The ASF licenses this file to You under the Apache License, Version 2.0
+%% (the "License"); you may not use this file except in compliance with
+%% the License. You may obtain a copy of the License at
+%%
+%% http://www.apache.org/licenses/LICENSE-2.0
+%%
+%% Unless required by applicable law or agreed to in writing, software
+%% distributed under the License is distributed on an "AS IS" BASIS,
+%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+%% See the License for the specific language governing permissions and
+%% limitations under the License.
+%%------------------------------------------------------------------------------
-module(dubbo_heartbeat).
--author("dlive").
-include("dubbo.hrl").
%% API
-export([generate_request/2]).
--spec(generate_request(RequestId::undefined|integer(),NeedResponse::boolean())->{ok,binary()}).
-generate_request(undefined,NeedResponse)->
+-spec(generate_request(RequestId :: undefined|integer(), NeedResponse :: boolean()) -> {ok, binary()}).
+generate_request(undefined, NeedResponse) ->
RequestId = dubbo_id_generator:gen_id(),
- generate_request(RequestId,NeedResponse);
-generate_request(RequestId,NeedResponse)->
- Req = #dubbo_request{is_event = true,is_twoway = NeedResponse,mid = RequestId,data = undefined,mversion= <<"2.0.0">>},
- {ok,Bin} = dubbo_codec:encode_request(Req),
- {ok,Bin}.
\ No newline at end of file
+ generate_request(RequestId, NeedResponse);
+generate_request(RequestId, NeedResponse) ->
+ Req = #dubbo_request{is_event = true, is_twoway = NeedResponse, mid = RequestId, data = undefined, mversion = <<"2.0.0">>},
+ {ok, Bin} = dubbo_codec:encode_request(Req),
+ {ok, Bin}.
\ No newline at end of file
diff --git a/src/dubbo_id_generator.erl b/src/dubbo_id_generator.erl
index a97406d..896aa0c 100644
--- a/src/dubbo_id_generator.erl
+++ b/src/dubbo_id_generator.erl
@@ -1,13 +1,20 @@
-%%%-------------------------------------------------------------------
-%%% @author dlive
-%%% @copyright (C) 2016, <COMPANY>
-%%% @doc
-%%%
-%%% @end
-%%% Created : 17. 十月 2016 上午11:12
-%%%-------------------------------------------------------------------
+%%------------------------------------------------------------------------------
+%% Licensed to the Apache Software Foundation (ASF) under one or more
+%% contributor license agreements. See the NOTICE file distributed with
+%% this work for additional information regarding copyright ownership.
+%% The ASF licenses this file to You under the Apache License, Version 2.0
+%% (the "License"); you may not use this file except in compliance with
+%% the License. You may obtain a copy of the License at
+%%
+%% http://www.apache.org/licenses/LICENSE-2.0
+%%
+%% Unless required by applicable law or agreed to in writing, software
+%% distributed under the License is distributed on an "AS IS" BASIS,
+%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+%% See the License for the specific language governing permissions and
+%% limitations under the License.
+%%------------------------------------------------------------------------------
-module(dubbo_id_generator).
--author("dlive").
-behaviour(gen_server).
@@ -21,11 +28,11 @@
handle_info/2,
terminate/2,
code_change/3]).
--export([gen_id/0,get_index/2]).
+-export([gen_id/0, get_index/2]).
-define(SERVER, ?MODULE).
--define(INDEX_ETS_TABLE,dubbo_id_count_table).
--define(MAX_NUM,9223372036854775807).
+-define(INDEX_ETS_TABLE, dubbo_id_count_table).
+-define(MAX_NUM, 9223372036854775807).
-record(state, {}).
%%%===================================================================
@@ -144,34 +151,34 @@
code_change(_OldVsn, State, _Extra) ->
{ok, State}.
-gen_id()->
- try ets:update_counter(?INDEX_ETS_TABLE,cur_index,{2,1,?MAX_NUM,1}) of
+gen_id() ->
+ try ets:update_counter(?INDEX_ETS_TABLE, cur_index, {2, 1, ?MAX_NUM, 1}) of
NewCount ->
NewCount
catch
_Type:_Reason ->
- (catch ets:insert(?INDEX_ETS_TABLE,{cur_index,1})),
- ets:update_counter(?INDEX_ETS_TABLE,cur_index,{2,1,?MAX_NUM,1})
+ (catch ets:insert(?INDEX_ETS_TABLE, {cur_index, 1})),
+ ets:update_counter(?INDEX_ETS_TABLE, cur_index, {2, 1, ?MAX_NUM, 1})
end.
-get_index(Type,Max)->
- try ets:update_counter(?INDEX_ETS_TABLE,Type,{2,1,Max,1}) of
+get_index(Type, Max) ->
+ try ets:update_counter(?INDEX_ETS_TABLE, Type, {2, 1, Max, 1}) of
NewCount ->
NewCount
catch
_Type:_Reason ->
- (catch ets:insert(?INDEX_ETS_TABLE,{Type,1})),
- ets:update_counter(?INDEX_ETS_TABLE,Type,{2,1,Max,1})
+ (catch ets:insert(?INDEX_ETS_TABLE, {Type, 1})),
+ ets:update_counter(?INDEX_ETS_TABLE, Type, {2, 1, Max, 1})
end.
%%%===================================================================
%%% Internal functions
%%%===================================================================
-init_table()->
- try ets:new(?INDEX_ETS_TABLE, [public,named_table]) of
+init_table() ->
+ try ets:new(?INDEX_ETS_TABLE, [public, named_table]) of
?INDEX_ETS_TABLE ->
- ets:insert(?INDEX_ETS_TABLE,{cur_index,1}),
+ ets:insert(?INDEX_ETS_TABLE, {cur_index, 1}),
ok
catch
_Type:Reason ->
- logger:error("[DUBBO] error init auto inc table reason:~p",[Reason])
+ logger:error("[DUBBO] error init auto inc table reason:~p", [Reason])
end.
\ No newline at end of file
diff --git a/src/dubbo_invoker.erl b/src/dubbo_invoker.erl
index 7b72492..b29751c 100644
--- a/src/dubbo_invoker.erl
+++ b/src/dubbo_invoker.erl
@@ -1,90 +1,97 @@
-%%%-------------------------------------------------------------------
-%%% @author dlive
-%%% @copyright (C) 2018, <COMPANY>
-%%% @doc
-%%%
-%%% @end
-%%% Created : 06. Mar 2018 12:17 AM
-%%%-------------------------------------------------------------------
+%%------------------------------------------------------------------------------
+%% Licensed to the Apache Software Foundation (ASF) under one or more
+%% contributor license agreements. See the NOTICE file distributed with
+%% this work for additional information regarding copyright ownership.
+%% The ASF licenses this file to You under the Apache License, Version 2.0
+%% (the "License"); you may not use this file except in compliance with
+%% the License. You may obtain a copy of the License at
+%%
+%% http://www.apache.org/licenses/LICENSE-2.0
+%%
+%% Unless required by applicable law or agreed to in writing, software
+%% distributed under the License is distributed on an "AS IS" BASIS,
+%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+%% See the License for the specific language governing permissions and
+%% limitations under the License.
+%%------------------------------------------------------------------------------
-module(dubbo_invoker).
--author("dlive").
-include("dubbo.hrl").
%% API
--export([invoke_request/2,invoke_request/3,invoke_request/5]).
+-export([invoke_request/2, invoke_request/3, invoke_request/5]).
--spec invoke_request(Interface::binary(),Request::#dubbo_request{})->
- {ok,reference()}|
- {ok,reference(),Data::any(),RpcContent::list()}|
- {error,Reason::timeout|no_provider|any()}.
-invoke_request(Interface,Request)->
- invoke_request(Interface,Request,[],#{},self()).
+-spec invoke_request(Interface :: binary(), Request :: #dubbo_request{}) ->
+ {ok, reference()}|
+ {ok, reference(), Data :: any(), RpcContent :: list()}|
+ {error, Reason :: timeout|no_provider|any()}.
+invoke_request(Interface, Request) ->
+ invoke_request(Interface, Request, [], #{}, self()).
--spec invoke_request(Interface::binary(),Request::#dubbo_request{},RequestOption::map())->
- {ok,reference()}|
- {ok,reference(),Data::any(),RpcContent::list()}|
- {error,Reason::timeout|no_provider|any()}.
-invoke_request(Interface,Request,RequestOption)->
- invoke_request(Interface,Request,maps:get(ctx,RequestOption,[]),RequestOption,self()).
+-spec invoke_request(Interface :: binary(), Request :: #dubbo_request{}, RequestOption :: map()) ->
+ {ok, reference()}|
+ {ok, reference(), Data :: any(), RpcContent :: list()}|
+ {error, Reason :: timeout|no_provider|any()}.
+invoke_request(Interface, Request, RequestOption) ->
+ invoke_request(Interface, Request, maps:get(ctx, RequestOption, []), RequestOption, self()).
--spec invoke_request(Interface::binary(),Request::#dubbo_request{},RpcContext::list(),RequestState::map(),CallBackPid::pid())->
- {ok,reference()}|
- {ok,reference(),Data::any(),RpcContent::list()}|
- {error,Reason::timeout|no_provider|request_full|any()}.
-invoke_request(Interface,Request,RpcContext,RequestState,CallBackPid)->
- case dubbo_consumer_pool:select_connection(Interface,Request#dubbo_request.mid) of
- {ok,#connection_info{pid=Pid,host_flag = HostFlag}} ->
- case dubbo_traffic_control:check_goon(HostFlag,199) of
+-spec invoke_request(Interface :: binary(), Request :: #dubbo_request{}, RpcContext :: list(), RequestState :: map(), CallBackPid :: pid()) ->
+ {ok, reference()}|
+ {ok, reference(), Data :: any(), RpcContent :: list()}|
+ {error, Reason :: timeout|no_provider|request_full|any()}.
+invoke_request(Interface, Request, RpcContext, RequestState, CallBackPid) ->
+ case dubbo_consumer_pool:select_connection(Interface, Request#dubbo_request.mid) of
+ {ok, #connection_info{pid = Pid, host_flag = HostFlag}} ->
+ case dubbo_traffic_control:check_goon(HostFlag, 199) of
ok ->
- Request2 = merge_attachments(Request,RpcContext),
- {ok,RequestData} = dubbo_codec:encode_request(Request2),
- Ref=get_ref(RequestState),
- gen_server:cast(Pid,{send_request,Ref,Request2,RequestData,CallBackPid,RequestState}),
+ Request2 = merge_attachments(Request, RpcContext),
+ {ok, RequestData} = dubbo_codec:encode_request(Request2),
+ Ref = get_ref(RequestState),
+ gen_server:cast(Pid, {send_request, Ref, Request2, RequestData, CallBackPid, RequestState}),
case is_sync(RequestState) of
- true->
- sync_receive(Ref,get_timeout(RequestState));
- false-> {ok, Ref}
+ true ->
+ sync_receive(Ref, get_timeout(RequestState));
+ false -> {ok, Ref}
end;
full ->
- {error,request_full}
+ {error, request_full}
end;
- {error,none}->
- logger:error("[INVOKE] ~p error Reason no_provider",[Interface]),
- {error,no_provider}
+ {error, none} ->
+ logger:error("[INVOKE] ~p error Reason no_provider", [Interface]),
+ {error, no_provider}
end.
-is_sync(Option)->
- maps:is_key(sync,Option).
-get_ref(Option)->
- maps:get(ref,Option,make_ref()).
+is_sync(Option) ->
+ maps:is_key(sync, Option).
+get_ref(Option) ->
+ maps:get(ref, Option, make_ref()).
-get_timeout(Option)->
- maps:get(timeout,Option,?REQUEST_TIME_OUT).
+get_timeout(Option) ->
+ maps:get(timeout, Option, ?REQUEST_TIME_OUT).
-sync_receive(Ref,TimeOut)->
+sync_receive(Ref, TimeOut) ->
receive
- {'$gen_cast',{response_process,Ref,RpcContent,Response}}->
- {ok,Ref,Response,RpcContent}
+ {'$gen_cast', {response_process, Ref, RpcContent, Response}} ->
+ {ok, Ref, Response, RpcContent}
after
TimeOut ->
- {error,timeout}
+ {error, timeout}
end.
-merge_attachments(#dubbo_request{data = null}=Request,_Option) ->
+merge_attachments(#dubbo_request{data = null} = Request, _Option) ->
Request;
-merge_attachments(Request,Option)->
- Attachements= Request#dubbo_request.data#dubbo_rpc_invocation.attachments,
- case lists:keyfind(attachments,1,Option) of
- false->OptionAttachments=[];
- {attachments,OptionAttachments}->
+merge_attachments(Request, Option) ->
+ Attachements = Request#dubbo_request.data#dubbo_rpc_invocation.attachments,
+ case lists:keyfind(attachments, 1, Option) of
+ false -> OptionAttachments = [];
+ {attachments, OptionAttachments} ->
OptionAttachments
end,
- List=[
+ List = [
{<<"version">>, <<"0.0.0">>},
{<<"timeout">>, <<"5000">>}
],
- Attachements2= lists:merge3(Attachements,OptionAttachments,List),
- Data2=Request#dubbo_request.data#dubbo_rpc_invocation{attachments = Attachements2},
+ Attachements2 = lists:merge3(Attachements, OptionAttachments, List),
+ Data2 = Request#dubbo_request.data#dubbo_rpc_invocation{attachments = Attachements2},
Request#dubbo_request{data = Data2}.
diff --git a/src/dubbo_netty_client.erl b/src/dubbo_netty_client.erl
index 754c8c5..bd0bc67 100644
--- a/src/dubbo_netty_client.erl
+++ b/src/dubbo_netty_client.erl
@@ -1,13 +1,20 @@
-%%%-------------------------------------------------------------------
-%%% @author dlive
-%%% @copyright (C) 2016, <COMPANY>
-%%% @doc
-%%%
-%%% @end
-%%% Created : 14. 十月 2016 下午3:31
-%%%-------------------------------------------------------------------
+%%------------------------------------------------------------------------------
+%% Licensed to the Apache Software Foundation (ASF) under one or more
+%% contributor license agreements. See the NOTICE file distributed with
+%% this work for additional information regarding copyright ownership.
+%% The ASF licenses this file to You under the Apache License, Version 2.0
+%% (the "License"); you may not use this file except in compliance with
+%% the License. You may obtain a copy of the License at
+%%
+%% http://www.apache.org/licenses/LICENSE-2.0
+%%
+%% Unless required by applicable law or agreed to in writing, software
+%% distributed under the License is distributed on an "AS IS" BASIS,
+%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+%% See the License for the specific language governing permissions and
+%% limitations under the License.
+%%------------------------------------------------------------------------------
-module(dubbo_netty_client).
--author("dlive").
-behaviour(gen_server).
@@ -26,10 +33,10 @@
-define(SERVER, ?MODULE).
--record(heartbeat,{last_write=0,last_read=0,timeout=60000,max_timeout=61000}).
--record(state, {provider_config,socket =undefined,
- heartbeat=#heartbeat{},
- recv_buffer= <<>> , %%从服务端接收的数据
+-record(heartbeat, {last_write = 0, last_read = 0, timeout = 60000, max_timeout = 61000}).
+-record(state, {provider_config, socket = undefined,
+ heartbeat = #heartbeat{},
+ recv_buffer = <<>>, %%从服务端接收的数据
host_flag,
reconnection_timer
}).
@@ -44,10 +51,10 @@
%%
%% @end
%%--------------------------------------------------------------------
--spec(start_link(Name::binary(),HostFlag::binary(),ProviderConfig::#provider_config{},integer()) ->
+-spec(start_link(Name :: binary(), HostFlag :: binary(), ProviderConfig :: #provider_config{}, integer()) ->
{ok, Pid :: pid()} | ignore | {error, Reason :: term()}).
-start_link(Name,HostFlag,ProviderConfig,Index) ->
- gen_server:start_link({local, Name}, ?MODULE, [HostFlag,ProviderConfig,Index], []).
+start_link(Name, HostFlag, ProviderConfig, Index) ->
+ gen_server:start_link({local, Name}, ?MODULE, [HostFlag, ProviderConfig, Index], []).
%%%===================================================================
%%% gen_server callbacks
@@ -67,20 +74,20 @@
-spec(init(Args :: term()) ->
{ok, State :: #state{}} | {ok, State :: #state{}, timeout() | hibernate} |
{stop, Reason :: term()} | ignore).
-init([HostFlag,ProviderConfig,Index]) ->
- erlang:process_flag(min_bin_vheap_size, 1024*1024),
- #provider_config{host = Host,port = Port}=ProviderConfig,
- State = case open(Host,Port) of
- {ok,Socket} ->
+init([HostFlag, ProviderConfig, Index]) ->
+ erlang:process_flag(min_bin_vheap_size, 1024 * 1024),
+ #provider_config{host = Host, port = Port} = ProviderConfig,
+ State = case open(Host, Port) of
+ {ok, Socket} ->
#state{socket = Socket};
- {error,_Reason}->
+ {error, _Reason} ->
#state{}
- end,
+ end,
NowStamp = time_util:timestamp_ms(),
- HeartBeatInfo = #heartbeat{last_read = NowStamp,last_write = NowStamp},
- logger:info("netty client start ~p",[HostFlag]),
+ HeartBeatInfo = #heartbeat{last_read = NowStamp, last_write = NowStamp},
+ logger:info("netty client start ~p", [HostFlag]),
start_heartbeat_timer(HeartBeatInfo),
- {ok, State#state{provider_config=ProviderConfig,heartbeat=HeartBeatInfo,host_flag = HostFlag}}.
+ {ok, State#state{provider_config = ProviderConfig, heartbeat = HeartBeatInfo, host_flag = HostFlag}}.
%%--------------------------------------------------------------------
%% @private
@@ -112,22 +119,22 @@
{noreply, NewState :: #state{}, timeout() | hibernate} |
{stop, Reason :: term(), NewState :: #state{}}).
-handle_cast({send_request,Ref,Request,Data,SourcePid,RequestState}, State) ->
- logger:debug("[send_request begin] send data to provider consumer mid ~p pid ~p sourcePid ~p",[Request#dubbo_request.mid,self(),SourcePid]),
- NewState = case send_msg(Data,State) of
- ok->
- save_request_info(Request,SourcePid,Ref,RequestState),
- logger:debug("[send_request end] send data to provider consumer pid ~p state ok",[self()]),
- State;
- {error,closed}->
- logger:warning("send request error, connection is closed"),
- State2 = reconnect(State),
- State2;
- {error,R1}->
- logger:error("[send_request end] send data to provider consumer pid error ~p ~p",[self(),R1]),
- State
- end,
- HeartbeatInfo =update_heartbeat(write,NewState#state.heartbeat),
+handle_cast({send_request, Ref, Request, Data, SourcePid, RequestState}, State) ->
+ logger:debug("[send_request begin] send data to provider consumer mid ~p pid ~p sourcePid ~p", [Request#dubbo_request.mid, self(), SourcePid]),
+ NewState = case send_msg(Data, State) of
+ ok ->
+ save_request_info(Request, SourcePid, Ref, RequestState),
+ logger:debug("[send_request end] send data to provider consumer pid ~p state ok", [self()]),
+ State;
+ {error, closed} ->
+ logger:warning("send request error, connection is closed"),
+ State2 = reconnect(State),
+ State2;
+ {error, R1} ->
+ logger:error("[send_request end] send data to provider consumer pid error ~p ~p", [self(), R1]),
+ State
+ end,
+ HeartbeatInfo = update_heartbeat(write, NewState#state.heartbeat),
{noreply, NewState#state{heartbeat = HeartbeatInfo}};
handle_cast(_Request, State) ->
@@ -149,44 +156,44 @@
{stop, Reason :: term(), NewState :: #state{}}).
-handle_info({tcp,_Port,Data}, #state{recv_buffer = RecvBuffer} = State) ->
+handle_info({tcp, _Port, Data}, #state{recv_buffer = RecvBuffer} = State) ->
%% inet:setopts(State#state.socket, [{active, once}]),
%% logger:debug("[INFO] recv one data ~w",[Data]),
- {ok,NextBuffer,NewState} = case check_recv_data(<< RecvBuffer/binary,Data/binary >>,State) of
- {next_buffer,NextBuffer2,State3}->
- logger:debug("[INFO] recv one data state wait next_buffer"),
- {ok,NextBuffer2,State3}
- end,
+ {ok, NextBuffer, NewState} = case check_recv_data(<<RecvBuffer/binary, Data/binary>>, State) of
+ {next_buffer, NextBuffer2, State3} ->
+ logger:debug("[INFO] recv one data state wait next_buffer"),
+ {ok, NextBuffer2, State3}
+ end,
%% HeartbeatInfo =update_heartbeat(write,NewState#state.heartbeat),
{noreply, NewState#state{recv_buffer = NextBuffer}};
-handle_info({tcp_closed,Port},State)->
- logger:info("dubbo connection closed ~p",[Port]),
- NewState=reconnect(State),
+handle_info({tcp_closed, Port}, State) ->
+ logger:info("dubbo connection closed ~p", [Port]),
+ NewState = reconnect(State),
{noreply, NewState};
-handle_info({timeout, _TimerRef, {reconnect}},State)->
- NewState=reconnect(State#state{reconnection_timer = undefined}),
+handle_info({timeout, _TimerRef, {reconnect}}, State) ->
+ NewState = reconnect(State#state{reconnection_timer = undefined}),
{noreply, NewState};
-handle_info({timeout, _TimerRef, {heartbeat_timer}},State) ->
- {ok,NewState} = case check_heartbeat_state(State) of
- {normal}-> {ok,State};
- {send_heart}->
- send_heartbeat_msg(undefined,true,State);
- {reconnect} ->
- %% @todo reconnect
- {ok,State}
- end,
- HeartbeatInfo = update_heartbeat(write,NewState#state.heartbeat),
+handle_info({timeout, _TimerRef, {heartbeat_timer}}, State) ->
+ {ok, NewState} = case check_heartbeat_state(State) of
+ {normal} -> {ok, State};
+ {send_heart} ->
+ send_heartbeat_msg(undefined, true, State);
+ {reconnect} ->
+ %% @todo reconnect
+ {ok, State}
+ end,
+ HeartbeatInfo = update_heartbeat(write, NewState#state.heartbeat),
start_heartbeat_timer(HeartbeatInfo),
- {noreply,NewState#state{heartbeat = HeartbeatInfo}};
-handle_info(_Info,State) ->
- logger:warning("[INFO] get one info:~p",[_Info]),
+ {noreply, NewState#state{heartbeat = HeartbeatInfo}};
+handle_info(_Info, State) ->
+ logger:warning("[INFO] get one info:~p", [_Info]),
%% inet:setopts(State#state.socket, [{active, once}]),
%% case State#state.tmp_pid of
%% undefined ->ok;
%% Pid ->
%% gen_server:cast(Pid,{msg_back})
%% end,
- HeartbeatInfo =update_heartbeat(write,State#state.heartbeat),
+ HeartbeatInfo = update_heartbeat(write, State#state.heartbeat),
{noreply, State#state{heartbeat = HeartbeatInfo}}.
%%--------------------------------------------------------------------
@@ -203,7 +210,7 @@
-spec(terminate(Reason :: (normal | shutdown | {shutdown, term()} | term()),
State :: #state{}) -> term()).
terminate(_Reason, _State) ->
- logger:warning("terminate reason:~p",[_Reason]),
+ logger:warning("terminate reason:~p", [_Reason]),
ok.
%%--------------------------------------------------------------------
@@ -224,76 +231,76 @@
%%% Internal functions
%%%===================================================================
-open(Host,Port)->
- logger:debug("will connect to provider ~p ~p",[Host,Port]),
+open(Host, Port) ->
+ logger:debug("will connect to provider ~p ~p", [Host, Port]),
%
- case gen_tcp:connect(Host,Port,[
+ case gen_tcp:connect(Host, Port, [
binary,
- {packet,0},{active, false},
- {reuseaddr,true},
+ {packet, 0}, {active, false},
+ {reuseaddr, true},
{delay_send, true},
{nodelay, true},
{high_watermark, 512 * 1024},
{low_watermark, 256 * 1024},
{sndbuf, 512 * 1024},
{recbuf, 512 * 1024}
- ]) of
- {ok,Sockets} ->
+ ]) of
+ {ok, Sockets} ->
inet:setopts(Sockets, [{active, true}]),
- {ok,Sockets};
+ {ok, Sockets};
Info ->
- logger:error("start client connection error ~p",[Info]),
- {error,Info}
+ logger:error("start client connection error ~p", [Info]),
+ {error, Info}
end.
-reconnect(#state{reconnection_timer = Timer}=State) when Timer /= undefined ->
+reconnect(#state{reconnection_timer = Timer} = State) when Timer /= undefined ->
State;
-reconnect(State)->
- #provider_config{host = Host,port = Port} = State#state.provider_config,
+reconnect(State) ->
+ #provider_config{host = Host, port = Port} = State#state.provider_config,
case State#state.socket of
- undefined ->ok;
- Socket->
+ undefined -> ok;
+ Socket ->
gen_tcp:close(Socket)
end,
- case open(Host,Port) of
- {ok,Socket2}->
- logger:warning("reconnect to provider ~p ~p success",[Host,Port]),
- State#state{socket = Socket2,recv_buffer = <<>>};
- {error,Reason}->
- logger:warning("connect to provider error ~p",[Reason]),
- TimerRef = erlang:start_timer(2000,self(),{reconnect}),
- State#state{socket = undefined,reconnection_timer = TimerRef}
+ case open(Host, Port) of
+ {ok, Socket2} ->
+ logger:warning("reconnect to provider ~p ~p success", [Host, Port]),
+ State#state{socket = Socket2, recv_buffer = <<>>};
+ {error, Reason} ->
+ logger:warning("connect to provider error ~p", [Reason]),
+ TimerRef = erlang:start_timer(2000, self(), {reconnect}),
+ State#state{socket = undefined, reconnection_timer = TimerRef}
end.
-send_msg(Msg,State) ->
+send_msg(Msg, State) ->
case State#state.socket of
- undefined->
- {error,closed};
+ undefined ->
+ {error, closed};
Socket ->
- case gen_tcp:send(Socket,Msg) of
- ok->
+ case gen_tcp:send(Socket, Msg) of
+ ok ->
ok;
- {error,Reason}->
- logger:error("send to server error,reason:~p",[Reason]),
- {error,Reason}
+ {error, Reason} ->
+ logger:error("send to server error,reason:~p", [Reason]),
+ {error, Reason}
end
end.
%%%=================================================================
%%% 心跳检测
%%%=================================================================
-start_heartbeat_timer(HeartbeatInfo)->
- erlang:start_timer(HeartbeatInfo#heartbeat.timeout, self() , {heartbeat_timer}),
+start_heartbeat_timer(HeartbeatInfo) ->
+ erlang:start_timer(HeartbeatInfo#heartbeat.timeout, self(), {heartbeat_timer}),
ok.
-update_heartbeat(write,Info)->
+update_heartbeat(write, Info) ->
Info#heartbeat{last_write = time_util:timestamp_ms()};
-update_heartbeat(read,Info)->
+update_heartbeat(read, Info) ->
Info#heartbeat{last_read = time_util:timestamp_ms()}.
-check_heartbeat_state(#state{heartbeat = HeartBeatInfo}=_State)->
+check_heartbeat_state(#state{heartbeat = HeartBeatInfo} = _State) ->
Now = time_util:timestamp_ms(),
- #heartbeat{last_read = LastRead,last_write = LastWrite,timeout = Timeout,max_timeout = MaxTimeout} = HeartBeatInfo,
+ #heartbeat{last_read = LastRead, last_write = LastWrite, timeout = Timeout, max_timeout = MaxTimeout} = HeartBeatInfo,
if
(Now - LastRead) > Timeout ->
{send_heart};
@@ -301,58 +308,58 @@
{send_heart};
(Now - LastRead) > MaxTimeout ->
{reconnect};
- true->
+ true ->
{normal}
end.
-send_heartbeat_msg(Mid,NeedResponse,State)->
- {ok,Bin} = dubbo_heartbeat:generate_request(Mid,NeedResponse),
- NewState = case send_msg(Bin,State) of
- ok ->
- logger:info("send one heartbeat msg to server"),
- State;
- {error,Reason} ->
- logger:warning("dubbo connection send heartbeat error ~p",[Reason]),
- State2 = reconnect(State),
- State2
- end,
- {ok,NewState}.
+send_heartbeat_msg(Mid, NeedResponse, State) ->
+ {ok, Bin} = dubbo_heartbeat:generate_request(Mid, NeedResponse),
+ NewState = case send_msg(Bin, State) of
+ ok ->
+ logger:info("send one heartbeat msg to server"),
+ State;
+ {error, Reason} ->
+ logger:warning("dubbo connection send heartbeat error ~p", [Reason]),
+ State2 = reconnect(State),
+ State2
+ end,
+ {ok, NewState}.
%%%=================================================================
%%% 接收数据处理
%%%=================================================================
--spec check_recv_data(Data::binary(),State::#state{})->{ready,ReadyData::binary()} | {ready,ReadyData::binary(),NextBuffer::binary()}.
-check_recv_data(<<?DUBBO_MEGIC_HIGH,?DUBBO_MEGIC_LOW,Rest/binary>> = Data,State) when byte_size(Rest)<14 ->
- {next_buffer,Data,State};
-check_recv_data(<<?DUBBO_MEGIC_HIGH,?DUBBO_MEGIC_LOW,_OtherFlag:80,DataLen:32,Rest/binary>> = Data,State) ->
+-spec check_recv_data(Data :: binary(), State :: #state{}) -> {ready, ReadyData :: binary()} | {ready, ReadyData :: binary(), NextBuffer :: binary()}.
+check_recv_data(<<?DUBBO_MEGIC_HIGH, ?DUBBO_MEGIC_LOW, Rest/binary>> = Data, State) when byte_size(Rest) < 14 ->
+ {next_buffer, Data, State};
+check_recv_data(<<?DUBBO_MEGIC_HIGH, ?DUBBO_MEGIC_LOW, _OtherFlag:80, DataLen:32, Rest/binary>> = Data, State) ->
RestSize = byte_size(Rest),
if
- DataLen==RestSize ->
- {ok,State2} = process_data(Data,State),
- {next_buffer,<<>>,State2};
- DataLen>RestSize ->
- logger:warning("need wait next buffer data ~p",[Data]),
- {next_buffer,Data,State};
- DataLen<RestSize ->
- <<ReadyData:DataLen/binary,NextBuffer/binary>> = Rest,
- OneData = <<?DUBBO_MEGIC_HIGH:8,?DUBBO_MEGIC_LOW:8,_OtherFlag:80,DataLen:32,ReadyData/binary>>,
- {ok,State3} = process_data(OneData,State),
+ DataLen == RestSize ->
+ {ok, State2} = process_data(Data, State),
+ {next_buffer, <<>>, State2};
+ DataLen > RestSize ->
+ logger:warning("need wait next buffer data ~p", [Data]),
+ {next_buffer, Data, State};
+ DataLen < RestSize ->
+ <<ReadyData:DataLen/binary, NextBuffer/binary>> = Rest,
+ OneData = <<?DUBBO_MEGIC_HIGH:8, ?DUBBO_MEGIC_LOW:8, _OtherFlag:80, DataLen:32, ReadyData/binary>>,
+ {ok, State3} = process_data(OneData, State),
%% logger:warning("recevi more data ~w ",[NextBuffer]),
- check_recv_data(NextBuffer,State3)
+ check_recv_data(NextBuffer, State3)
end;
-check_recv_data(<<Error/integer,Data/binary>>,State)->
- logger:error("recv bad header data,Begin Byte:~p",[Error]),
- check_recv_data(Data,State);
-check_recv_data(<<>>,State)->
- {next_buffer,<<>>,State}.
+check_recv_data(<<Error/integer, Data/binary>>, State) ->
+ logger:error("recv bad header data,Begin Byte:~p", [Error]),
+ check_recv_data(Data, State);
+check_recv_data(<<>>, State) ->
+ {next_buffer, <<>>, State}.
-process_data(Data,State)->
- <<Header:16/binary,RestData/binary>> = Data,
+process_data(Data, State) ->
+ <<Header:16/binary, RestData/binary>> = Data,
case dubbo_codec:decode_header(Header) of
- {ok,response,ResponseInfo}->
- process_response(ResponseInfo#dubbo_response.is_event,ResponseInfo,RestData,State),
+ {ok, response, ResponseInfo} ->
+ process_response(ResponseInfo#dubbo_response.is_event, ResponseInfo, RestData, State),
%% dubbo_traffic_control:decr_count(State#state.host_flag),
%% case get_earse_request_info(ResponseInfo#dubbo_response.mid) of
%% undefined->
@@ -371,50 +378,50 @@
%% ok
%% end
%% end,
- {ok,State};
- {ok,request,RequestInfo}->
- {ok,Req} = dubbo_codec:decode_request(RequestInfo,RestData),
- logger:info("get one request mid ~p, is_event ~p",[Req#dubbo_request.mid,Req#dubbo_request.is_event]),
- {ok,State2} = process_request(Req#dubbo_request.is_event,Req,State),
- {ok,State2};
- {error,Type,RelData}->
- logger:error("process_data error type ~p RelData ~p",[Type,RelData]),
- {ok,State}
+ {ok, State};
+ {ok, request, RequestInfo} ->
+ {ok, Req} = dubbo_codec:decode_request(RequestInfo, RestData),
+ logger:info("get one request mid ~p, is_event ~p", [Req#dubbo_request.mid, Req#dubbo_request.is_event]),
+ {ok, State2} = process_request(Req#dubbo_request.is_event, Req, State),
+ {ok, State2};
+ {error, Type, RelData} ->
+ logger:error("process_data error type ~p RelData ~p", [Type, RelData]),
+ {ok, State}
end.
%% @doc process event
--spec process_response(IsEvent::boolean(),#dubbo_response{},#state{},term())->ok.
-process_response(false,ResponseInfo,RestData,State)->
+-spec process_response(IsEvent :: boolean(), #dubbo_response{}, #state{}, term()) -> ok.
+process_response(false, ResponseInfo, RestData, State) ->
dubbo_traffic_control:decr_count(State#state.host_flag),
case get_earse_request_info(ResponseInfo#dubbo_response.mid) of
- undefined->
- logger:error("dubbo response can't find request data,response ~p",[ResponseInfo]);
- {SourcePid,Ref,_RequestState} ->
- {ok,Res} = dubbo_codec:decode_response(ResponseInfo,RestData),
- logger:info("got one response mid ~p, is_event ~p state ~p",[Res#dubbo_response.mid,Res#dubbo_response.is_event,Res#dubbo_response.state]),
+ undefined ->
+ logger:error("dubbo response can't find request data,response ~p", [ResponseInfo]);
+ {SourcePid, Ref, _RequestState} ->
+ {ok, Res} = dubbo_codec:decode_response(ResponseInfo, RestData),
+ logger:info("got one response mid ~p, is_event ~p state ~p", [Res#dubbo_response.mid, Res#dubbo_response.is_event, Res#dubbo_response.state]),
case Res#dubbo_response.is_event of
false ->
%% todo rpccontent need merge response with request
- RpcContent=[],
+ RpcContent = [],
ResponseData = dubbo_type_transfer:response_to_native(Res),
- gen_server:cast(SourcePid,{response_process,Ref,RpcContent,ResponseData});
- _->
+ gen_server:cast(SourcePid, {response_process, Ref, RpcContent, ResponseData});
+ _ ->
ok
end
end,
- {ok,State};
-process_response(true,_ResponseInfo,_RestData,State)->
- {ok,State}.
+ {ok, State};
+process_response(true, _ResponseInfo, _RestData, State) ->
+ {ok, State}.
-process_request(true,Request,State)->
- {ok,NewState} = send_heartbeat_msg(Request#dubbo_request.mid,false,State),
- {ok,NewState};
-process_request(false,Request,State)->
- {ok,State}.
+process_request(true, Request, State) ->
+ {ok, NewState} = send_heartbeat_msg(Request#dubbo_request.mid, false, State),
+ {ok, NewState};
+process_request(false, Request, State) ->
+ {ok, State}.
-save_request_info(Request,SourcePid,Ref,RequestState)->
- put(Request#dubbo_request.mid,{SourcePid,Ref,RequestState}).
-get_earse_request_info(Mid)->
+save_request_info(Request, SourcePid, Ref, RequestState) ->
+ put(Request#dubbo_request.mid, {SourcePid, Ref, RequestState}).
+get_earse_request_info(Mid) ->
erase(Mid).
\ No newline at end of file
diff --git a/src/dubbo_network_tools.erl b/src/dubbo_network_tools.erl
index a74b8e4..24c55de 100644
--- a/src/dubbo_network_tools.erl
+++ b/src/dubbo_network_tools.erl
@@ -1,28 +1,35 @@
-%%%-------------------------------------------------------------------
-%%% @author dlive
-%%% @copyright (C) 2018, <COMPANY>
-%%% @doc
-%%%
-%%% @end
-%%% Created : 21. Mar 2018 4:07 PM
-%%%-------------------------------------------------------------------
+%%------------------------------------------------------------------------------
+%% Licensed to the Apache Software Foundation (ASF) under one or more
+%% contributor license agreements. See the NOTICE file distributed with
+%% this work for additional information regarding copyright ownership.
+%% The ASF licenses this file to You under the Apache License, Version 2.0
+%% (the "License"); you may not use this file except in compliance with
+%% the License. You may obtain a copy of the License at
+%%
+%% http://www.apache.org/licenses/LICENSE-2.0
+%%
+%% Unless required by applicable law or agreed to in writing, software
+%% distributed under the License is distributed on an "AS IS" BASIS,
+%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+%% See the License for the specific language governing permissions and
+%% limitations under the License.
+%%------------------------------------------------------------------------------
-module(dubbo_network_tools).
--author("dlive").
%% API
--export([local_ip_v4/0,local_ipv4/0,local_ipv4_binary/0]).
+-export([local_ip_v4/0, local_ipv4/0, local_ipv4_binary/0]).
local_ip_v4() ->
{ok, Addrs} = inet:getifaddrs(),
hd([
Addr || {_, Opts} <- Addrs, {addr, Addr} <- Opts,
- size(Addr) == 4, Addr =/= {127,0,0,1}
+ size(Addr) == 4, Addr =/= {127, 0, 0, 1}
]).
-local_ipv4_binary()->
- {I1,I2,I3,I4}=local_ip_v4(),
- list_to_binary(io_lib:format("~p.~p.~p.~p",[I1,I2,I3,I4])).
-local_ipv4()->
- {I1,I2,I3,I4}=local_ip_v4(),
- lists:flatten(io_lib:format("~p.~p.~p.~p",[I1,I2,I3,I4])).
+local_ipv4_binary() ->
+ {I1, I2, I3, I4} = local_ip_v4(),
+ list_to_binary(io_lib:format("~p.~p.~p.~p", [I1, I2, I3, I4])).
+local_ipv4() ->
+ {I1, I2, I3, I4} = local_ip_v4(),
+ lists:flatten(io_lib:format("~p.~p.~p.~p", [I1, I2, I3, I4])).
diff --git a/src/dubbo_node_config_util.erl b/src/dubbo_node_config_util.erl
index f28e162..9d96523 100644
--- a/src/dubbo_node_config_util.erl
+++ b/src/dubbo_node_config_util.erl
@@ -1,76 +1,83 @@
-%%%-------------------------------------------------------------------
-%%% @author dlive
-%%% @copyright (C) 2017, <COMPANY>
-%%% @doc
-%%%
-%%% @end
-%%% Created : 30. Dec 2017 2:27 PM
-%%%-------------------------------------------------------------------
+%%------------------------------------------------------------------------------
+%% Licensed to the Apache Software Foundation (ASF) under one or more
+%% contributor license agreements. See the NOTICE file distributed with
+%% this work for additional information regarding copyright ownership.
+%% The ASF licenses this file to You under the Apache License, Version 2.0
+%% (the "License"); you may not use this file except in compliance with
+%% the License. You may obtain a copy of the License at
+%%
+%% http://www.apache.org/licenses/LICENSE-2.0
+%%
+%% Unless required by applicable law or agreed to in writing, software
+%% distributed under the License is distributed on an "AS IS" BASIS,
+%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+%% See the License for the specific language governing permissions and
+%% limitations under the License.
+%%------------------------------------------------------------------------------
-module(dubbo_node_config_util).
--author("dlive").
-include("dubbo.hrl").
%% API
--export([parse_provider_info/1,gen_provider_info/1]).
+-export([parse_provider_info/1, gen_provider_info/1]).
-parse_provider_info(ProviderStr) when is_binary(ProviderStr)->
+parse_provider_info(ProviderStr) when is_binary(ProviderStr) ->
parse_provider_info(binary_to_list(ProviderStr));
-parse_provider_info(ProviderStr)->
- case http_uri:parse(http_uri:decode(ProviderStr),[{scheme_defaults,[{dubbo,20880}]}]) of
+parse_provider_info(ProviderStr) ->
+ case http_uri:parse(http_uri:decode(ProviderStr), [{scheme_defaults, [{dubbo, 20880}]}]) of
{ok, {Scheme, _UserInfo, Host, Port, _Path, Query}} ->
- QueryStr = case lists:prefix("?",Query) of
- true ->
- [_|Query2] = Query,
- Query2;
- false->
- Query
- end,
- QueryListTmp = string:tokens(QueryStr,"&"),
- ProviderConfig = parse_parameter(QueryListTmp,#provider_config{protocol=Scheme,host=Host,port = Port}),
- logger:debug("parse provider info string ~p,result: ~p",[ProviderStr,ProviderConfig]),
- {ok,ProviderConfig};
- {error,R1} ->
- logger:debug("parse provider error string ~p, error ~p",[ProviderStr,R1]),
- {error,R1}
+ QueryStr = case lists:prefix("?", Query) of
+ true ->
+ [_ | Query2] = Query,
+ Query2;
+ false ->
+ Query
+ end,
+ QueryListTmp = string:tokens(QueryStr, "&"),
+ ProviderConfig = parse_parameter(QueryListTmp, #provider_config{protocol = Scheme, host = Host, port = Port}),
+ logger:debug("parse provider info string ~p,result: ~p", [ProviderStr, ProviderConfig]),
+ {ok, ProviderConfig};
+ {error, R1} ->
+ logger:debug("parse provider error string ~p, error ~p", [ProviderStr, R1]),
+ {error, R1}
end.
-parse_parameter([],Config)->
+parse_parameter([], Config) ->
Config;
-parse_parameter([Item|Rest],Config)->
- case string:tokens(Item,"=") of
- KeyPair when length(KeyPair) ==2 ->
- [Key,Value] = KeyPair,
- ConfigNew = parse_parameter(Key,Value,Config),
- parse_parameter(Rest,ConfigNew);
+parse_parameter([Item | Rest], Config) ->
+ case string:tokens(Item, "=") of
+ KeyPair when length(KeyPair) == 2 ->
+ [Key, Value] = KeyPair,
+ ConfigNew = parse_parameter(Key, Value, Config),
+ parse_parameter(Rest, ConfigNew);
KeyPair2 ->
- logger:error("parse parameter error, keypair ~p",[KeyPair2]),
- parse_parameter(Rest,Config)
+ logger:error("parse parameter error, keypair ~p", [KeyPair2]),
+ parse_parameter(Rest, Config)
end.
-parse_parameter("anyhost",Value,Config)->
+parse_parameter("anyhost", Value, Config) ->
Config#provider_config{anyhost = list_to_atom(Value)};
-parse_parameter("application",Value,Config)->
+parse_parameter("application", Value, Config) ->
Config#provider_config{application = list_to_binary(Value)};
-parse_parameter("dubbo",Value,Config)->
+parse_parameter("dubbo", Value, Config) ->
Config#provider_config{dubbo = list_to_binary(Value)};
-parse_parameter("executes",Value,Config)->
+parse_parameter("executes", Value, Config) ->
Config#provider_config{executes = list_to_integer(Value)};
-parse_parameter("interface",Value,Config)->
+parse_parameter("interface", Value, Config) ->
Config#provider_config{interface = list_to_binary(Value)};
-parse_parameter("methods",Value,Config)->
- MethodList= string:tokens(Value,","),
+parse_parameter("methods", Value, Config) ->
+ MethodList = string:tokens(Value, ","),
MethodList2 = [list_to_binary(Item) || Item <- MethodList],
Config#provider_config{methods = MethodList2};
-parse_parameter("side",Value,Config)->
+parse_parameter("side", Value, Config) ->
Config#provider_config{side = list_to_binary(Value)};
-parse_parameter("interface",Value,Config)->
+parse_parameter("interface", Value, Config) ->
Config#provider_config{interface = list_to_binary(Value)};
-parse_parameter(_,_,Config)->
+parse_parameter(_, _, Config) ->
Config.
-gen_provider_info(ProviderConfig)->
- Parameter=gen_provider_parameter(ProviderConfig),
- Info = io_lib:format("dubbo://~s:~p/~s?~s",[
+gen_provider_info(ProviderConfig) ->
+ Parameter = gen_provider_parameter(ProviderConfig),
+ Info = io_lib:format("dubbo://~s:~p/~s?~s", [
ProviderConfig#provider_config.host,
ProviderConfig#provider_config.port,
ProviderConfig#provider_config.interface,
@@ -79,17 +86,17 @@
list_to_binary(http_uri:encode(Info)).
gen_provider_parameter(Providerconfig) ->
- Method= [binary_to_list(Item) || Item <- Providerconfig#provider_config.methods],
- Method2= list_to_binary(string:join(Method,",")),
- List=[
- {<<"interface">>,Providerconfig#provider_config.interface},
- {<<"application">>,Providerconfig#provider_config.application},
+ Method = [binary_to_list(Item) || Item <- Providerconfig#provider_config.methods],
+ Method2 = list_to_binary(string:join(Method, ",")),
+ List = [
+ {<<"interface">>, Providerconfig#provider_config.interface},
+ {<<"application">>, Providerconfig#provider_config.application},
{<<"anyhost">>, <<"true">>},
- {<<"dubbo">>,Providerconfig#provider_config.dubbo},
- {<<"executes">>,integer_to_binary(Providerconfig#provider_config.executes)},
- {<<"methods">>,Method2},
- {<<"side">>,Providerconfig#provider_config.side},
- {<<"timestamp">>,integer_to_binary(time_util:timestamp_ms())}
+ {<<"dubbo">>, Providerconfig#provider_config.dubbo},
+ {<<"executes">>, integer_to_binary(Providerconfig#provider_config.executes)},
+ {<<"methods">>, Method2},
+ {<<"side">>, Providerconfig#provider_config.side},
+ {<<"timestamp">>, integer_to_binary(time_util:timestamp_ms())}
],
- List2 = [io_lib:format("~ts=~ts",[Key,Value]) || {Key,Value} <- List],
- lists:flatten(string:join(List2,"&")).
\ No newline at end of file
+ List2 = [io_lib:format("~ts=~ts", [Key, Value]) || {Key, Value} <- List],
+ lists:flatten(string:join(List2, "&")).
\ No newline at end of file
diff --git a/src/dubbo_provider_protocol.erl b/src/dubbo_provider_protocol.erl
index eec62cb..11434b6 100644
--- a/src/dubbo_provider_protocol.erl
+++ b/src/dubbo_provider_protocol.erl
@@ -1,13 +1,20 @@
-%%%-------------------------------------------------------------------
-%%% @author dlive
-%%% @copyright (C) 2018, <COMPANY>
-%%% @doc
-%%%
-%%% @end
-%%% Created : 20. Mar 2018 7:19 PM
-%%%-------------------------------------------------------------------
+%%------------------------------------------------------------------------------
+%% Licensed to the Apache Software Foundation (ASF) under one or more
+%% contributor license agreements. See the NOTICE file distributed with
+%% this work for additional information regarding copyright ownership.
+%% The ASF licenses this file to You under the Apache License, Version 2.0
+%% (the "License"); you may not use this file except in compliance with
+%% the License. You may obtain a copy of the License at
+%%
+%% http://www.apache.org/licenses/LICENSE-2.0
+%%
+%% Unless required by applicable law or agreed to in writing, software
+%% distributed under the License is distributed on an "AS IS" BASIS,
+%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+%% See the License for the specific language governing permissions and
+%% limitations under the License.
+%%------------------------------------------------------------------------------
-module(dubbo_provider_protocol).
--author("dlive").
-behaviour(gen_server).
-behaviour(ranch_protocol).
@@ -16,7 +23,7 @@
%% API
--export([start_link/4,register_impl_provider/3, select_impl_provider/1]).
+-export([start_link/4, register_impl_provider/3, select_impl_provider/1]).
%% gen_server callbacks
-export([init/1,
@@ -30,11 +37,11 @@
-define(IDLE_TIMEOUT, 70000).
--record(heartbeat,{last_write=0,last_read=0,timeout=50000,max_timeout=9000}).
+-record(heartbeat, {last_write = 0, last_read = 0, timeout = 50000, max_timeout = 9000}).
--record(state, {transport,provider_config,socket =undefined,
- heartbeat=#heartbeat{},
- recv_buffer= <<>> %%从客户端接收的数据
+-record(state, {transport, provider_config, socket = undefined,
+ heartbeat = #heartbeat{},
+ recv_buffer = <<>> %%从客户端接收的数据
}).
%%%===================================================================
@@ -55,24 +62,24 @@
logger:info("provider connected"),
ok = ranch:accept_ack(Ref),
%% ok = Transport:setopts(Socket, [{active, once}]),
- ok = Transport:setopts(Socket, [{active, true},{packet,0}]),
+ ok = Transport:setopts(Socket, [{active, true}, {packet, 0}]),
gen_server:enter_loop(?MODULE, [],
- #state{socket=Socket, transport=Transport},
+ #state{socket = Socket, transport = Transport},
?IDLE_TIMEOUT).
-handle_info({tcp,_Port,Data}, #state{recv_buffer = RecvBuffer,socket=Socket, transport=Transport} = State) ->
+handle_info({tcp, _Port, Data}, #state{recv_buffer = RecvBuffer, socket = Socket, transport = Transport} = State) ->
%% Transport:setopts(Socket, [{active, once}]),
- NowBuffer = << RecvBuffer/binary,Data/binary >>,
+ NowBuffer = <<RecvBuffer/binary, Data/binary>>,
- {ok,NextBuffer,NewState} = case check_recv_data(NowBuffer,State) of
- {next_buffer,<<>>,State2} ->
- {ok,<<>>,State2};
- {next_buffer,NextBuffer2,State3}->
- logger:debug("[INFO] recv one data state wait next_buffer"),
- {ok,NextBuffer2,State3}
- end,
+ {ok, NextBuffer, NewState} = case check_recv_data(NowBuffer, State) of
+ {next_buffer, <<>>, State2} ->
+ {ok, <<>>, State2};
+ {next_buffer, NextBuffer2, State3} ->
+ logger:debug("[INFO] recv one data state wait next_buffer"),
+ {ok, NextBuffer2, State3}
+ end,
%% HeartbeatInfo =update_heartbeat(write,NewState#state.heartbeat),
- {noreply, NewState#state{recv_buffer = NextBuffer},?IDLE_TIMEOUT};
+ {noreply, NewState#state{recv_buffer = NextBuffer}, ?IDLE_TIMEOUT};
handle_info({tcp_closed, _Socket}, State) ->
logger:warning("provider socket is closed"),
@@ -81,102 +88,101 @@
{stop, Reason, State};
handle_info(timeout, State) ->
logger:info("dubbo provider connection idle timeout"),
- {stop, {shutdown,idle_timeout}, State};
+ {stop, {shutdown, idle_timeout}, State};
handle_info(_Info, State) ->
{stop, normal, State}.
handle_call(_Request, _From, State) ->
{reply, ok, State}.
-handle_cast({send_response,Data}, #state{socket = Socket} = State) ->
- case gen_tcp:send(Socket,Data) of
+handle_cast({send_response, Data}, #state{socket = Socket} = State) ->
+ case gen_tcp:send(Socket, Data) of
ok ->
ok;
Other ->
- logger:warning("response error ~p",[Other])
+ logger:warning("response error ~p", [Other])
end,
{noreply, State};
handle_cast(_Msg, State) ->
{noreply, State}.
terminate(Reason, _State) ->
- logger:info("proviver connection terminal reason ~p",[Reason]),
+ logger:info("proviver connection terminal reason ~p", [Reason]),
ok.
code_change(_OldVsn, State, _Extra) ->
{ok, State}.
-register_impl_provider(Interface,ImplModuleName,ModuleName)->
- ets:insert(?PROVIDER_IMPL_TABLE,{Interface,ImplModuleName,ModuleName}),
+register_impl_provider(Interface, ImplModuleName, ModuleName) ->
+ ets:insert(?PROVIDER_IMPL_TABLE, {Interface, ImplModuleName, ModuleName}),
ok.
--spec select_impl_provider(Interface::binary()) ->{ok,binary()} | {error,term()}.
+-spec select_impl_provider(Interface :: binary()) -> {ok, binary()} | {error, term()}.
select_impl_provider(Interface) ->
- case ets:lookup(?PROVIDER_IMPL_TABLE,Interface) of
- []->
- {error,no_provider};
- [{Interface,ImplModuleName,ModuleName}] ->
- {ok,ImplModuleName}
+ case ets:lookup(?PROVIDER_IMPL_TABLE, Interface) of
+ [] ->
+ {error, no_provider};
+ [{Interface, ImplModuleName, ModuleName}] ->
+ {ok, ImplModuleName}
end.
-
%%%=================================================================
%%% 接收数据处理
%%%=================================================================
--spec check_recv_data(Data::binary(),State::#state{})->{ready,ReadyData::binary()} | {ready,ReadyData::binary(),NextBuffer::binary()}.
-check_recv_data(<<?DUBBO_MEGIC_HIGH,?DUBBO_MEGIC_LOW,Rest/binary>> = Data,State) when byte_size(Rest)<14 ->
- {next_buffer,Data,State};
-check_recv_data(<<?DUBBO_MEGIC_HIGH,?DUBBO_MEGIC_LOW,_OtherFlag:80,DataLen:32,Rest/binary>> = Data,State) ->
+-spec check_recv_data(Data :: binary(), State :: #state{}) -> {ready, ReadyData :: binary()} | {ready, ReadyData :: binary(), NextBuffer :: binary()}.
+check_recv_data(<<?DUBBO_MEGIC_HIGH, ?DUBBO_MEGIC_LOW, Rest/binary>> = Data, State) when byte_size(Rest) < 14 ->
+ {next_buffer, Data, State};
+check_recv_data(<<?DUBBO_MEGIC_HIGH, ?DUBBO_MEGIC_LOW, _OtherFlag:80, DataLen:32, Rest/binary>> = Data, State) ->
RestSize = byte_size(Rest),
if
- DataLen==RestSize ->
- {ok,State2} = process_data(Data,State),
- {next_buffer,<<>>,State2};
- DataLen>RestSize ->
- logger:warning("need wait next buffer data ~p",[Data]),
- {next_buffer,Data,State};
- DataLen<RestSize ->
- <<ReadyData:DataLen/binary,NextBuffer/binary>> = Rest,
- OneData = <<?DUBBO_MEGIC_HIGH:8,?DUBBO_MEGIC_LOW:8,_OtherFlag:80,DataLen:32,ReadyData/binary>>,
- {ok,State3} = process_data(OneData,State),
- logger:warning("recevi more data ~w ",[NextBuffer]),
- check_recv_data(NextBuffer,State3)
+ DataLen == RestSize ->
+ {ok, State2} = process_data(Data, State),
+ {next_buffer, <<>>, State2};
+ DataLen > RestSize ->
+ logger:warning("need wait next buffer data ~p", [Data]),
+ {next_buffer, Data, State};
+ DataLen < RestSize ->
+ <<ReadyData:DataLen/binary, NextBuffer/binary>> = Rest,
+ OneData = <<?DUBBO_MEGIC_HIGH:8, ?DUBBO_MEGIC_LOW:8, _OtherFlag:80, DataLen:32, ReadyData/binary>>,
+ {ok, State3} = process_data(OneData, State),
+ logger:warning("recevi more data ~w ", [NextBuffer]),
+ check_recv_data(NextBuffer, State3)
end;
-check_recv_data(<<Error/integer,Data/binary>>,State)->
- logger:error("recv bad header data,Begin Byte:~p",[Error]),
- check_recv_data(Data,State);
-check_recv_data(<<>>,State)->
- {next_buffer,<<>>,State}.
+check_recv_data(<<Error/integer, Data/binary>>, State) ->
+ logger:error("recv bad header data,Begin Byte:~p", [Error]),
+ check_recv_data(Data, State);
+check_recv_data(<<>>, State) ->
+ {next_buffer, <<>>, State}.
-process_data(Data,State)->
- <<Header:16/binary,RestData/binary>> = Data,
+process_data(Data, State) ->
+ <<Header:16/binary, RestData/binary>> = Data,
case dubbo_codec:decode_header(Header) of
- {ok,request,RequestInfo}->
- {ok,Req} = dubbo_codec:decode_request(RequestInfo,RestData),
- logger:info("get one request mid ~p, is_event ~p",[Req#dubbo_request.mid,Req#dubbo_request.is_event]),
- {ok,State2} = process_request(Req#dubbo_request.is_event,Req,State),
- {ok,State2};
- {ok,response,ResponseInfo}->
- {ok,Res} = dubbo_codec:decode_response(ResponseInfo,RestData),
- logger:info("get one response mid ~p, is_event ~p state ~p",[Res#dubbo_response.mid,Res#dubbo_response.is_event,Res#dubbo_response.state]),
- {ok,State3} =process_response(Res#dubbo_response.is_event,Res,State),
- {ok,State3};
- {error,Type,RelData}->
- logger:error("process_data error type ~p RelData ~p",[Type,RelData]),
- {ok,State}
+ {ok, request, RequestInfo} ->
+ {ok, Req} = dubbo_codec:decode_request(RequestInfo, RestData),
+ logger:info("get one request mid ~p, is_event ~p", [Req#dubbo_request.mid, Req#dubbo_request.is_event]),
+ {ok, State2} = process_request(Req#dubbo_request.is_event, Req, State),
+ {ok, State2};
+ {ok, response, ResponseInfo} ->
+ {ok, Res} = dubbo_codec:decode_response(ResponseInfo, RestData),
+ logger:info("get one response mid ~p, is_event ~p state ~p", [Res#dubbo_response.mid, Res#dubbo_response.is_event, Res#dubbo_response.state]),
+ {ok, State3} = process_response(Res#dubbo_response.is_event, Res, State),
+ {ok, State3};
+ {error, Type, RelData} ->
+ logger:error("process_data error type ~p RelData ~p", [Type, RelData]),
+ {ok, State}
end.
%% @doc process event
--spec process_response(IsEvent::boolean(),#dubbo_response{},#state{})->ok.
-process_response(true,Response,State)->
+-spec process_response(IsEvent :: boolean(), #dubbo_response{}, #state{}) -> ok.
+process_response(true, Response, State) ->
%%
- {ok,State};
+ {ok, State};
-process_response(false,Response,State)->
+process_response(false, Response, State) ->
%% case get_earse_request_info(Response#dubbo_response.mid) of
%% undefined->
%% logger:error("dubbo response can't find request data,response ~p",[Response]);
@@ -186,13 +192,13 @@
%% ResponseData = de_type_transfer:response_to_native(Response),
%% gen_server:cast(SourcePid,{msg_back,Ref,ResponseData,RpcContent})
%% end,
- {ok,State}.
+ {ok, State}.
-process_request(true,Request,State)->
+process_request(true, Request, State) ->
%% {ok,NewState} = send_heartbeat_msg(Request#dubbo_request.mid,State),
- logger:debug("process request event ~p",[Request]),
- {ok,State};
-process_request(false,Request,State)->
- logger:info("process request ~p",[Request]),
- dubbo_provider_worker:process_request(Request,self()),
- {ok,State}.
\ No newline at end of file
+ logger:debug("process request event ~p", [Request]),
+ {ok, State};
+process_request(false, Request, State) ->
+ logger:info("process request ~p", [Request]),
+ dubbo_provider_worker:process_request(Request, self()),
+ {ok, State}.
\ No newline at end of file
diff --git a/src/dubbo_provider_worker.erl b/src/dubbo_provider_worker.erl
index f857a91..25120a7 100644
--- a/src/dubbo_provider_worker.erl
+++ b/src/dubbo_provider_worker.erl
@@ -1,18 +1,25 @@
-%%%-------------------------------------------------------------------
-%%% @author dlive
-%%% @copyright (C) 2018, <COMPANY>
-%%% @doc
-%%%
-%%% @end
-%%% Created : 11. Mar 2018 8:08 PM
-%%%-------------------------------------------------------------------
+%%------------------------------------------------------------------------------
+%% Licensed to the Apache Software Foundation (ASF) under one or more
+%% contributor license agreements. See the NOTICE file distributed with
+%% this work for additional information regarding copyright ownership.
+%% The ASF licenses this file to You under the Apache License, Version 2.0
+%% (the "License"); you may not use this file except in compliance with
+%% the License. You may obtain a copy of the License at
+%%
+%% http://www.apache.org/licenses/LICENSE-2.0
+%%
+%% Unless required by applicable law or agreed to in writing, software
+%% distributed under the License is distributed on an "AS IS" BASIS,
+%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+%% See the License for the specific language governing permissions and
+%% limitations under the License.
+%%------------------------------------------------------------------------------
-module(dubbo_provider_worker).
--author("dlive").
-behaviour(gen_server).
%% API
--export([start_link/1,process_request/2]).
+-export([start_link/1, process_request/2]).
%% gen_server callbacks
-export([init/1,
@@ -27,10 +34,10 @@
-include("dubboerl.hrl").
-include("dubbo_type.hrl").
--record(heartbeat,{last_write=0,last_read=0,timeout=50000,max_timeout=9000}).
--record(state, {provider_config,socket =undefined,
- heartbeat=#heartbeat{},
- recv_buffer= <<>> %%从客户端接收的数据
+-record(heartbeat, {last_write = 0, last_read = 0, timeout = 50000, max_timeout = 9000}).
+-record(state, {provider_config, socket = undefined,
+ heartbeat = #heartbeat{},
+ recv_buffer = <<>> %%从客户端接收的数据
}).
%%%===================================================================
@@ -99,14 +106,14 @@
{noreply, NewState :: #state{}} |
{noreply, NewState :: #state{}, timeout() | hibernate} |
{stop, Reason :: term(), NewState :: #state{}}).
-handle_cast({request,Request,SourcePid},State)->
+handle_cast({request, Request, SourcePid}, State) ->
%% #dubbo_request{mid=Mid} = Request,
%% Data = #databaseOperateResponse{databaseOperateRsp = "ha-ha"},
%% Data2 =#dubbo_rpc_invocation{parameters = [Data]},
%% {ok,Content }= de_codec:encode_response(#dubbo_response{mid=Mid,is_event = false,data= Data2}),
- {ok,Content} = invoker_implement(Request),
- gen_server:cast(SourcePid,{send_response,Content}),
+ {ok, Content} = invoker_implement(Request),
+ gen_server:cast(SourcePid, {send_response, Content}),
{noreply, State};
handle_cast(_Request, State) ->
@@ -162,10 +169,10 @@
{ok, State}.
-process_request(Request,SourcePid)->
+process_request(Request, SourcePid) ->
Worker = poolboy:checkout(?PROVIDER_WORKER),
try
- gen_server:cast(Worker,{request,Request,SourcePid})
+ gen_server:cast(Worker, {request, Request, SourcePid})
after
ok = poolboy:checkin(?PROVIDER_WORKER, Worker)
end.
@@ -174,30 +181,30 @@
%%% Internal functions
%%%===================================================================
--spec invoker_implement(#dubbo_request{})-> {ok,response_content()}.
-invoker_implement(Request)->
- #dubbo_rpc_invocation{className = Interface,methodName = MethodName,parameters = Parameters} = Request#dubbo_request.data,
+-spec invoker_implement(#dubbo_request{}) -> {ok, response_content()}.
+invoker_implement(Request) ->
+ #dubbo_rpc_invocation{className = Interface, methodName = MethodName, parameters = Parameters} = Request#dubbo_request.data,
case dubbo_provider_protocol:select_impl_provider(Interface) of
- {ok,ImplModule}->
- case apply(ImplModule,binary_to_atom(MethodName,latin1),Parameters) of
- {error}->
+ {ok, ImplModule} ->
+ case apply(ImplModule, binary_to_atom(MethodName, latin1), Parameters) of
+ {error} ->
ok;
- #dubbo_rpc_invocation{}=ResultInvoca ->
+ #dubbo_rpc_invocation{} = ResultInvoca ->
#dubbo_request{mid = Mid} = Request,
- {ok,Content }=
+ {ok, Content} =
dubbo_codec:encode_response(#dubbo_response{
serialize_type = Request#dubbo_request.serialize_type,
- mid=Mid,
+ mid = Mid,
is_event = false,
- data= ResultInvoca}),
- {ok,Content};
- ResultObj->
+ data = ResultInvoca}),
+ {ok, Content};
+ ResultObj ->
%% Data = #databaseOperateResponse{databaseOperateRsp = "ha-ha"},
#dubbo_request{mid = Mid} = Request,
- Data2 =#dubbo_rpc_invocation{parameters = [ResultObj]},
- {ok,Content }= dubbo_codec:encode_response(#dubbo_response{serialize_type = Request#dubbo_request.serialize_type,mid=Mid,is_event = false,data= Data2}),
- {ok,Content}
+ Data2 = #dubbo_rpc_invocation{parameters = [ResultObj]},
+ {ok, Content} = dubbo_codec:encode_response(#dubbo_response{serialize_type = Request#dubbo_request.serialize_type, mid = Mid, is_event = false, data = Data2}),
+ {ok, Content}
end;
- {error,Reason} ->
- {error,Reason}
+ {error, Reason} ->
+ {error, Reason}
end.
\ No newline at end of file
diff --git a/src/dubbo_provider_worker_sup.erl b/src/dubbo_provider_worker_sup.erl
index 0b5708f..3f68ca5 100644
--- a/src/dubbo_provider_worker_sup.erl
+++ b/src/dubbo_provider_worker_sup.erl
@@ -1,13 +1,20 @@
-%%%-------------------------------------------------------------------
-%%% @author dlive
-%%% @copyright (C) 2018, <COMPANY>
-%%% @doc
-%%%
-%%% @end
-%%% Created : 11. Mar 2018 8:04 PM
-%%%-------------------------------------------------------------------
+%%------------------------------------------------------------------------------
+%% Licensed to the Apache Software Foundation (ASF) under one or more
+%% contributor license agreements. See the NOTICE file distributed with
+%% this work for additional information regarding copyright ownership.
+%% The ASF licenses this file to You under the Apache License, Version 2.0
+%% (the "License"); you may not use this file except in compliance with
+%% the License. You may obtain a copy of the License at
+%%
+%% http://www.apache.org/licenses/LICENSE-2.0
+%%
+%% Unless required by applicable law or agreed to in writing, software
+%% distributed under the License is distributed on an "AS IS" BASIS,
+%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+%% See the License for the specific language governing permissions and
+%% limitations under the License.
+%%------------------------------------------------------------------------------
-module(dubbo_provider_worker_sup).
--author("dlive").
-behaviour(supervisor).
diff --git a/src/dubbo_serializa_hessian.erl b/src/dubbo_serializa_hessian.erl
index 927bc82..d1d4f47 100644
--- a/src/dubbo_serializa_hessian.erl
+++ b/src/dubbo_serializa_hessian.erl
@@ -1,42 +1,49 @@
-%%%-------------------------------------------------------------------
-%%% @author dlive
-%%% @copyright (C) 2018, <COMPANY>
-%%% @doc
-%%%
-%%% @end
-%%% Created : 11. May 2018 4:12 PM
-%%%-------------------------------------------------------------------
+%%------------------------------------------------------------------------------
+%% Licensed to the Apache Software Foundation (ASF) under one or more
+%% contributor license agreements. See the NOTICE file distributed with
+%% this work for additional information regarding copyright ownership.
+%% The ASF licenses this file to You under the Apache License, Version 2.0
+%% (the "License"); you may not use this file except in compliance with
+%% the License. You may obtain a copy of the License at
+%%
+%% http://www.apache.org/licenses/LICENSE-2.0
+%%
+%% Unless required by applicable law or agreed to in writing, software
+%% distributed under the License is distributed on an "AS IS" BASIS,
+%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+%% See the License for the specific language governing permissions and
+%% limitations under the License.
+%%------------------------------------------------------------------------------
-module(dubbo_serializa_hessian).
--author("dlive").
-include("dubbo.hrl").
%% API
-export([decode_header/1]).
-export([decode_response/2]).
-export([decode_request/2]).
--export([encode_request_data/1,encode_response_data/1]).
+-export([encode_request_data/1, encode_response_data/1]).
-encode_request_data(Request)->
- State=type_encoding:init(),
- DataType =case Request#dubbo_request.is_event of
- true->
- dubbo_event;
- false->
- case Request#dubbo_request.data of
- #dubbo_rpc_invocation{} ->
- dubbo_rpc_invocation;
- _ ->
- unknow
- end
- end,
- {ok,Bin} = encode_request_data(DataType,Request,Request#dubbo_request.data,State),
- {ok,Bin}.
+encode_request_data(Request) ->
+ State = type_encoding:init(),
+ DataType = case Request#dubbo_request.is_event of
+ true ->
+ dubbo_event;
+ false ->
+ case Request#dubbo_request.data of
+ #dubbo_rpc_invocation{} ->
+ dubbo_rpc_invocation;
+ _ ->
+ unknow
+ end
+ end,
+ {ok, Bin} = encode_request_data(DataType, Request, Request#dubbo_request.data, State),
+ {ok, Bin}.
-encode_request_data(dubbo_event,_Request,Data,State) ->
- Bin = cotton_hessian:encode(Data,State),
- {ok,Bin};
-encode_request_data(dubbo_rpc_invocation,_Request,Data,State) ->
+encode_request_data(dubbo_event, _Request, Data, State) ->
+ Bin = cotton_hessian:encode(Data, State),
+ {ok, Bin};
+encode_request_data(dubbo_rpc_invocation, _Request, Data, State) ->
METHOD_NAME = Data#dubbo_rpc_invocation.methodName,
METHOD_ARGS_TYPES = Data#dubbo_rpc_invocation.parameterDesc,
RequestList = [
@@ -46,83 +53,83 @@
cotton_hessian:encode(METHOD_NAME, State),
cotton_hessian:encode(METHOD_ARGS_TYPES, State)
],
- {ArgsBin,State2} = encode_arguments(Data,State),
+ {ArgsBin, State2} = encode_arguments(Data, State),
AttachDict = dict:from_list(Data#dubbo_rpc_invocation.attachments),
- AttachMaps = #map{dict = AttachDict },
- {AttachBinay,_} = cotton_hessian:encode(AttachMaps, State2),
- RequestData = erlang:iolist_to_binary(RequestList ++ [ArgsBin,AttachBinay]),
- {ok,RequestData}.
+ AttachMaps = #map{dict = AttachDict},
+ {AttachBinay, _} = cotton_hessian:encode(AttachMaps, State2),
+ RequestData = erlang:iolist_to_binary(RequestList ++ [ArgsBin, AttachBinay]),
+ {ok, RequestData}.
-encode_response_data(Response)->
- State=type_encoding:init(),
- DataType =case Response#dubbo_response.is_event of
- true->
- dubbo_event;
- false->
- case Response#dubbo_response.data of
- #dubbo_rpc_invocation{} ->
- dubbo_rpc_invocation;
- _ ->
- unknow
- end
- end,
- {ok,Bin} = encode_response_data(DataType,Response,Response#dubbo_response.data,State),
- {ok,Bin}.
+encode_response_data(Response) ->
+ State = type_encoding:init(),
+ DataType = case Response#dubbo_response.is_event of
+ true ->
+ dubbo_event;
+ false ->
+ case Response#dubbo_response.data of
+ #dubbo_rpc_invocation{} ->
+ dubbo_rpc_invocation;
+ _ ->
+ unknow
+ end
+ end,
+ {ok, Bin} = encode_response_data(DataType, Response, Response#dubbo_response.data, State),
+ {ok, Bin}.
-encode_response_data(dubbo_event,_Response,Data,State) ->
- Bin = cotton_hessian:encode(Data,State),
- {ok,Bin};
-encode_response_data(dubbo_rpc_invocation,_Response,Data,State) ->
+encode_response_data(dubbo_event, _Response, Data, State) ->
+ Bin = cotton_hessian:encode(Data, State),
+ {ok, Bin};
+encode_response_data(dubbo_rpc_invocation, _Response, Data, State) ->
Result = case Data of
null ->
[
cotton_hessian:encode(?RESPONSE_NULL_VALUE, State)
];
_ ->
- {ArgsBin,_State2} = encode_arguments(Data,State),
+ {ArgsBin, _State2} = encode_arguments(Data, State),
[
cotton_hessian:encode(?RESPONSE_VALUE, State),
ArgsBin
]
end,
ResponseData = erlang:iolist_to_binary(Result),
- {ok,ResponseData}.
+ {ok, ResponseData}.
-encode_arguments(Data,State)->
- {StateNew} = lists:foldl(fun(X,{StateTmp})->
- StateTmpNew = type_encoding:enlist(X,StateTmp),
+encode_arguments(Data, State) ->
+ {StateNew} = lists:foldl(fun(X, {StateTmp}) ->
+ StateTmpNew = type_encoding:enlist(X, StateTmp),
{StateTmpNew} end,
- {State},Data#dubbo_rpc_invocation.parameterTypes),
- {Bin,State2} = lists:foldl(fun(X,{BinTmp,StateTmp2})->
+ {State}, Data#dubbo_rpc_invocation.parameterTypes),
+ {Bin, State2} = lists:foldl(fun(X, {BinTmp, StateTmp2}) ->
case cotton_hessian:encode(X, StateTmp2) of
- {ArgsBin,StateTmpNew} ->
- {<<BinTmp/binary,ArgsBin/binary>>, StateTmpNew};
+ {ArgsBin, StateTmpNew} ->
+ {<<BinTmp/binary, ArgsBin/binary>>, StateTmpNew};
ArgsBin2 ->
- {<<BinTmp/binary,ArgsBin2/binary>>, StateTmp2}
+ {<<BinTmp/binary, ArgsBin2/binary>>, StateTmp2}
end end,
- {<<>>,StateNew},Data#dubbo_rpc_invocation.parameters),
- {Bin,State2}.
+ {<<>>, StateNew}, Data#dubbo_rpc_invocation.parameters),
+ {Bin, State2}.
--spec decode_header(binary())-> {State::ok|error,Type::request|response,Data::#dubbo_response{}|#dubbo_request{}}.
-decode_header(Header)->
- <<?DUBBO_MEGIC_HIGH,?DUBBO_MEGIC_LOW,Flag:8,State:8,Mid:64,DataLen:32>> = Header,
+-spec decode_header(binary()) -> {State :: ok|error, Type :: request|response, Data :: #dubbo_response{}|#dubbo_request{}}.
+decode_header(Header) ->
+ <<?DUBBO_MEGIC_HIGH, ?DUBBO_MEGIC_LOW, Flag:8, State:8, Mid:64, DataLen:32>> = Header,
if
(Flag band 16#80) == 0 ->
- {DecodeState,Res} = decode_header(response,Flag,State,Mid,DataLen),
- {DecodeState,response,Res};
+ {DecodeState, Res} = decode_header(response, Flag, State, Mid, DataLen),
+ {DecodeState, response, Res};
true ->
- {DecodeState,Req} = decode_header(request,Flag,State,Mid,DataLen),
- {DecodeState,request,Req}
+ {DecodeState, Req} = decode_header(request, Flag, State, Mid, DataLen),
+ {DecodeState, request, Req}
end.
-decode_header(request,Flag,State,Mid,DataLen)->
+decode_header(request, Flag, State, Mid, DataLen) ->
SerializeType = Flag band 16#1f,
IsTwoWay = if
- (Flag band 16#40) /=0 -> true;
+ (Flag band 16#40) /= 0 -> true;
true -> false
end,
IsEvent = if
- (Flag band 16#20) /=0 -> true;
+ (Flag band 16#20) /= 0 -> true;
true -> false
end,
Req = #dubbo_request{
@@ -132,8 +139,8 @@
mversion = <<"2.0.0">>,
serialize_type = SerializeType
},
- {ok,Req};
-decode_header(response,Flag,State,Mid,DataLen)->
+ {ok, Req};
+decode_header(response, Flag, State, Mid, DataLen) ->
SerializeType = Flag band 16#1f,
IsEvent = if
(Flag band 16#20) /= 0 -> true;
@@ -144,50 +151,50 @@
state = State,
mid = Mid
},
- {ok,Res}.
+ {ok, Res}.
--spec decode_response(#dubbo_response{},binary())-> {ok,#dubbo_response{}}.
-decode_response(Res,Data)->
+-spec decode_response(#dubbo_response{}, binary()) -> {ok, #dubbo_response{}}.
+decode_response(Res, Data) ->
if
Res#dubbo_response.is_event == true ->
- decode_response(dubbo_event,Res,Data);
+ decode_response(dubbo_event, Res, Data);
true ->
- decode_response(dubbo_rpc_invocation,Res,Data)
+ decode_response(dubbo_rpc_invocation, Res, Data)
end.
-decode_response(dubbo_rpc_invocation,Res,Data)->
- {Rest,Type,State} = cotton_hessian:decode(Data,cotton_hessian:init()),
+decode_response(dubbo_rpc_invocation, Res, Data) ->
+ {Rest, Type, State} = cotton_hessian:decode(Data, cotton_hessian:init()),
case Type of
1 ->
- {_,Object,DecodeState} = cotton_hessian:decode(Rest,State),
- {ok,Res#dubbo_response{data = Object,decode_state = DecodeState}};
+ {_, Object, DecodeState} = cotton_hessian:decode(Rest, State),
+ {ok, Res#dubbo_response{data = Object, decode_state = DecodeState}};
2 ->
- {ok,Res#dubbo_response{data = null,decode_state = State}};
- _->
- logger:warning("decode unkonw type ~p ~p",[Type,Rest]),
- {Rest2,Object2,DecodeState2} = cotton_hessian:decode(Rest,State),
- logger:warning("decode unkonw type2 ~p ~p",[Object2,Rest2]),
- {ok,Res#dubbo_response{data = Object2,decode_state = DecodeState2}}
+ {ok, Res#dubbo_response{data = null, decode_state = State}};
+ _ ->
+ logger:warning("decode unkonw type ~p ~p", [Type, Rest]),
+ {Rest2, Object2, DecodeState2} = cotton_hessian:decode(Rest, State),
+ logger:warning("decode unkonw type2 ~p ~p", [Object2, Rest2]),
+ {ok, Res#dubbo_response{data = Object2, decode_state = DecodeState2}}
end;
-decode_response(dubbo_event,Res,Data)->
- {_Rest,undefined,_NewState} = cotton_hessian:decode(Data,cotton_hessian:init()),
- {ok,Res#dubbo_response{data = undefined}}.
+decode_response(dubbo_event, Res, Data) ->
+ {_Rest, undefined, _NewState} = cotton_hessian:decode(Data, cotton_hessian:init()),
+ {ok, Res#dubbo_response{data = undefined}}.
--spec decode_request(#dubbo_request{},binary())-> {ok,#dubbo_request{}}.
-decode_request(Req,Data)->
+-spec decode_request(#dubbo_request{}, binary()) -> {ok, #dubbo_request{}}.
+decode_request(Req, Data) ->
if
Req#dubbo_request.is_event == true ->
- decode_request(dubbo_event,Req,Data);
+ decode_request(dubbo_event, Req, Data);
true ->
- decode_request(dubbo_rpc_invocation,Req,Data)
+ decode_request(dubbo_rpc_invocation, Req, Data)
end.
-decode_request(dubbo_rpc_invocation,Req,Data)->
- {ResultList,NewState,RestData} = decode_request_body(Data,cotton_hessian:init(),[dubbo,path,version,method_name,desc_and_args,attachments]),
- [DubboVersion,Path,Version,MethodName,Desc,ArgsObj,Attachments]=ResultList,
- RpcData = #dubbo_rpc_invocation{className = Path,classVersion = Version,methodName = MethodName,parameterDesc = Data,parameters = ArgsObj,attachments = Attachments},
+decode_request(dubbo_rpc_invocation, Req, Data) ->
+ {ResultList, NewState, RestData} = decode_request_body(Data, cotton_hessian:init(), [dubbo, path, version, method_name, desc_and_args, attachments]),
+ [DubboVersion, Path, Version, MethodName, Desc, ArgsObj, Attachments] = ResultList,
+ RpcData = #dubbo_rpc_invocation{className = Path, classVersion = Version, methodName = MethodName, parameterDesc = Data, parameters = ArgsObj, attachments = Attachments},
Req2 = Req#dubbo_request{data = RpcData},
- {ok,Req2};
+ {ok, Req2};
%% {Rest,Dubbo,State} = cotton_hessian:decode(Data,cotton_hessian:init()),
%% {Rest1,ClassName,State1} = cotton_hessian:decode(Data,State),
%% {Rest2,ClassName,State2} = cotton_hessian:decode(Rest1,State1),
@@ -203,42 +210,42 @@
%% logger:warning("decode unkonw type2 ~p ~p",[Object2,Rest2]),
%% {ok,Req#dubbo_request{data = Object2,decode_state = DecodeState2}}
%% end;
-decode_request(dubbo_event,Req,Data)->
- {_Rest,undefined,_NewState} = cotton_hessian:decode(Data,cotton_hessian:init()),
- {ok,Req#dubbo_request{data = undefined}}.
+decode_request(dubbo_event, Req, Data) ->
+ {_Rest, undefined, _NewState} = cotton_hessian:decode(Data, cotton_hessian:init()),
+ {ok, Req#dubbo_request{data = undefined}}.
-decode_request_body(Data,State,List)->
- {ResultList,NewState,RestData} = decode_request_body(List,Data,State,[]),
- {lists:reverse(ResultList),NewState,RestData}.
-decode_request_body([ParseType|List],Data,State,ResultList)
- when ParseType==dubbo;ParseType==path;ParseType==version;ParseType==method_name ->
- {Rest,Result,NewState } = cotton_hessian:decode(Data,State),
- decode_request_body(List,Rest,NewState, [Result] ++ ResultList);
-decode_request_body([desc_and_args| List],Data,State,ResultList)->
- {Rest,ParameterDesc,State1 } = cotton_hessian:decode(Data,State),
+decode_request_body(Data, State, List) ->
+ {ResultList, NewState, RestData} = decode_request_body(List, Data, State, []),
+ {lists:reverse(ResultList), NewState, RestData}.
+decode_request_body([ParseType | List], Data, State, ResultList)
+ when ParseType == dubbo;ParseType == path;ParseType == version;ParseType == method_name ->
+ {Rest, Result, NewState} = cotton_hessian:decode(Data, State),
+ decode_request_body(List, Rest, NewState, [Result] ++ ResultList);
+decode_request_body([desc_and_args | List], Data, State, ResultList) ->
+ {Rest, ParameterDesc, State1} = cotton_hessian:decode(Data, State),
if
size(ParameterDesc) == 0 ->
- decode_request_body(List,Rest,State1, [ [],[] ]++ ResultList);
+ decode_request_body(List, Rest, State1, [[], []] ++ ResultList);
true ->
- ParameterDescArray = binary:split(ParameterDesc,<<";">>),
- {ArgsObjList,NewState,RestData} = decode_request_body_args(ParameterDescArray,Rest,State1,[]),
- decode_request_body(List,RestData,NewState, [ArgsObjList,ParameterDesc]++ ResultList)
+ ParameterDescArray = binary:split(ParameterDesc, <<";">>),
+ {ArgsObjList, NewState, RestData} = decode_request_body_args(ParameterDescArray, Rest, State1, []),
+ decode_request_body(List, RestData, NewState, [ArgsObjList, ParameterDesc] ++ ResultList)
end;
-decode_request_body([attachments|List],Data,State,ResultList)->
- {Rest,Attachments,State1 } = cotton_hessian:decode(Data,State),
+decode_request_body([attachments | List], Data, State, ResultList) ->
+ {Rest, Attachments, State1} = cotton_hessian:decode(Data, State),
AttachmentsList = dict:to_list(Attachments#map.dict),
- decode_request_body(List,Rest,State1,[AttachmentsList] ++ ResultList);
-decode_request_body([_Type1|List],Data,State,ResultList)->
+ decode_request_body(List, Rest, State1, [AttachmentsList] ++ ResultList);
+decode_request_body([_Type1 | List], Data, State, ResultList) ->
logger:warning("decode_request_body unknow type"),
- decode_request_body(List,Data,State, ResultList);
-decode_request_body([],Data,State,ResultList)->
- {ResultList,State,Data}.
+ decode_request_body(List, Data, State, ResultList);
+decode_request_body([], Data, State, ResultList) ->
+ {ResultList, State, Data}.
-decode_request_body_args([],Data,State,ArgsObjList)->
- {ArgsObjList,State,Data};
-decode_request_body_args([ArgsType|RestList],Data,State,ArgsObjList) when ArgsType== <<>> ->
- decode_request_body_args(RestList,Data,State,ArgsObjList);
-decode_request_body_args([_ArgsType|RestList],Data,State,ArgsObjList) ->
- {Rest,ArgObj,NewState } = cotton_hessian:decode(Data,State),
- ArgObj2 = dubbo_type_transfer:classobj_to_native(ArgObj,NewState),
- decode_request_body_args(RestList,Rest,NewState,ArgsObjList++[ArgObj2]).
\ No newline at end of file
+decode_request_body_args([], Data, State, ArgsObjList) ->
+ {ArgsObjList, State, Data};
+decode_request_body_args([ArgsType | RestList], Data, State, ArgsObjList) when ArgsType == <<>> ->
+ decode_request_body_args(RestList, Data, State, ArgsObjList);
+decode_request_body_args([_ArgsType | RestList], Data, State, ArgsObjList) ->
+ {Rest, ArgObj, NewState} = cotton_hessian:decode(Data, State),
+ ArgObj2 = dubbo_type_transfer:classobj_to_native(ArgObj, NewState),
+ decode_request_body_args(RestList, Rest, NewState, ArgsObjList ++ [ArgObj2]).
\ No newline at end of file
diff --git a/src/dubbo_serializa_json.erl b/src/dubbo_serializa_json.erl
index c7126b8..35a1079 100644
--- a/src/dubbo_serializa_json.erl
+++ b/src/dubbo_serializa_json.erl
@@ -1,32 +1,40 @@
-%%%-------------------------------------------------------------------
-%%% @author dlive
-%%% @copyright (C) 2018, <COMPANY>
-%%% @doc
-%%%
-%%% @end
-%%% Created : 11. May 2018 10:07 AM
-%%%-------------------------------------------------------------------
+%%------------------------------------------------------------------------------
+%% Licensed to the Apache Software Foundation (ASF) under one or more
+%% contributor license agreements. See the NOTICE file distributed with
+%% this work for additional information regarding copyright ownership.
+%% The ASF licenses this file to You under the Apache License, Version 2.0
+%% (the "License"); you may not use this file except in compliance with
+%% the License. You may obtain a copy of the License at
+%%
+%% http://www.apache.org/licenses/LICENSE-2.0
+%%
+%% Unless required by applicable law or agreed to in writing, software
+%% distributed under the License is distributed on an "AS IS" BASIS,
+%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+%% See the License for the specific language governing permissions and
+%% limitations under the License.
+%%------------------------------------------------------------------------------
-module(dubbo_serializa_json).
--author("dlive").
+
-include("dubbo.hrl").
%% API
--export([decode_response/2,decode_request/2,decode_header/1,decode_request/2]).
+-export([decode_response/2, decode_request/2, decode_header/1, decode_request/2]).
--export([encode_request_data/1,encode_response_data/1]).
+-export([encode_request_data/1, encode_response_data/1]).
-encode_request_data(Request)->
- DataType =case Request#dubbo_request.is_event of
- false->
- dubbo_rpc_invocation;
- true->
- dubbo_event
- end,
- {ok,Bin} = encode_request_data(DataType,Request,Request#dubbo_request.data,[]),
- {ok,Bin}.
+encode_request_data(Request) ->
+ DataType = case Request#dubbo_request.is_event of
+ false ->
+ dubbo_rpc_invocation;
+ true ->
+ dubbo_event
+ end,
+ {ok, Bin} = encode_request_data(DataType, Request, Request#dubbo_request.data, []),
+ {ok, Bin}.
-encode_request_data(dubbo_rpc_invocation,_Request,Data,State) ->
+encode_request_data(dubbo_rpc_invocation, _Request, Data, State) ->
RequestList = [
string_encode(?DUBBO_VERSION),
?LINE_SEPERATOR,
@@ -39,43 +47,43 @@
string_encode(Data#dubbo_rpc_invocation.parameterDesc),
?LINE_SEPERATOR
],
- {ArgsBin,_} = encode_arguments(Data,State),
- AttachBinay = jiffy:encode({Data#dubbo_rpc_invocation.attachments},[]),
- RequestData = erlang:iolist_to_binary(RequestList ++ [ArgsBin,AttachBinay,?LINE_SEPERATOR]),
- {ok,RequestData};
-encode_request_data(dubbo_event,_Request,Data,_State) ->
+ {ArgsBin, _} = encode_arguments(Data, State),
+ AttachBinay = jiffy:encode({Data#dubbo_rpc_invocation.attachments}, []),
+ RequestData = erlang:iolist_to_binary(RequestList ++ [ArgsBin, AttachBinay, ?LINE_SEPERATOR]),
+ {ok, RequestData};
+encode_request_data(dubbo_event, _Request, Data, _State) ->
%% @todo 确认该数据类型
- Bin = jiffy:encode(Data),
- {ok,Bin}.
+ Bin = jiffy:encode(Data),
+ {ok, Bin}.
-encode_response_data(Response)->
- State=#{},
- DataType =case Response#dubbo_response.is_event of
- true->
- dubbo_event;
- false->
- case Response#dubbo_response.data of
- #dubbo_rpc_invocation{} ->
- dubbo_rpc_invocation;
- _ ->
- unknow
- end
- end,
- {ok,Bin} = encode_response_data(DataType,Response,Response#dubbo_response.data,State),
- {ok,Bin}.
+encode_response_data(Response) ->
+ State = #{},
+ DataType = case Response#dubbo_response.is_event of
+ true ->
+ dubbo_event;
+ false ->
+ case Response#dubbo_response.data of
+ #dubbo_rpc_invocation{} ->
+ dubbo_rpc_invocation;
+ _ ->
+ unknow
+ end
+ end,
+ {ok, Bin} = encode_response_data(DataType, Response, Response#dubbo_response.data, State),
+ {ok, Bin}.
-encode_response_data(dubbo_event,_Response,Data,State) ->
- Bin = jiffy:encode(Data,[]),
- {ok,Bin};
-encode_response_data(dubbo_rpc_invocation,_Response,Data,State) ->
+encode_response_data(dubbo_event, _Response, Data, State) ->
+ Bin = jiffy:encode(Data, []),
+ {ok, Bin};
+encode_response_data(dubbo_rpc_invocation, _Response, Data, State) ->
Result = case Data of
null ->
[
string_encode(?RESPONSE_NULL_VALUE)
];
_ ->
- {ArgsBin,_State2} = encode_arguments(Data,State),
+ {ArgsBin, _State2} = encode_arguments(Data, State),
[
string_encode(?RESPONSE_VALUE),
?LINE_SEPERATOR,
@@ -83,36 +91,36 @@
]
end,
ResponseData = erlang:iolist_to_binary(Result),
- {ok,ResponseData}.
+ {ok, ResponseData}.
-encode_arguments(Data,State)->
+encode_arguments(Data, State) ->
{Bin} = lists:foldl(
- fun(X,{BinTmp})->
+ fun(X, {BinTmp}) ->
ArgsBin = string_encode(X),
- {<<BinTmp/binary,ArgsBin/binary ,?LINE_SEPERATOR/binary>>}
+ {<<BinTmp/binary, ArgsBin/binary, ?LINE_SEPERATOR/binary>>}
end,
- {<<>>},Data#dubbo_rpc_invocation.parameters),
- {Bin,State}.
+ {<<>>}, Data#dubbo_rpc_invocation.parameters),
+ {Bin, State}.
--spec decode_header(binary())-> {State::ok|error,Type::request|response,Data::#dubbo_response{}|#dubbo_request{}}.
-decode_header(Header)->
- <<?DUBBO_MEGIC_HIGH,?DUBBO_MEGIC_LOW,Flag:8,State:8,Mid:64,DataLen:32>> = Header,
+-spec decode_header(binary()) -> {State :: ok|error, Type :: request|response, Data :: #dubbo_response{}|#dubbo_request{}}.
+decode_header(Header) ->
+ <<?DUBBO_MEGIC_HIGH, ?DUBBO_MEGIC_LOW, Flag:8, State:8, Mid:64, DataLen:32>> = Header,
if
(Flag band 16#80) == 0 ->
- {DecodeState,Res} = decode_header(response,Flag,State,Mid,DataLen),
- {DecodeState,response,Res};
+ {DecodeState, Res} = decode_header(response, Flag, State, Mid, DataLen),
+ {DecodeState, response, Res};
true ->
- {DecodeState,Req} = decode_header(request,Flag,State,Mid,DataLen),
- {DecodeState,request,Req}
+ {DecodeState, Req} = decode_header(request, Flag, State, Mid, DataLen),
+ {DecodeState, request, Req}
end.
-decode_header(request,Flag,State,Mid,DataLen)->
+decode_header(request, Flag, State, Mid, DataLen) ->
SerializeType = Flag band 16#1f,
IsTwoWay = if
- (Flag band 16#40) /=0 -> true;
+ (Flag band 16#40) /= 0 -> true;
true -> false
end,
IsEvent = if
- (Flag band 16#20) /=0 -> true;
+ (Flag band 16#20) /= 0 -> true;
true -> false
end,
Req = #dubbo_request{
@@ -122,8 +130,8 @@
mversion = <<"2.0.0">>,
serialize_type = SerializeType
},
- {ok,Req};
-decode_header(response,Flag,State,Mid,DataLen)->
+ {ok, Req};
+decode_header(response, Flag, State, Mid, DataLen) ->
SerializeType = Flag band 16#1f,
IsEvent = if
(Flag band 16#20) /= 0 -> true;
@@ -134,18 +142,18 @@
state = State,
mid = Mid
},
- {ok,Res}.
+ {ok, Res}.
--spec decode_response(#dubbo_response{},binary())-> {ok,#dubbo_response{}}.
-decode_response(Res,Data)->
+-spec decode_response(#dubbo_response{}, binary()) -> {ok, #dubbo_response{}}.
+decode_response(Res, Data) ->
if
Res#dubbo_response.is_event == true ->
- decode_response(dubbo_event,Res,Data);
+ decode_response(dubbo_event, Res, Data);
true ->
- decode_response(dubbo_rpc_invocation,Res,Data)
+ decode_response(dubbo_rpc_invocation, Res, Data)
end.
-decode_response(dubbo_rpc_invocation,Res,Data)->
- DataList = binary:split(Data,<<"\n">>,[global]),
+decode_response(dubbo_rpc_invocation, Res, Data) ->
+ DataList = binary:split(Data, <<"\n">>, [global]),
[TypeBin | DataList1] = DataList,
%% {Rest,Type,State} = cotton_hessian:decode(Data,cotton_hessian:init()),
Type = jiffy:decode(TypeBin),
@@ -154,116 +162,116 @@
?RESPONSE_VALUE ->
%% {_,Object,DecodeState} = cotton_hessian:decode(Rest,State),
[Value | _] = DataList1,
- Object = jiffy:decode(Value,[return_maps]),
- {ok,Res#dubbo_response{data = Object}};
+ Object = jiffy:decode(Value, [return_maps]),
+ {ok, Res#dubbo_response{data = Object}};
?RESPONSE_NULL_VALUE ->
- {ok,Res#dubbo_response{data = null}};
+ {ok, Res#dubbo_response{data = null}};
?RESPONSE_WITH_EXCEPTION ->
[ExceptionValue | _] = DataList1,
ExceptionObject = jiffy:decode(ExceptionValue),
- {ok,Res#dubbo_response{data = ExceptionObject}};
+ {ok, Res#dubbo_response{data = ExceptionObject}};
Other ->
- logger:error("server response unkonw info ~p",[Other]),
- {ok,Res#dubbo_response{data = <<"server pool exhausted">>}}
+ logger:error("server response unkonw info ~p", [Other]),
+ {ok, Res#dubbo_response{data = <<"server pool exhausted">>}}
end;
-decode_response(dubbo_event,Res,Data)->
+decode_response(dubbo_event, Res, Data) ->
%% {_Rest,undefined,_NewState} = cotton_hessian:decode(Data,cotton_hessian:init()),
- {ok,Res#dubbo_response{data = null}}.
+ {ok, Res#dubbo_response{data = null}}.
--spec decode_request(#dubbo_request{},binary())-> {ok,#dubbo_request{}}.
-decode_request(Req,Data)->
+-spec decode_request(#dubbo_request{}, binary()) -> {ok, #dubbo_request{}}.
+decode_request(Req, Data) ->
if
Req#dubbo_request.is_event == true ->
- decode_request(dubbo_event,Req,Data);
+ decode_request(dubbo_event, Req, Data);
true ->
- decode_request(dubbo_rpc_invocation,Req,Data)
+ decode_request(dubbo_rpc_invocation, Req, Data)
end.
-decode_request(dubbo_rpc_invocation,Req,Data)->
- {ResultList,NewState,RestData} = decode_request_body(Data,#{},[dubbo,path,version,method_name,desc_and_args,attachments]),
- [DubboVersion,Path,Version,MethodName,Desc,ArgsObj,Attachments]=ResultList,
- RpcData = #dubbo_rpc_invocation{className = Path,classVersion = Version,methodName = MethodName,parameterDesc = Desc,parameters = ArgsObj,attachments = Attachments},
+decode_request(dubbo_rpc_invocation, Req, Data) ->
+ {ResultList, NewState, RestData} = decode_request_body(Data, #{}, [dubbo, path, version, method_name, desc_and_args, attachments]),
+ [DubboVersion, Path, Version, MethodName, Desc, ArgsObj, Attachments] = ResultList,
+ RpcData = #dubbo_rpc_invocation{className = Path, classVersion = Version, methodName = MethodName, parameterDesc = Desc, parameters = ArgsObj, attachments = Attachments},
Req2 = Req#dubbo_request{data = RpcData},
- {ok,Req2};
+ {ok, Req2};
-decode_request(dubbo_event,Req,Data)->
+decode_request(dubbo_event, Req, Data) ->
%% DataList = binary:split(Data,<<"\n">>),
- logger:debug("dubbo_event datalist ~w",[Data]),
- Result = jiffy:decode(Data,[]),
+ logger:debug("dubbo_event datalist ~w", [Data]),
+ Result = jiffy:decode(Data, []),
%% {_Rest,undefined,_NewState} = cotton_hessian:decode(Data,cotton_hessian:init()),
- {ok,Req#dubbo_request{data = Result}}.
+ {ok, Req#dubbo_request{data = Result}}.
-decode_request_body(Data,State,List)->
- logger:debug("decode_request_body origin data ~p",[Data]),
- DataList = binary:split(Data,<<"\n">>,[global]),
+decode_request_body(Data, State, List) ->
+ logger:debug("decode_request_body origin data ~p", [Data]),
+ DataList = binary:split(Data, <<"\n">>, [global]),
if
- length(DataList) <6 ->
- {error,request_data_error};
+ length(DataList) < 6 ->
+ {error, request_data_error};
true ->
- {ResultList,NewState,RestData} = decode_request_body(List,DataList,State,[]),
- {lists:reverse(ResultList),NewState,RestData}
+ {ResultList, NewState, RestData} = decode_request_body(List, DataList, State, []),
+ {lists:reverse(ResultList), NewState, RestData}
end.
-decode_request_body([ParseType|List],[DataItem | Data],State,ResultList)
- when ParseType==dubbo;ParseType==path;ParseType==version;ParseType==method_name ->
- DecodeData = jiffy:decode(DataItem,[return_maps]),
- decode_request_body(List,Data,State, [DecodeData] ++ ResultList);
+decode_request_body([ParseType | List], [DataItem | Data], State, ResultList)
+ when ParseType == dubbo;ParseType == path;ParseType == version;ParseType == method_name ->
+ DecodeData = jiffy:decode(DataItem, [return_maps]),
+ decode_request_body(List, Data, State, [DecodeData] ++ ResultList);
-decode_request_body([desc_and_args| List],[DescBin|Data],State,ResultList)->
- ParameterDesc = jiffy:decode(DescBin,[]),
+decode_request_body([desc_and_args | List], [DescBin | Data], State, ResultList) ->
+ ParameterDesc = jiffy:decode(DescBin, []),
%% {Rest,ParameterDesc,State1 } = cotton_hessian:decode(Data,State),
if
size(ParameterDesc) == 0 ->
- decode_request_body(List,Data,State, [ [],[] ]++ ResultList);
+ decode_request_body(List, Data, State, [[], []] ++ ResultList);
true ->
- ParameterDescArray = binary:split(ParameterDesc,<<";">>),
- {ArgsObjList,NewState,RestData} = decode_request_body_args(ParameterDescArray,Data,State,[]),
- decode_request_body(List,RestData,NewState, [ArgsObjList,ParameterDesc]++ ResultList)
+ ParameterDescArray = binary:split(ParameterDesc, <<";">>),
+ {ArgsObjList, NewState, RestData} = decode_request_body_args(ParameterDescArray, Data, State, []),
+ decode_request_body(List, RestData, NewState, [ArgsObjList, ParameterDesc] ++ ResultList)
end;
-decode_request_body([attachments|List],[DataItem|Data],State,ResultList)->
- Attachments = jiffy:decode(DataItem,[return_maps]),
+decode_request_body([attachments | List], [DataItem | Data], State, ResultList) ->
+ Attachments = jiffy:decode(DataItem, [return_maps]),
%% AttachmentsList = dict:to_list(Attachments#map.dict),
- decode_request_body(List,Data,State,[Attachments] ++ ResultList);
-decode_request_body([_Type1|List],Data,State,ResultList)->
+ decode_request_body(List, Data, State, [Attachments] ++ ResultList);
+decode_request_body([_Type1 | List], Data, State, ResultList) ->
logger:warning("decode_request_body unknow type"),
- decode_request_body(List,Data,State, ResultList);
-decode_request_body([],Data,State,ResultList)->
- {ResultList,State,Data}.
+ decode_request_body(List, Data, State, ResultList);
+decode_request_body([], Data, State, ResultList) ->
+ {ResultList, State, Data}.
-decode_request_body_args([],Data,State,ArgsObjList)->
- {ArgsObjList,State,Data};
+decode_request_body_args([], Data, State, ArgsObjList) ->
+ {ArgsObjList, State, Data};
-decode_request_body_args([ArgsType|RestList],Data,State,ArgsObjList) when ArgsType== <<>> ->
- decode_request_body_args(RestList,Data,State,ArgsObjList);
+decode_request_body_args([ArgsType | RestList], Data, State, ArgsObjList) when ArgsType == <<>> ->
+ decode_request_body_args(RestList, Data, State, ArgsObjList);
-decode_request_body_args([ArgsType|RestList],[DataItem |Data],State,ArgsObjList) ->
- ArgObj = jiffy:decode(DataItem,[return_maps]),
+decode_request_body_args([ArgsType | RestList], [DataItem | Data], State, ArgsObjList) ->
+ ArgObj = jiffy:decode(DataItem, [return_maps]),
%% {Rest,ArgObj,NewState } = cotton_hessian:decode(Data,State),
- ArgObj2 = dubbo_type_transfer:jsonobj_to_native(ArgsType,ArgObj,State),
- decode_request_body_args(RestList,Data,State,ArgsObjList++[ArgObj2]).
+ ArgObj2 = dubbo_type_transfer:jsonobj_to_native(ArgsType, ArgObj, State),
+ decode_request_body_args(RestList, Data, State, ArgsObjList ++ [ArgObj2]).
string_encode(Data) when is_binary(Data) ->
- << <<"\"">>/binary,Data/binary,<<"\"">>/binary >>;
+ <<<<"\"">>/binary, Data/binary, <<"\"">>/binary>>;
string_encode(Data) when is_tuple(Data) ->
- [Name |_] = tuple_to_list(Data),
+ [Name | _] = tuple_to_list(Data),
%% Size = record_info(size, Name),
%% Fields = record_info(fields, Name),
case type_register:lookup_native_type(Name) of
undefined ->
<<"data encode error">>;
- #type_def{fieldnames = Fields,foreign_type = _ForeignType} ->
- logger:debug("string_encode lookup ~p ret ~p",[Name,Fields]),
+ #type_def{fieldnames = Fields, foreign_type = _ForeignType} ->
+ logger:debug("string_encode lookup ~p ret ~p", [Name, Fields]),
MapValue = lists:foldl(
fun({I, E}, Acc) ->
Acc#{E => element(I, Data)}
- end, #{}, lists:zip(lists:seq(2, length(Fields)+1 ),Fields)),
+ end, #{}, lists:zip(lists:seq(2, length(Fields) + 1), Fields)),
jiffy:encode(MapValue)
end;
-string_encode(Data)->
+string_encode(Data) ->
jiffy:encode(Data).
diff --git a/src/dubbo_traffic_control.erl b/src/dubbo_traffic_control.erl
index a8bd010..0a75aa7 100644
--- a/src/dubbo_traffic_control.erl
+++ b/src/dubbo_traffic_control.erl
@@ -7,43 +7,42 @@
%%% Created : 22. May 2018 1:58 PM
%%%-------------------------------------------------------------------
-module(dubbo_traffic_control).
--author("dlive").
-include("dubboerl.hrl").
%% API
--export([init/0,check_goon/2,decr_count/1]).
+-export([init/0, check_goon/2, decr_count/1]).
-init()->
+init() ->
case ets:info(?TRAFFIC_CONTROL) of
undefined ->
- io:format("init decoding TRAFFIC_CONTROL table pid ~p~n",[self()]),
- ets:new(?TRAFFIC_CONTROL,[public,named_table, {write_concurrency, true}]); %% public
+ io:format("init decoding TRAFFIC_CONTROL table pid ~p~n", [self()]),
+ ets:new(?TRAFFIC_CONTROL, [public, named_table, {write_concurrency, true}]); %% public
_ ->
ets:delete(?TRAFFIC_CONTROL),
- ets:new(?TRAFFIC_CONTROL,[public,named_table, {write_concurrency, true}])
+ ets:new(?TRAFFIC_CONTROL, [public, named_table, {write_concurrency, true}])
end,
ok.
-check_goon(Key,Max)->
- try ets:update_counter(?TRAFFIC_CONTROL,Key,1) of
+check_goon(Key, Max) ->
+ try ets:update_counter(?TRAFFIC_CONTROL, Key, 1) of
Value when Value > Max ->
- ets:update_counter(?TRAFFIC_CONTROL,Key,-1),
+ ets:update_counter(?TRAFFIC_CONTROL, Key, -1),
full;
_V ->
ok
catch
- _T:_R->
- ets:insert(?TRAFFIC_CONTROL,{Key,1}),
+ _T:_R ->
+ ets:insert(?TRAFFIC_CONTROL, {Key, 1}),
ok
end.
-decr_count(Key)->
- try ets:update_counter(?TRAFFIC_CONTROL,Key,-1) of
+decr_count(Key) ->
+ try ets:update_counter(?TRAFFIC_CONTROL, Key, -1) of
_V ->
ok
catch
- _T:_R->
- ets:insert(?TRAFFIC_CONTROL,{Key,0}),
+ _T:_R ->
+ ets:insert(?TRAFFIC_CONTROL, {Key, 0}),
ok
end.
\ No newline at end of file
diff --git a/src/dubbo_type_transfer.erl b/src/dubbo_type_transfer.erl
index 27db68b..e67e493 100644
--- a/src/dubbo_type_transfer.erl
+++ b/src/dubbo_type_transfer.erl
@@ -7,86 +7,84 @@
%%% Created : 27. 十月 2016 下午8:28
%%%-------------------------------------------------------------------
-module(dubbo_type_transfer).
--author("dlive").
-
-include("hessian.hrl").
-include("dubbo.hrl").
%% API
--export([java_to_native/2,pre_process_typedef/3,response_to_native/1,classobj_to_native/2,jsonobj_to_native/3]).
+-export([java_to_native/2, pre_process_typedef/3, response_to_native/1, classobj_to_native/2, jsonobj_to_native/3]).
-response_to_native(Response)->
- java_to_native(Response#dubbo_response.data,Response#dubbo_response.decode_state).
+response_to_native(Response) ->
+ java_to_native(Response#dubbo_response.data, Response#dubbo_response.decode_state).
-classobj_to_native(Data,DecodeState)->
- java_to_native(Data,DecodeState).
+classobj_to_native(Data, DecodeState) ->
+ java_to_native(Data, DecodeState).
-java_to_native(#object{values = ForeignData}=Data,State)->
- ForeignDataNew = [java_to_native(ValueItem,State) || ValueItem <-ForeignData ],
+java_to_native(#object{values = ForeignData} = Data, State) ->
+ ForeignDataNew = [java_to_native(ValueItem, State) || ValueItem <- ForeignData],
- case cotton_hessian:get_deftype(Data#object.typeRef,State) of
- #type_def{fieldnames = ObjectFields,foreign_type = ForeignType } ->
+ case cotton_hessian:get_deftype(Data#object.typeRef, State) of
+ #type_def{fieldnames = ObjectFields, foreign_type = ForeignType} ->
case get_deftype(ForeignType) of
- false->
+ false ->
error;
- #type_def{fieldnames = NativeFields,native_type = NativeTupeName}->
- AsDict = dict:from_list(lists:zip(ObjectFields,ForeignDataNew)),
- NativeData = [dict:fetch(atom_to_binary(Key,utf8),AsDict) || Key <- NativeFields],
- list_to_tuple( [NativeTupeName] ++ NativeData)
+ #type_def{fieldnames = NativeFields, native_type = NativeTupeName} ->
+ AsDict = dict:from_list(lists:zip(ObjectFields, ForeignDataNew)),
+ NativeData = [dict:fetch(atom_to_binary(Key, utf8), AsDict) || Key <- NativeFields],
+ list_to_tuple([NativeTupeName] ++ NativeData)
end;
Info ->
- logger:warning("java_to_native error:~p",[Info]),
+ logger:warning("java_to_native error:~p", [Info]),
error
end;
-java_to_native(#list{values = ForeignData}=Data,State)->
- ForeignDataNew = [java_to_native(ValueItem,State) || ValueItem <-ForeignData ],
+java_to_native(#list{values = ForeignData} = Data, State) ->
+ ForeignDataNew = [java_to_native(ValueItem, State) || ValueItem <- ForeignData],
ForeignDataNew;
-java_to_native(Data,_)->
- logger:debug("java_to_native unkonw type ~p",[Data]),
+java_to_native(Data, _) ->
+ logger:debug("java_to_native unkonw type ~p", [Data]),
Data.
-get_deftype(ForeignType)->
+get_deftype(ForeignType) ->
case type_register:lookup_foreign_type(ForeignType) of
- undefined->
- logger:debug("get deftype undefined ~p",[ForeignType]),
+ undefined ->
+ logger:debug("get deftype undefined ~p", [ForeignType]),
false;
- #type_def{}=TypeDef->
- logger:debug("get deftype success ~p",[ForeignType]),
+ #type_def{} = TypeDef ->
+ logger:debug("get deftype success ~p", [ForeignType]),
TypeDef;
- _->
- logger:debug("get deftype undefined ~p",[ForeignType]),
+ _ ->
+ logger:debug("get deftype undefined ~p", [ForeignType]),
false
end.
-pre_process_typedef(NativeType,ForeignType,FieldsNames)->
- Type = #type_def{native_type = NativeType,foreign_type = ForeignType,fieldnames = FieldsNames},
+pre_process_typedef(NativeType, ForeignType, FieldsNames) ->
+ Type = #type_def{native_type = NativeType, foreign_type = ForeignType, fieldnames = FieldsNames},
%% Type2=type_decoding:hash_store(Type),
type_register:regiest_foreign_native(Type),
- logger:debug("pre_process_typedef ~p,~p",[NativeType,ForeignType]),
+ logger:debug("pre_process_typedef ~p,~p", [NativeType, ForeignType]),
ok.
-jsonobj_to_native(Type,JsonObj,State)->
+jsonobj_to_native(Type, JsonObj, State) ->
ClassName = java_desc_name_to_dot(Type),
%% todo need recursion transfer
case type_register:lookup_foreign_type(ClassName) of
undefined ->
JsonObj;
- #type_def{fieldnames = Fields,native_type = NativeType} ->
- logger:debug("jsonobj_to_native ~p ~p ~p",[ClassName,Fields,JsonObj]),
- NativeData = [ maps:get(atom_to_binary(Key,utf8),JsonObj,undefined) || Key <- Fields],
- list_to_tuple( [NativeType] ++ NativeData)
+ #type_def{fieldnames = Fields, native_type = NativeType} ->
+ logger:debug("jsonobj_to_native ~p ~p ~p", [ClassName, Fields, JsonObj]),
+ NativeData = [maps:get(atom_to_binary(Key, utf8), JsonObj, undefined) || Key <- Fields],
+ list_to_tuple([NativeType] ++ NativeData)
end.
java_desc_name_to_dot(DescName) ->
case DescName of
- <<$L,ClassName/binary>> ->
- binary:replace(ClassName,<<"/">>,<<".">>,[global]);
+ <<$L, ClassName/binary>> ->
+ binary:replace(ClassName, <<"/">>, <<".">>, [global]);
_ ->
DescName
end.
diff --git a/src/dubbo_zookeeper.erl b/src/dubbo_zookeeper.erl
index 8e1e96f..e6f500b 100644
--- a/src/dubbo_zookeeper.erl
+++ b/src/dubbo_zookeeper.erl
@@ -1,19 +1,25 @@
-%%%-------------------------------------------------------------------
-%%% @author dlive
-%%% @copyright (C) 2016, <COMPANY>
-%%% @doc
-%%%
-%%% @end
-%%% Created : 29. 十月 2016 上午9:56
-%%%-------------------------------------------------------------------
+%%------------------------------------------------------------------------------
+%% Licensed to the Apache Software Foundation (ASF) under one or more
+%% contributor license agreements. See the NOTICE file distributed with
+%% this work for additional information regarding copyright ownership.
+%% The ASF licenses this file to You under the Apache License, Version 2.0
+%% (the "License"); you may not use this file except in compliance with
+%% the License. You may obtain a copy of the License at
+%%
+%% http://www.apache.org/licenses/LICENSE-2.0
+%%
+%% Unless required by applicable law or agreed to in writing, software
+%% distributed under the License is distributed on an "AS IS" BASIS,
+%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+%% See the License for the specific language governing permissions and
+%% limitations under the License.
+%%------------------------------------------------------------------------------
-module(dubbo_zookeeper).
--author("dlive").
-
-behaviour(gen_server).
-include("dubbo.hrl").
%% API
--export([start_link/0,register_consumer/1,register_consumer/2,gen_consumer_node_info/1,register_provider/1,provider_watcher/1]).
+-export([start_link/0, register_consumer/1, register_consumer/2, gen_consumer_node_info/1, register_provider/1, provider_watcher/1]).
%% gen_server callbacks
-export([init/1,
@@ -61,7 +67,7 @@
{ok, State :: #state{}} | {ok, State :: #state{}, timeout() | hibernate} |
{stop, Reason :: term()} | ignore).
init([]) ->
- {ok,Pid} = connection(),
+ {ok, Pid} = connection(),
{ok, #state{zk_pid = Pid}}.
%%--------------------------------------------------------------------
@@ -80,11 +86,11 @@
{stop, Reason :: term(), Reply :: term(), NewState :: #state{}} |
{stop, Reason :: term(), NewState :: #state{}}).
-handle_call({add_consumer,Consumer}, _From, State) ->
- add_consumer(Consumer,State),
+handle_call({add_consumer, Consumer}, _From, State) ->
+ add_consumer(Consumer, State),
{reply, ok, State};
-handle_call({add_provider,Provider}, _From, State) ->
- register_provider_path(Provider,State),
+handle_call({add_provider, Provider}, _From, State) ->
+ register_provider_path(Provider, State),
{reply, ok, State};
handle_call(_Request, _From, State) ->
{reply, ok, State}.
@@ -100,8 +106,8 @@
{noreply, NewState :: #state{}} |
{noreply, NewState :: #state{}, timeout() | hibernate} |
{stop, Reason :: term(), NewState :: #state{}}).
-handle_cast({provider_node_change,Interface,Path}, #state{zk_pid = Pid}=State) ->
- get_provider_and_start(Pid,Interface,Path),
+handle_cast({provider_node_change, Interface, Path}, #state{zk_pid = Pid} = State) ->
+ get_provider_and_start(Pid, Interface, Path),
{noreply, State};
handle_cast(_Request, State) ->
{noreply, State}.
@@ -121,7 +127,7 @@
{noreply, NewState :: #state{}, timeout() | hibernate} |
{stop, Reason :: term(), NewState :: #state{}}).
handle_info(_Info, State) ->
- logger:info("zk server recv msg:~p",[_Info]),
+ logger:info("zk server recv msg:~p", [_Info]),
{noreply, State}.
%%--------------------------------------------------------------------
@@ -156,100 +162,100 @@
register_consumer(Consumer) ->
- gen_server:call(?SERVER,{add_consumer,Consumer}),
+ gen_server:call(?SERVER, {add_consumer, Consumer}),
ok.
-register_consumer(Name,Option)->
- Consumer=#consumer_config{interface = Name,methods = [<<"testa">>,<<"testb">>]},
+register_consumer(Name, Option) ->
+ Consumer = #consumer_config{interface = Name, methods = [<<"testa">>, <<"testb">>]},
register_consumer(Consumer),
ok.
-register_provider(Provider)->
- gen_server:call(?SERVER,{add_provider,Provider}),
+register_provider(Provider) ->
+ gen_server:call(?SERVER, {add_provider, Provider}),
ok.
%%%===================================================================
%%% Internal functions
%%%===================================================================
-connection()->
- {ok,List} = application:get_env(dubboerl,zookeeper_list),
+connection() ->
+ {ok, List} = application:get_env(dubboerl, zookeeper_list),
{ok, Pid} = erlzk:connect(List, 30000, [
{chroot, "/"},
{monitor, self()}]),
- {ok,Pid}.
+ {ok, Pid}.
-add_consumer(Consumer,State)->
- Pid= State#state.zk_pid,
+add_consumer(Consumer, State) ->
+ Pid = State#state.zk_pid,
%% InterfacePath= << <<"/dubbo/">>/binary,Name/binary ,<<"consumers">>/binary >>,
ConsumerNode = gen_consumer_node_info(Consumer),
- ConsumerNode2= list_to_binary(edoc_lib:escape_uri(binary_to_list(ConsumerNode))),
- check_and_create_path(Pid,<<"">>,[{<<"dubbo">>,p},{Consumer#consumer_config.interface,p},{<<"consumers">>,p},{ConsumerNode2,e} ]),
- get_provider_list(Consumer,State),
+ ConsumerNode2 = list_to_binary(edoc_lib:escape_uri(binary_to_list(ConsumerNode))),
+ check_and_create_path(Pid, <<"">>, [{<<"dubbo">>, p}, {Consumer#consumer_config.interface, p}, {<<"consumers">>, p}, {ConsumerNode2, e}]),
+ get_provider_list(Consumer, State),
ok.
-register_provider_path(Provider,State)->
- #state{zk_pid = Pid}=State,
+register_provider_path(Provider, State) ->
+ #state{zk_pid = Pid} = State,
ProviderNode = dubbo_node_config_util:gen_provider_info(Provider),
- check_and_create_path(Pid,<<"">>,[{<<"dubbo">>,p},{Provider#provider_config.interface,p},{<<"providers">>,p},{ProviderNode,e}]),
+ check_and_create_path(Pid, <<"">>, [{<<"dubbo">>, p}, {Provider#provider_config.interface, p}, {<<"providers">>, p}, {ProviderNode, e}]),
ok.
-get_provider_list(Consumer,State)->
- Pid= State#state.zk_pid,
- InterfacePath= << <<"/dubbo/">>/binary,(Consumer#consumer_config.interface)/binary ,<<"/providers">>/binary >>,
- get_provider_and_start(Pid,Consumer#consumer_config.interface,InterfacePath),
+get_provider_list(Consumer, State) ->
+ Pid = State#state.zk_pid,
+ InterfacePath = <<<<"/dubbo/">>/binary, (Consumer#consumer_config.interface)/binary, <<"/providers">>/binary>>,
+ get_provider_and_start(Pid, Consumer#consumer_config.interface, InterfacePath),
ok.
-get_provider_and_start(Pid,Interface,Path)->
- case erlzk:get_children(Pid,Path,spawn(dubbo_zookeeper,provider_watcher,[Interface])) of
- {ok,ChildList} ->
- logger:debug("get provider list ~p",[ChildList]),
- start_provider_process(Interface,ChildList),
+get_provider_and_start(Pid, Interface, Path) ->
+ case erlzk:get_children(Pid, Path, spawn(dubbo_zookeeper, provider_watcher, [Interface])) of
+ {ok, ChildList} ->
+ logger:debug("get provider list ~p", [ChildList]),
+ start_provider_process(Interface, ChildList),
ok;
- {error,R1} ->
- logger:debug("[add_consumer] get_provider_list error ~p ~p",[R1]),
+ {error, R1} ->
+ logger:debug("[add_consumer] get_provider_list error ~p ~p", [R1]),
ok
end.
-provider_watcher(Interface)->
+provider_watcher(Interface) ->
receive
- {node_children_changed,Path} ->
- gen_server:cast(?SERVER,{provider_node_change,Interface,Path}),
- logger:debug("provider_watcher get event ~p ~p",[node_children_changed,Path]);
+ {node_children_changed, Path} ->
+ gen_server:cast(?SERVER, {provider_node_change, Interface, Path}),
+ logger:debug("provider_watcher get event ~p ~p", [node_children_changed, Path]);
{Event, Path} ->
%% Path = "/a",
%% Event = node_created
- logger:debug("provider_watcher get event ~p ~p",[Event,Path])
+ logger:debug("provider_watcher get event ~p ~p", [Event, Path])
end,
ok.
-create_path(Pid,Path,CreateType)->
- case erlzk:create(Pid,Path,CreateType) of
- {ok,ActualPath}->
- logger:debug("[add_consumer] create zk path success ~p",[ActualPath]),
+create_path(Pid, Path, CreateType) ->
+ case erlzk:create(Pid, Path, CreateType) of
+ {ok, ActualPath} ->
+ logger:debug("[add_consumer] create zk path success ~p", [ActualPath]),
ok;
- {error,R1}->
- logger:debug("[add_consumer] create zk path error ~p ~p",[Path,R1])
+ {error, R1} ->
+ logger:debug("[add_consumer] create zk path error ~p ~p", [Path, R1])
end,
ok.
-check_and_create_path(_Pid,_RootPath,[]) ->
+check_and_create_path(_Pid, _RootPath, []) ->
ok;
-check_and_create_path(Pid,RootPath,[{Item,CreateType}|Rst])->
- CheckPath= << RootPath/binary,<<"/">>/binary,Item/binary >>,
- case erlzk:exists(Pid,CheckPath) of
- {ok,Stat} ->
- check_and_create_path(Pid,CheckPath,Rst);
- {error,no_node}->
- logger:debug("[add_consumer] check_and_create_path unexist no_node ~p",[CheckPath]),
- create_path(Pid,CheckPath,CreateType),
- check_and_create_path(Pid,CheckPath,Rst);
- {error,R1} ->
- logger:debug("[add_consumer] check_and_create_path unexist ~p",[R1]),
- check_and_create_path(Pid,CheckPath,Rst)
+check_and_create_path(Pid, RootPath, [{Item, CreateType} | Rst]) ->
+ CheckPath = <<RootPath/binary, <<"/">>/binary, Item/binary>>,
+ case erlzk:exists(Pid, CheckPath) of
+ {ok, Stat} ->
+ check_and_create_path(Pid, CheckPath, Rst);
+ {error, no_node} ->
+ logger:debug("[add_consumer] check_and_create_path unexist no_node ~p", [CheckPath]),
+ create_path(Pid, CheckPath, CreateType),
+ check_and_create_path(Pid, CheckPath, Rst);
+ {error, R1} ->
+ logger:debug("[add_consumer] check_and_create_path unexist ~p", [R1]),
+ check_and_create_path(Pid, CheckPath, Rst)
end.
-gen_consumer_node_info(Consumer)->
+gen_consumer_node_info(Consumer) ->
%% revision参数字段的作用是什么? 暂时不添加
- Methods=lists_util:join(Consumer#consumer_config.methods,<<",">>),
- Value=io_lib:format(<<"consumer://~s/~s?application=~s&category=~s&check=~p&default.timeout=~p&dubbo=~s&interface=~s&methods=~s&side=~s×tamp=~p">>,
+ Methods = lists_util:join(Consumer#consumer_config.methods, <<",">>),
+ Value = io_lib:format(<<"consumer://~s/~s?application=~s&category=~s&check=~p&default.timeout=~p&dubbo=~s&interface=~s&methods=~s&side=~s×tamp=~p">>,
[dubbo_common_fun:local_ip_v4_str(),
Consumer#consumer_config.interface,
Consumer#consumer_config.application,
@@ -261,10 +267,10 @@
Methods,
Consumer#consumer_config.side,
time_util:timestamp_ms()
- ]),
+ ]),
list_to_binary(Value).
%%dubbo_zookeeper:register_consumer(<<"com.ifcoder.abcd">>,[]).
-start_provider_process(Interface,ProviderList)->
- dubbo_consumer_pool:start_consumer(Interface,ProviderList).
+start_provider_process(Interface, ProviderList) ->
+ dubbo_consumer_pool:start_consumer(Interface, ProviderList).
diff --git a/src/dubboerl.app.src b/src/dubboerl.app.src
index 58eed2b..5f6d4ad 100644
--- a/src/dubboerl.app.src
+++ b/src/dubboerl.app.src
@@ -1,16 +1,16 @@
{application, dubboerl,
- [{description, "An OTP application"},
- {vsn, "0.3.0"},
- {registered, []},
- {mod, { dubboerl_app, []}},
- {applications,
- [kernel,
- stdlib,xmerl,ranch,erlzk,poolboy,inets
- ]},
- {env,[]},
- {modules, []},
+ [{description, "An OTP application"},
+ {vsn, "0.3.0"},
+ {registered, []},
+ {mod, {dubboerl_app, []}},
+ {applications,
+ [kernel,
+ stdlib, xmerl, ranch, erlzk, poolboy, inets
+ ]},
+ {env, []},
+ {modules, []},
- {maintainers, []},
- {licenses, []},
- {links, [{"Github", "https://github.com/dubboerl/dubboerl"}]}
- ]}.
+ {maintainers, []},
+ {licenses, []},
+ {links, [{"Github", "https://github.com/dubboerl/dubboerl"}]}
+ ]}.
diff --git a/src/dubboerl.erl b/src/dubboerl.erl
index a0dd95e..0a5f5bc 100644
--- a/src/dubboerl.erl
+++ b/src/dubboerl.erl
@@ -1,51 +1,58 @@
-%%%-------------------------------------------------------------------
-%%% @author dlive
-%%% @copyright (C) 2017, <COMPANY>
-%%% @doc
-%%%
-%%% @end
-%%% Created : 22. Dec 2017 11:54 PM
-%%%-------------------------------------------------------------------
+%%------------------------------------------------------------------------------
+%% Licensed to the Apache Software Foundation (ASF) under one or more
+%% contributor license agreements. See the NOTICE file distributed with
+%% this work for additional information regarding copyright ownership.
+%% The ASF licenses this file to You under the Apache License, Version 2.0
+%% (the "License"); you may not use this file except in compliance with
+%% the License. You may obtain a copy of the License at
+%%
+%% http://www.apache.org/licenses/LICENSE-2.0
+%%
+%% Unless required by applicable law or agreed to in writing, software
+%% distributed under the License is distributed on an "AS IS" BASIS,
+%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+%% See the License for the specific language governing permissions and
+%% limitations under the License.
+%%------------------------------------------------------------------------------
-module(dubboerl).
--author("dlive").
-include("dubboerl.hrl").
-include("dubbo.hrl").
%% API
--export([init/0,start_consumer/0,start_provider/0]).
+-export([init/0, start_consumer/0, start_provider/0]).
-init()->
- ok=start_consumer(),
- ok=start_provider(),
+init() ->
+ ok = start_consumer(),
+ ok = start_provider(),
ok.
-start_consumer()->
- ConsumerList = application:get_env(dubboerl,consumer,[]),
- ApplicationName = application:get_env(dubboerl,application,<<"defaultApplication">>),
- lists:map(fun({Interface,Option})->
- ConsumerInfo = dubbo_config_util:gen_consumer(ApplicationName,Interface,Option),
+start_consumer() ->
+ ConsumerList = application:get_env(dubboerl, consumer, []),
+ ApplicationName = application:get_env(dubboerl, application, <<"defaultApplication">>),
+ lists:map(fun({Interface, Option}) ->
+ ConsumerInfo = dubbo_config_util:gen_consumer(ApplicationName, Interface, Option),
dubbo_zookeeper:register_consumer(ConsumerInfo),
- logger:info("register consumer success ~p",[Interface])
- end,ConsumerList),
+ logger:info("register consumer success ~p", [Interface])
+ end, ConsumerList),
ok.
-start_provider()->
- ProviderList = application:get_env(dubboerl,provider,[]),
- ApplicationName = application:get_env(dubboerl,application,<<"defaultApplication">>),
- DubboServerPort = application:get_env(dubboerl,port,?DUBBO_DEFAULT_PORT),
+start_provider() ->
+ ProviderList = application:get_env(dubboerl, provider, []),
+ ApplicationName = application:get_env(dubboerl, application, <<"defaultApplication">>),
+ DubboServerPort = application:get_env(dubboerl, port, ?DUBBO_DEFAULT_PORT),
start_provider_listen(DubboServerPort),
- lists:map(fun({ImplModuleName,BehaviourModuleName,Interface,Option})->
- ok = dubbo_provider_protocol:register_impl_provider(Interface,ImplModuleName,BehaviourModuleName),
- MethodList= apply(BehaviourModuleName,get_method_999_list,[]),
- ProviderInfo = dubbo_config_util:gen_provider(ApplicationName,DubboServerPort,Interface,MethodList,Option),
+ lists:map(fun({ImplModuleName, BehaviourModuleName, Interface, Option}) ->
+ ok = dubbo_provider_protocol:register_impl_provider(Interface, ImplModuleName, BehaviourModuleName),
+ MethodList = apply(BehaviourModuleName, get_method_999_list, []),
+ ProviderInfo = dubbo_config_util:gen_provider(ApplicationName, DubboServerPort, Interface, MethodList, Option),
dubbo_zookeeper:register_provider(ProviderInfo),
- logger:info("register provider success ~p ~p",[ImplModuleName,Interface])
- end,ProviderList),
+ logger:info("register provider success ~p ~p", [ImplModuleName, Interface])
+ end, ProviderList),
ok.
-start_provider_listen(Port)->
+start_provider_listen(Port) ->
{ok, _} = ranch:start_listener(tcp_reverse,
ranch_tcp, [{port, Port}], dubbo_provider_protocol, []),
ok.
diff --git a/src/dubboerl_app.erl b/src/dubboerl_app.erl
index 8e8bca7..2e92c59 100644
--- a/src/dubboerl_app.erl
+++ b/src/dubboerl_app.erl
@@ -1,15 +1,26 @@
-%%%-------------------------------------------------------------------
-%% @doc dubboerl public API
-%% @end
-%%%-------------------------------------------------------------------
-
+%%------------------------------------------------------------------------------
+%% Licensed to the Apache Software Foundation (ASF) under one or more
+%% contributor license agreements. See the NOTICE file distributed with
+%% this work for additional information regarding copyright ownership.
+%% The ASF licenses this file to You under the Apache License, Version 2.0
+%% (the "License"); you may not use this file except in compliance with
+%% the License. You may obtain a copy of the License at
+%%
+%% http://www.apache.org/licenses/LICENSE-2.0
+%%
+%% Unless required by applicable law or agreed to in writing, software
+%% distributed under the License is distributed on an "AS IS" BASIS,
+%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+%% See the License for the specific language governing permissions and
+%% limitations under the License.
+%%------------------------------------------------------------------------------
-module(dubboerl_app).
-behaviour(application).
-include("dubboerl.hrl").
%% Application callbacks
--export([start/2, stop/1,env_init/0]).
+-export([start/2, stop/1, env_init/0]).
%%====================================================================
%% API
@@ -27,18 +38,18 @@
%%====================================================================
%% Internal functions
%%====================================================================
-env_init()->
- ets:new(?PROVIDER_IMPL_TABLE,[public,named_table]),
+env_init() ->
+ ets:new(?PROVIDER_IMPL_TABLE, [public, named_table]),
dubbo_traffic_control:init(),
type_register:init(),
register_type_list().
%% type_decoding:init().
-register_type_list()->
+register_type_list() ->
List = java_type_defined:get_list(),
lists:map(
- fun({NativeType,ForeignType,Fields}) ->
- dubbo_type_transfer:pre_process_typedef(NativeType,ForeignType,Fields)
- end,List),
+ fun({NativeType, ForeignType, Fields}) ->
+ dubbo_type_transfer:pre_process_typedef(NativeType, ForeignType, Fields)
+ end, List),
ok.
\ No newline at end of file
diff --git a/src/dubboerl_sup.erl b/src/dubboerl_sup.erl
index f17c79b..a829015 100644
--- a/src/dubboerl_sup.erl
+++ b/src/dubboerl_sup.erl
@@ -1,8 +1,19 @@
-%%%-------------------------------------------------------------------
-%% @doc dubboerl top level supervisor.
-%% @end
-%%%-------------------------------------------------------------------
-
+%%------------------------------------------------------------------------------
+%% Licensed to the Apache Software Foundation (ASF) under one or more
+%% contributor license agreements. See the NOTICE file distributed with
+%% this work for additional information regarding copyright ownership.
+%% The ASF licenses this file to You under the Apache License, Version 2.0
+%% (the "License"); you may not use this file except in compliance with
+%% the License. You may obtain a copy of the License at
+%%
+%% http://www.apache.org/licenses/LICENSE-2.0
+%%
+%% Unless required by applicable law or agreed to in writing, software
+%% distributed under the License is distributed on an "AS IS" BASIS,
+%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+%% See the License for the specific language governing permissions and
+%% limitations under the License.
+%%------------------------------------------------------------------------------
-module(dubboerl_sup).
-behaviour(supervisor).
@@ -30,21 +41,21 @@
%% Child :: {Id,StartFunc,Restart,Shutdown,Type,Modules}
init([]) ->
dubboerl_app:env_init(),
- ZK = {dubbo_zookeeper,{dubbo_zookeeper, start_link, []},transient,5000,worker,[dubbo_zookeeper]},
+ ZK = {dubbo_zookeeper, {dubbo_zookeeper, start_link, []}, transient, 5000, worker, [dubbo_zookeeper]},
%% NettySer = {dubbo_netty_client,{dubbo_netty_client, start_link, []},transient,5000,worker,[dubbo_netty_client]},
- Id_count = {dubbo_id_generator,{dubbo_id_generator, start_link, []},transient,5000,worker,[dubbo_id_generator]},
- ProviderPoolSup = {dubbo_provider_worker_sup,{dubbo_provider_worker_sup, start_link, []},transient,5000,supervisor,[dubbo_provider_worker_sup]},
- ConsumerPoolSup = {dubbo_consumer_pool_sup,{dubbo_consumer_pool_sup, start_link, []},transient,5000,supervisor,[dubbo_consumer_pool_sup]},
- ConsumerPool = {dubbo_consumer_pool,{dubbo_consumer_pool, start_link, []},transient,5000,worker,[dubbo_consumer_pool]},
- ListNew1=
- case application:get_env(dubboerl,registry,false) of
+ Id_count = {dubbo_id_generator, {dubbo_id_generator, start_link, []}, transient, 5000, worker, [dubbo_id_generator]},
+ ProviderPoolSup = {dubbo_provider_worker_sup, {dubbo_provider_worker_sup, start_link, []}, transient, 5000, supervisor, [dubbo_provider_worker_sup]},
+ ConsumerPoolSup = {dubbo_consumer_pool_sup, {dubbo_consumer_pool_sup, start_link, []}, transient, 5000, supervisor, [dubbo_consumer_pool_sup]},
+ ConsumerPool = {dubbo_consumer_pool, {dubbo_consumer_pool, start_link, []}, transient, 5000, worker, [dubbo_consumer_pool]},
+ ListNew1 =
+ case application:get_env(dubboerl, registry, false) of
true ->
[ZK];
- false->
+ false ->
[]
end,
- ListNew = ListNew1 ++ [Id_count,ConsumerPool,ConsumerPoolSup,ProviderPoolSup],
- {ok, { {one_for_one, 60, 10}, ListNew} }.
+ ListNew = ListNew1 ++ [Id_count, ConsumerPool, ConsumerPoolSup, ProviderPoolSup],
+ {ok, {{one_for_one, 60, 10}, ListNew}}.
%%====================================================================
%% Internal functions
diff --git a/src/java_type_defined.erl b/src/java_type_defined.erl
index b4eda9e..b736a0e 100644
--- a/src/java_type_defined.erl
+++ b/src/java_type_defined.erl
@@ -1,21 +1,27 @@
-%%%-------------------------------------------------------------------
-%%% @author dlive
-%%% @copyright (C) 2018, <COMPANY>
-%%% @doc
-%%%
-%%% @end
-%%% Created : 09. Mar 2018 11:06 PM
-%%%-------------------------------------------------------------------
+%%------------------------------------------------------------------------------
+%% Licensed to the Apache Software Foundation (ASF) under one or more
+%% contributor license agreements. See the NOTICE file distributed with
+%% this work for additional information regarding copyright ownership.
+%% The ASF licenses this file to You under the Apache License, Version 2.0
+%% (the "License"); you may not use this file except in compliance with
+%% the License. You may obtain a copy of the License at
+%%
+%% http://www.apache.org/licenses/LICENSE-2.0
+%%
+%% Unless required by applicable law or agreed to in writing, software
+%% distributed under the License is distributed on an "AS IS" BASIS,
+%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+%% See the License for the specific language governing permissions and
+%% limitations under the License.
+%%------------------------------------------------------------------------------
-module(java_type_defined).
--author("dlive").
-
-include("java_type.hrl").
%% API
-export([get_list/0]).
-get_list()->
+get_list() ->
[
- {null_pointer_exception,<<"java.lang.NullPointerException">>,record_info(fields,null_pointer_exception)},
- {stack_stack_trace_element,<<"java.lang.StackTraceElement">>,record_info(fields,stack_stack_trace_element)}
+ {null_pointer_exception, <<"java.lang.NullPointerException">>, record_info(fields, null_pointer_exception)},
+ {stack_stack_trace_element, <<"java.lang.StackTraceElement">>, record_info(fields, stack_stack_trace_element)}
].
\ No newline at end of file
diff --git a/src/lists_util.erl b/src/lists_util.erl
index fec6cf0..af84527 100644
--- a/src/lists_util.erl
+++ b/src/lists_util.erl
@@ -1,16 +1,22 @@
-%%%-------------------------------------------------------------------
-%%% @author dlive
-%%% @copyright (C) 2017, <COMPANY>
-%%% @doc
-%%%
-%%% @end
-%%% Created : 27. Dec 2017 6:09 PM
-%%%-------------------------------------------------------------------
+%%------------------------------------------------------------------------------
+%% Licensed to the Apache Software Foundation (ASF) under one or more
+%% contributor license agreements. See the NOTICE file distributed with
+%% this work for additional information regarding copyright ownership.
+%% The ASF licenses this file to You under the Apache License, Version 2.0
+%% (the "License"); you may not use this file except in compliance with
+%% the License. You may obtain a copy of the License at
+%%
+%% http://www.apache.org/licenses/LICENSE-2.0
+%%
+%% Unless required by applicable law or agreed to in writing, software
+%% distributed under the License is distributed on an "AS IS" BASIS,
+%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+%% See the License for the specific language governing permissions and
+%% limitations under the License.
+%%------------------------------------------------------------------------------
-module(lists_util).
--author("dlive").
-
%% API
--export([join/2,del_duplicate/1]).
+-export([join/2, del_duplicate/1]).
-spec(join(List :: list(), Separator :: binary()) -> binary()).
join(List, _Separator) when length(List) == 0 ->
@@ -38,6 +44,6 @@
true ->
List2;
_ ->
- [X]++ List2
+ [X] ++ List2
end
end, [], List).
diff --git a/src/time_util.erl b/src/time_util.erl
index 31e09ee..3243487 100644
--- a/src/time_util.erl
+++ b/src/time_util.erl
@@ -1,49 +1,65 @@
+%%------------------------------------------------------------------------------
+%% Licensed to the Apache Software Foundation (ASF) under one or more
+%% contributor license agreements. See the NOTICE file distributed with
+%% this work for additional information regarding copyright ownership.
+%% The ASF licenses this file to You under the Apache License, Version 2.0
+%% (the "License"); you may not use this file except in compliance with
+%% the License. You may obtain a copy of the License at
+%%
+%% http://www.apache.org/licenses/LICENSE-2.0
+%%
+%% Unless required by applicable law or agreed to in writing, software
+%% distributed under the License is distributed on an "AS IS" BASIS,
+%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+%% See the License for the specific language governing permissions and
+%% limitations under the License.
+%%------------------------------------------------------------------------------
-module(time_util).
-include_lib("kernel/include/file.hrl").
-export([
- get_cur_time/0,get_cur_time/1,
+ get_cur_time/0, get_cur_time/1,
format_time_to_str/1,
- timestamp/0,timestamp_ms/0,
+ timestamp/0, timestamp_ms/0,
timestamp_to_datetime/1,
timestamp_to_local_datetime/1,
get_cur_date/0,
datetime_to_timestamp/1]).
-get_cur_time()->
- {{Year,Month,Day},{Hour,Min,Second}}=calendar:now_to_local_time(os:timestamp()),
- io_lib:format("~4..0w-~2..0w-~2..0w ~2..0w:~2..0w:~2..0w",[Year, Month, Day, Hour,Min,Second]).
+get_cur_time() ->
+ {{Year, Month, Day}, {Hour, Min, Second}} = calendar:now_to_local_time(os:timestamp()),
+ io_lib:format("~4..0w-~2..0w-~2..0w ~2..0w:~2..0w:~2..0w", [Year, Month, Day, Hour, Min, Second]).
-get_cur_date()->
- {{Year,Month,Day},{Hour,Min,Second}}=calendar:now_to_local_time(os:timestamp()),
- io_lib:format("~4..0w-~2..0w-~2..0w",[Year, Month, Day]).
+get_cur_date() ->
+ {{Year, Month, Day}, {Hour, Min, Second}} = calendar:now_to_local_time(os:timestamp()),
+ io_lib:format("~4..0w-~2..0w-~2..0w", [Year, Month, Day]).
-get_cur_time({{Year,Month,Day},{Hour,Min,Second}})->
- io_lib:format("~4..0w-~2..0w-~2..0w ~2..0w:~2..0w:~2..0w",[Year, Month, Day, Hour,Min,Second]).
+get_cur_time({{Year, Month, Day}, {Hour, Min, Second}}) ->
+ io_lib:format("~4..0w-~2..0w-~2..0w ~2..0w:~2..0w:~2..0w", [Year, Month, Day, Hour, Min, Second]).
-format_time_to_str({{Year,Month,Day},{Hour,Min,Second}})->
- io_lib:format("~4..0w-~2..0w-~2..0w ~2..0w:~2..0w:~2..0w",[Year, Month, Day, Hour,Min,Second]).
+format_time_to_str({{Year, Month, Day}, {Hour, Min, Second}}) ->
+ io_lib:format("~4..0w-~2..0w-~2..0w ~2..0w:~2..0w:~2..0w", [Year, Month, Day, Hour, Min, Second]).
timestamp() ->
{M, S, _} = os:timestamp(),
M * 1000000 + S.
-timestamp_ms()->
- {M,S,W} = os:timestamp(),
- M*1000000000+S*1000+(W div 1000).
+timestamp_ms() ->
+ {M, S, W} = os:timestamp(),
+ M * 1000000000 + S * 1000 + (W div 1000).
timestamp_to_datetime(Timestamp) ->
calendar:gregorian_seconds_to_datetime(Timestamp +
- calendar:datetime_to_gregorian_seconds({{1970,1,1}, {0,0,0}})).
+ calendar:datetime_to_gregorian_seconds({{1970, 1, 1}, {0, 0, 0}})).
timestamp_to_local_datetime(Timestamp) ->
- Date=calendar:gregorian_seconds_to_datetime(Timestamp +
- calendar:datetime_to_gregorian_seconds({{1970,1,1}, {0,0,0}})),
+ Date = calendar:gregorian_seconds_to_datetime(Timestamp +
+ calendar:datetime_to_gregorian_seconds({{1970, 1, 1}, {0, 0, 0}})),
calendar:universal_time_to_local_time(Date).
-datetime_to_timestamp(Date)->
- [{D,T}]=calendar:local_time_to_universal_time_dst(Date),
- S = calendar:datetime_to_gregorian_seconds({D, T}),
+datetime_to_timestamp(Date) ->
+ [{D, T}] = calendar:local_time_to_universal_time_dst(Date),
+ S = calendar:datetime_to_gregorian_seconds({D, T}),
S1 = calendar:datetime_to_gregorian_seconds({{1970, 1, 1}, {0, 0, 0}}),
(S - S1).
diff --git a/src/type_decoding.erl b/src/type_decoding.erl
index 343725e..4112b61 100644
--- a/src/type_decoding.erl
+++ b/src/type_decoding.erl
@@ -22,46 +22,46 @@
%% the hash value that the sender passes in.
%% This must resolve to some type definition,
%% otherwise no instance of the decoded type can be created.
--record(decoding_state,{type_pool = dict:new(), reference_pool = dict:new(),obj_define_no=0}).
+-record(decoding_state, {type_pool = dict:new(), reference_pool = dict:new(), obj_define_no = 0}).
--export([init/0,init/1]).
+-export([init/0, init/1]).
-export([lookup_reference/2]).
--export([enlist/1,enlist/2]).
--export([hash_lookup/2,hash_store/2,hash_store/1,store_typepool/1]).
+-export([enlist/1, enlist/2]).
+-export([hash_lookup/2, hash_store/2, hash_store/1, store_typepool/1]).
-export([visit/2]).
--export([resolve_native_type/2,resolve_native_type/1]).
+-export([resolve_native_type/2, resolve_native_type/1]).
-export([camel_case_to_erlang/1]).
-export([build_foreign_view/3]).
-export([project_native_view/3]).
--define(TYPEPOOL_TABLE,type_pool).
--define(REFERENCEPOOL_TABLE,reference_pool).
+-define(TYPEPOOL_TABLE, type_pool).
+-define(REFERENCEPOOL_TABLE, reference_pool).
camel_case_to_erlang(String) when is_binary(String) ->
AsList = binary_to_list(String),
- AsErlang = lists:foldl(fun decamelize/2,[],AsList),
+ AsErlang = lists:foldl(fun decamelize/2, [], AsList),
list_to_atom(AsErlang).
-decamelize(Element,Acc) when Element >= $A, Element =< $Z ->
- lists:append(Acc,[$_,(Element + 16#20)] );
-decamelize(Element,Acc) -> lists:append(Acc,[Element]).
+decamelize(Element, Acc) when Element >= $A, Element =< $Z ->
+ lists:append(Acc, [$_, (Element + 16#20)]);
+decamelize(Element, Acc) -> lists:append(Acc, [Element]).
%% Facility to register a particular type to the pool of known types.
%% Adds the type to the pool of known types if it doesn't already exist.
-enlist(TypeDef) -> enlist(TypeDef,init()).
+enlist(TypeDef) -> enlist(TypeDef, init()).
enlist(TypeDef = #type_def{foreign_type = Key},
State = #decoding_state{type_pool = OldPool}) ->
- ets:insert(?TYPEPOOL_TABLE,{Key,TypeDef}),
+ ets:insert(?TYPEPOOL_TABLE, {Key, TypeDef}),
State.
store_typepool(TypeDef = #type_def{foreign_type = Key}) ->
- ets:insert(?TYPEPOOL_TABLE,{Key,TypeDef}),
+ ets:insert(?TYPEPOOL_TABLE, {Key, TypeDef}),
TypeDef.
-build_foreign_view(ForeignType,FieldNames,State) ->
- #type_def{native_type = Native} = resolve_native_type(ForeignType,State),
+build_foreign_view(ForeignType, FieldNames, State) ->
+ #type_def{native_type = Native} = resolve_native_type(ForeignType, State),
ForeignView = [camel_case_to_erlang(Fieldname) || Fieldname <- FieldNames],
DefineNo = State#decoding_state.obj_define_no,
{#type_def{
@@ -71,24 +71,24 @@
fieldnames = ForeignView}, State#decoding_state{obj_define_no = DefineNo}}.
% Projects the native view over tuples that in foreign order
-project_native_view(ForeignView,ForeignData,
- #type_def{native_type = NativeType, fieldnames = NativeView}) ->
- AsDict = dict:from_list(lists:zip(ForeignView,ForeignData)),
- NativeData = [dict:fetch(Key,AsDict) || Key <- NativeView],
- list_to_tuple( [NativeType] ++ NativeData).
+project_native_view(ForeignView, ForeignData,
+ #type_def{native_type = NativeType, fieldnames = NativeView}) ->
+ AsDict = dict:from_list(lists:zip(ForeignView, ForeignData)),
+ NativeData = [dict:fetch(Key, AsDict) || Key <- NativeView],
+ list_to_tuple([NativeType] ++ NativeData).
resolve_native_type(ForeignType, #decoding_state{type_pool = Pool}) ->
- case ets:lookup(?TYPEPOOL_TABLE,ForeignType) of
- []->
- throw({cannot_resolve_type,ForeignType});
- [{ForeignType,TypeDef}]->
+ case ets:lookup(?TYPEPOOL_TABLE, ForeignType) of
+ [] ->
+ throw({cannot_resolve_type, ForeignType});
+ [{ForeignType, TypeDef}] ->
TypeDef
end.
resolve_native_type(ForeignType) ->
- case ets:lookup(?TYPEPOOL_TABLE,ForeignType) of
- []->
+ case ets:lookup(?TYPEPOOL_TABLE, ForeignType) of
+ [] ->
undefined;
- [{ForeignType,TypeDef}]->
+ [{ForeignType, TypeDef}] ->
TypeDef
end.
%% case dict:fetch(ForeignType,Pool) of
@@ -101,8 +101,8 @@
%% Creates a reference for a type def that is unique within the
%% current invocation context
visit(TypeDef, State = #decoding_state{reference_pool = OldPool}) ->
- Size=ets:info(?REFERENCEPOOL_TABLE,size),
- ets:insert(?REFERENCEPOOL_TABLE,{Size,TypeDef#type_def{defineNo = Size}}),
+ Size = ets:info(?REFERENCEPOOL_TABLE, size),
+ ets:insert(?REFERENCEPOOL_TABLE, {Size, TypeDef#type_def{defineNo = Size}}),
State.
%% Size = dict:size(OldPool),
%% NewPool = dict:store(Size, TypeDef, OldPool),
@@ -111,14 +111,14 @@
%% Resolves a type def based on a reference that must be have set
%% with the current invocation context
lookup_reference(Ref, #decoding_state{reference_pool = Pool}) ->
- case ets:lookup(?REFERENCEPOOL_TABLE,Ref) of
- []->
+ case ets:lookup(?REFERENCEPOOL_TABLE, Ref) of
+ [] ->
throw("Lookup of unknown reference");
- [{Ref,TypeDef}]->
+ [{Ref, TypeDef}] ->
TypeDef
end.
- %?LOG(Pool),
- %?LOG(Ref),
+%?LOG(Pool),
+%?LOG(Ref),
%% case dict:fetch(Ref,Pool) of
%% error ->
%%%% ?ERROR(Ref, Pool),
@@ -128,12 +128,12 @@
%% end.
%% Does what it says on the tin.
-hash_lookup(Hash,_State) ->
+hash_lookup(Hash, _State) ->
%% init(false),
case ets:lookup(?REFERENCEPOOL_TABLE, Hash) of
[] ->
{not_found, Hash};
- [{Hash,TypeDef}] ->
+ [{Hash, TypeDef}] ->
TypeDef
end.
@@ -141,24 +141,24 @@
hash_store(#type_def{defineNo = Hash} = TypeDef, State) ->
%% init(false),
case Hash of
- -1->
- Size=ets:info(?REFERENCEPOOL_TABLE,size),
- ets:insert(?REFERENCEPOOL_TABLE,{Size,TypeDef#type_def{defineNo = Size}});
+ -1 ->
+ Size = ets:info(?REFERENCEPOOL_TABLE, size),
+ ets:insert(?REFERENCEPOOL_TABLE, {Size, TypeDef#type_def{defineNo = Size}});
_ ->
- ets:insert(?REFERENCEPOOL_TABLE,{Hash,TypeDef})
+ ets:insert(?REFERENCEPOOL_TABLE, {Hash, TypeDef})
end,
State.
hash_store(#type_def{defineNo = Hash} = TypeDef) ->
%% init(false),
- NewTypeDef=case Hash of
- -1->
- Size=ets:info(?REFERENCEPOOL_TABLE,size),
- TypeDef2=TypeDef#type_def{defineNo = Size},
- TypeDef2;
- _ ->
- TypeDef
- end,
- ets:insert(?REFERENCEPOOL_TABLE,{NewTypeDef#type_def.defineNo,NewTypeDef}),
+ NewTypeDef = case Hash of
+ -1 ->
+ Size = ets:info(?REFERENCEPOOL_TABLE, size),
+ TypeDef2 = TypeDef#type_def{defineNo = Size},
+ TypeDef2;
+ _ ->
+ TypeDef
+ end,
+ ets:insert(?REFERENCEPOOL_TABLE, {NewTypeDef#type_def.defineNo, NewTypeDef}),
NewTypeDef.
init() -> init(false).
@@ -186,27 +186,27 @@
%% end,
case ets:info(?TYPEPOOL_TABLE) of
undefined ->
- io:format("init decoding type_pool table pid ~p~n",[self()]),
- ets:new(?TYPEPOOL_TABLE,[public,named_table]); %% public
+ io:format("init decoding type_pool table pid ~p~n", [self()]),
+ ets:new(?TYPEPOOL_TABLE, [public, named_table]); %% public
_ ->
%% io:format("type decoding etsinfo ~p~n",[EtsInfo]),
if
Delete == true ->
ets:delete(?TYPEPOOL_TABLE),
- ets:new(?TYPEPOOL_TABLE,[public,named_table]);
+ ets:new(?TYPEPOOL_TABLE, [public, named_table]);
true ->
ok
end
end,
case ets:info(?REFERENCEPOOL_TABLE) of
undefined ->
- io:format("init decoding REFERENCEPOOL_TABLE table pid ~p~n",[self()]),
- ets:new(?REFERENCEPOOL_TABLE,[public,named_table]); %% public
+ io:format("init decoding REFERENCEPOOL_TABLE table pid ~p~n", [self()]),
+ ets:new(?REFERENCEPOOL_TABLE, [public, named_table]); %% public
_ ->
if
Delete == true ->
ets:delete(?REFERENCEPOOL_TABLE),
- ets:new(?REFERENCEPOOL_TABLE,[public,named_table]);
+ ets:new(?REFERENCEPOOL_TABLE, [public, named_table]);
true ->
ok
end
diff --git a/src/type_encoding.erl b/src/type_encoding.erl
index f457fb0..b2f72d7 100644
--- a/src/type_encoding.erl
+++ b/src/type_encoding.erl
@@ -22,21 +22,21 @@
%% When a tuple is to be encoded at run-time, a lookup is performed against
%% the type tag. This must resolve to some type definition,
%% otherwise no type information can be encoded into the output stream.
--record(encoding_state,{pool = dict:new(), count = -1}).
+-record(encoding_state, {pool = dict:new(), count = -1}).
-export([init/0]).
--export([enlist/1,enlist/2]).
+-export([enlist/1, enlist/2]).
-export([visit/2]).
%% Facility to register a particular type to the pool of known types.
%% Adds the type to the pool of known types if it doesn't already exist.
-init()->
+init() ->
#encoding_state{}.
-enlist(TypeDef) -> enlist(TypeDef,#encoding_state{}).
+enlist(TypeDef) -> enlist(TypeDef, #encoding_state{}).
enlist(TypeDef = #type_def{native_type = Key},
- State = #encoding_state{pool = OldPool}) ->
- case dict:is_key(Key,OldPool) of
+ State = #encoding_state{pool = OldPool}) ->
+ case dict:is_key(Key, OldPool) of
true ->
State;
false ->
@@ -53,39 +53,39 @@
%%
%% If it already has been written out, it must be back-referenced.
visit(NativeType, State = #encoding_state{pool = Pool}) ->
- logger:debug("[encode] visit ~p",[NativeType]),
- case dict:find(NativeType,Pool) of
- {ok,{-1, TypeDef}} ->
+ logger:debug("[encode] visit ~p", [NativeType]),
+ case dict:find(NativeType, Pool) of
+ {ok, {-1, TypeDef}} ->
%% The type needs hashing and it's reference needs updating
- {Ref,NewTypeDef,NewState} = assign_reference(TypeDef, State),
+ {Ref, NewTypeDef, NewState} = assign_reference(TypeDef, State),
%% Hash = erlang:phash2(TypeDef),
%%%%%%%%%%%%%%%%%%%%%%%%%%
%% LOOK INTO THIS DEPENDENCY, MAYBE EXTRACT IT OUT
%% type_decoding:hash_store(NewTypeDef,NewState), %% 貌似这个没用,可以去掉.
%%%%%%%%%%%%%%%%%%%%%%%%%%
- {hash, Ref,NewTypeDef , NewState};
- {ok,{Ref, TypeDef} } ->
+ {hash, Ref, NewTypeDef, NewState};
+ {ok, {Ref, TypeDef}} ->
{ref, Ref};
error ->
case get_deftype_public_pool(NativeType) of
undefined ->
- throw("unkonw native type "++ atom_to_list(NativeType));
+ throw("unkonw native type " ++ atom_to_list(NativeType));
TypeDefTmp ->
- State2 = enlist(TypeDefTmp,State),
- visit(NativeType,State2)
+ State2 = enlist(TypeDefTmp, State),
+ visit(NativeType, State2)
end
end.
%% This increments the reference count for the current scope and updates the
%% reference in the pool of known types
assign_reference(TypeDef = #type_def{native_type = Key},
- #encoding_state{pool = OldPool, count = Count}) ->
+ #encoding_state{pool = OldPool, count = Count}) ->
NewCount = Count + 1,
NewTypeDef = TypeDef#type_def{defineNo = NewCount},
Value = {NewCount, NewTypeDef},
NewPool = dict:store(Key, Value, OldPool),
- logger:debug("[encode] assign_reference type ~p definedNo ~p",[Key,NewCount]),
- {NewCount,NewTypeDef,#encoding_state{pool = NewPool, count = NewCount}}.
+ logger:debug("[encode] assign_reference type ~p definedNo ~p", [Key, NewCount]),
+ {NewCount, NewTypeDef, #encoding_state{pool = NewPool, count = NewCount}}.
-get_deftype_public_pool(NativeType)->
+get_deftype_public_pool(NativeType) ->
type_register:lookup_native_type(NativeType).
\ No newline at end of file
diff --git a/src/type_register.erl b/src/type_register.erl
index a338510..82d9202 100644
--- a/src/type_register.erl
+++ b/src/type_register.erl
@@ -16,49 +16,49 @@
-module(type_register).
%% API
--export([init/0,regiest_foreign_native/1,lookup_foreign_type/1,lookup_native_type/1]).
+-export([init/0, regiest_foreign_native/1, lookup_foreign_type/1, lookup_native_type/1]).
-include("hessian.hrl").
--define(FOREIGN_NATIVE_TABLE,foreign_native_table).
--define(NATIVE_FOREIGN_TABLE,native_foreign_table).
+-define(FOREIGN_NATIVE_TABLE, foreign_native_table).
+-define(NATIVE_FOREIGN_TABLE, native_foreign_table).
-init()->
+init() ->
case ets:info(?FOREIGN_NATIVE_TABLE) of
undefined ->
- ?FOREIGN_NATIVE_TABLE = ets:new(?FOREIGN_NATIVE_TABLE,[public,named_table]),
- logger:info("init decoding foreign_native_table table",[]);
+ ?FOREIGN_NATIVE_TABLE = ets:new(?FOREIGN_NATIVE_TABLE, [public, named_table]),
+ logger:info("init decoding foreign_native_table table", []);
_ ->
ets:delete(?FOREIGN_NATIVE_TABLE),
- ?FOREIGN_NATIVE_TABLE = ets:new(?FOREIGN_NATIVE_TABLE,[public,named_table])
+ ?FOREIGN_NATIVE_TABLE = ets:new(?FOREIGN_NATIVE_TABLE, [public, named_table])
end,
case ets:info(?NATIVE_FOREIGN_TABLE) of
undefined ->
- io:format("init decoding native_foreign_table table pid ~p~n",[self()]),
- ?NATIVE_FOREIGN_TABLE = ets:new(?NATIVE_FOREIGN_TABLE,[public,named_table]); %% public
+ io:format("init decoding native_foreign_table table pid ~p~n", [self()]),
+ ?NATIVE_FOREIGN_TABLE = ets:new(?NATIVE_FOREIGN_TABLE, [public, named_table]); %% public
_ ->
ets:delete(?NATIVE_FOREIGN_TABLE),
- ?NATIVE_FOREIGN_TABLE = ets:new(?NATIVE_FOREIGN_TABLE,[public,named_table])
+ ?NATIVE_FOREIGN_TABLE = ets:new(?NATIVE_FOREIGN_TABLE, [public, named_table])
end,
ok.
-regiest_foreign_native(TypeDef)->
- logger:debug("regiest foreign info ~p",[TypeDef]),
- ets:insert(?FOREIGN_NATIVE_TABLE,{TypeDef#type_def.foreign_type,TypeDef}),
- ets:insert(?NATIVE_FOREIGN_TABLE,{TypeDef#type_def.native_type,TypeDef}).
+regiest_foreign_native(TypeDef) ->
+ logger:debug("regiest foreign info ~p", [TypeDef]),
+ ets:insert(?FOREIGN_NATIVE_TABLE, {TypeDef#type_def.foreign_type, TypeDef}),
+ ets:insert(?NATIVE_FOREIGN_TABLE, {TypeDef#type_def.native_type, TypeDef}).
-lookup_foreign_type(ForeignType)->
- case ets:lookup(?FOREIGN_NATIVE_TABLE,ForeignType) of
- []->
+lookup_foreign_type(ForeignType) ->
+ case ets:lookup(?FOREIGN_NATIVE_TABLE, ForeignType) of
+ [] ->
undefined;
- [{_,TypeDef}] ->
+ [{_, TypeDef}] ->
TypeDef
end.
-lookup_native_type(NativeType)->
- case ets:lookup(?NATIVE_FOREIGN_TABLE,NativeType) of
- []->
+lookup_native_type(NativeType) ->
+ case ets:lookup(?NATIVE_FOREIGN_TABLE, NativeType) of
+ [] ->
undefined;
- [{_,TypeDef}] ->
+ [{_, TypeDef}] ->
TypeDef
end.
\ No newline at end of file
diff --git a/test/consumer_SUITE.erl b/test/consumer_SUITE.erl
index 734d9d3..a820b5d 100644
--- a/test/consumer_SUITE.erl
+++ b/test/consumer_SUITE.erl
@@ -1,14 +1,20 @@
-%%%-------------------------------------------------------------------
-%%% @author dlive
-%%% @copyright (C) 2019, <COMPANY>
-%%% @doc
-%%%
-%%% @end
-%%% Created : 02. May 2019 17:10
-%%%-------------------------------------------------------------------
+%%------------------------------------------------------------------------------
+%% Licensed to the Apache Software Foundation (ASF) under one or more
+%% contributor license agreements. See the NOTICE file distributed with
+%% this work for additional information regarding copyright ownership.
+%% The ASF licenses this file to You under the Apache License, Version 2.0
+%% (the "License"); you may not use this file except in compliance with
+%% the License. You may obtain a copy of the License at
+%%
+%% http://www.apache.org/licenses/LICENSE-2.0
+%%
+%% Unless required by applicable law or agreed to in writing, software
+%% distributed under the License is distributed on an "AS IS" BASIS,
+%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+%% See the License for the specific language governing permissions and
+%% limitations under the License.
+%%------------------------------------------------------------------------------
-module(consumer_SUITE).
--author("dlive").
-
%% API
-export([]).
@@ -21,7 +27,7 @@
%% Info = [tuple()]
%%--------------------------------------------------------------------
suite() ->
- [{timetrap,{seconds,60}}].
+ [{timetrap, {seconds, 60}}].
%%--------------------------------------------------------------------
%% Function: init_per_suite(Config0) ->
@@ -30,25 +36,25 @@
%% Reason = term()
%%--------------------------------------------------------------------
init_per_suite(Config) ->
- logger:add_handler(testttt,logger_std_h,#{
- level => debug
- }),
- Start = application:ensure_all_started(dubboerl),
+ logger:add_handler(testttt, logger_std_h, #{
+ level => debug
+ }),
+ Start = application:ensure_all_started(dubboerl),
%% dubboerl:init(),
- dubboerl:start_provider(),
- timer:sleep(2000),
- dubboerl:start_consumer(),
- dubbo_service_app:register_type_list(),
- timer:sleep(5000),
- io:format(user,"test case start info ~p~n",[Start]),
- [{appid,1}].
+ dubboerl:start_provider(),
+ timer:sleep(2000),
+ dubboerl:start_consumer(),
+ dubbo_service_app:register_type_list(),
+ timer:sleep(5000),
+ io:format(user, "test case start info ~p~n", [Start]),
+ [{appid, 1}].
%%--------------------------------------------------------------------
%% Function: end_per_suite(Config0) -> term() | {save_config,Config1}
%% Config0 = Config1 = [tuple()]
%%--------------------------------------------------------------------
end_per_suite(_Config) ->
- ok.
+ ok.
%%--------------------------------------------------------------------
%% Function: init_per_group(GroupName, Config0) ->
@@ -58,7 +64,7 @@
%% Reason = term()
%%--------------------------------------------------------------------
init_per_group(_GroupName, Config) ->
- Config.
+ Config.
%%--------------------------------------------------------------------
%% Function: end_per_group(GroupName, Config0) ->
@@ -67,7 +73,7 @@
%% Config0 = Config1 = [tuple()]
%%--------------------------------------------------------------------
end_per_group(_GroupName, _Config) ->
- ok.
+ ok.
%%--------------------------------------------------------------------
%% Function: init_per_testcase(TestCase, Config0) ->
@@ -77,7 +83,7 @@
%% Reason = term()
%%--------------------------------------------------------------------
init_per_testcase(_TestCase, Config) ->
- Config.
+ Config.
%%--------------------------------------------------------------------
%% Function: end_per_testcase(TestCase, Config0) ->
@@ -87,7 +93,7 @@
%% Reason = term()
%%--------------------------------------------------------------------
end_per_testcase(_TestCase, _Config) ->
- ok.
+ ok.
%%--------------------------------------------------------------------
%% Function: groups() -> [Group]
@@ -102,9 +108,9 @@
%% N = integer() | forever
%%--------------------------------------------------------------------
groups() ->
- [
- {consumer1,[sequence],[lib_type_register,json_sync_invoker,hessian_sync_invoker]}
- ].
+ [
+ {consumer1, [sequence], [lib_type_register, json_sync_invoker, hessian_sync_invoker]}
+ ].
%%--------------------------------------------------------------------
%% Function: all() -> GroupsAndTestCases | {skip,Reason}
@@ -114,14 +120,14 @@
%% Reason = term()
%%--------------------------------------------------------------------
all() ->
- [{group,consumer1}].
+ [{group, consumer1}].
%%--------------------------------------------------------------------
%% Function: TestCase() -> Info
%% Info = [tuple()]
%%--------------------------------------------------------------------
lib_type_register() ->
- [].
+ [].
%%--------------------------------------------------------------------
%% Function: TestCase(Config0) ->
@@ -132,19 +138,19 @@
%% Comment = term()
%%--------------------------------------------------------------------
lib_type_register(_Config) ->
- ok.
+ ok.
-json_sync_invoker(_Config)->
- application:set_env(dubboerl,protocol,json),
- R1 = user2:queryUserInfo(#userInfoRequest{username = "name",requestId = "111"},#{sync=> true}),
- io:format(user,"json_sync_invoker result ~p ~n",[R1]),
- R2 = user2:genUserId(),
- io:format(user,"json_sync_invoker result2 ~p ~n",[R2]),
- ok.
-hessian_sync_invoker(_Config)->
- application:set_env(dubboerl,protocol,hessian),
- R1 = user2:queryUserInfo(#userInfoRequest{username = "name",requestId = "111"},#{sync=> true}),
- io:format(user,"json_sync_invoker result ~p ~n",[R1]),
- R2 = user2:genUserId(),
- io:format(user,"json_sync_invoker result2 ~p ~n",[R2]),
- ok.
\ No newline at end of file
+json_sync_invoker(_Config) ->
+ application:set_env(dubboerl, protocol, json),
+ R1 = user2:queryUserInfo(#userInfoRequest{username = "name", requestId = "111"}, #{sync=> true}),
+ io:format(user, "json_sync_invoker result ~p ~n", [R1]),
+ R2 = user2:genUserId(),
+ io:format(user, "json_sync_invoker result2 ~p ~n", [R2]),
+ ok.
+hessian_sync_invoker(_Config) ->
+ application:set_env(dubboerl, protocol, hessian),
+ R1 = user2:queryUserInfo(#userInfoRequest{username = "name", requestId = "111"}, #{sync=> true}),
+ io:format(user, "json_sync_invoker result ~p ~n", [R1]),
+ R2 = user2:genUserId(),
+ io:format(user, "json_sync_invoker result2 ~p ~n", [R2]),
+ ok.
\ No newline at end of file
diff --git a/test/de_codec_tests.erl b/test/de_codec_tests.erl
index 5cf1e04..88b545a 100644
--- a/test/de_codec_tests.erl
+++ b/test/de_codec_tests.erl
@@ -1,18 +1,24 @@
-%%%-------------------------------------------------------------------
-%%% @author dlive
-%%% @copyright (C) 2018, <COMPANY>
-%%% @doc
-%%%
-%%% @end
-%%% Created : 06. Apr 2018 4:49 PM
-%%%-------------------------------------------------------------------
+%%------------------------------------------------------------------------------
+%% Licensed to the Apache Software Foundation (ASF) under one or more
+%% contributor license agreements. See the NOTICE file distributed with
+%% this work for additional information regarding copyright ownership.
+%% The ASF licenses this file to You under the Apache License, Version 2.0
+%% (the "License"); you may not use this file except in compliance with
+%% the License. You may obtain a copy of the License at
+%%
+%% http://www.apache.org/licenses/LICENSE-2.0
+%%
+%% Unless required by applicable law or agreed to in writing, software
+%% distributed under the License is distributed on an "AS IS" BASIS,
+%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+%% See the License for the specific language governing permissions and
+%% limitations under the License.
+%%------------------------------------------------------------------------------
-module(de_codec_tests).
--author("dlive").
-
-include_lib("eunit/include/eunit.hrl").
-include("dubbo.hrl").
--record(databaseOperateRequest,{
+-record(databaseOperateRequest, {
param}).
diff --git a/test/dubbo_adapter_tests.erl b/test/dubbo_adapter_tests.erl
index 8706e8b..45fd43c 100644
--- a/test/dubbo_adapter_tests.erl
+++ b/test/dubbo_adapter_tests.erl
@@ -1,35 +1,42 @@
-%%%-------------------------------------------------------------------
-%%% @author dlive
-%%% @copyright (C) 2019, <COMPANY>
-%%% @doc
-%%%
-%%% @end
-%%% Created : 07. May 2019 00:34
-%%%-------------------------------------------------------------------
+%%------------------------------------------------------------------------------
+%% Licensed to the Apache Software Foundation (ASF) under one or more
+%% contributor license agreements. See the NOTICE file distributed with
+%% this work for additional information regarding copyright ownership.
+%% The ASF licenses this file to You under the Apache License, Version 2.0
+%% (the "License"); you may not use this file except in compliance with
+%% the License. You may obtain a copy of the License at
+%%
+%% http://www.apache.org/licenses/LICENSE-2.0
+%%
+%% Unless required by applicable law or agreed to in writing, software
+%% distributed under the License is distributed on an "AS IS" BASIS,
+%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+%% See the License for the specific language governing permissions and
+%% limitations under the License.
+%%------------------------------------------------------------------------------
-module(dubbo_adapter_tests).
--author("dlive").
-include("dubbo.hrl").
-include_lib("eunit/include/eunit.hrl").
reference_test() ->
- dubbo_id_generator:start_link(),
- Invocation = #dubbo_rpc_invocation{
- className = <<"testname">>,
- classVersion = <<"testversion">>,
- methodName = <<"getUserInfo">>,
- parameterDesc = <<"Ljava/lang/String;"/utf8>>,
- parameterTypes = [
- #type_def{foreign_type = <<"java.lang.String">>,
- native_type = string,
- fieldnames = []}
- ],
- parameters = [
- <<"test">>
- ],
- attachments = [
- {<<"path">>, <<"testname">>},
- {<<"interface">> , <<"testname">>}
- ]
- },
- Request = dubbo_adapter:reference(Invocation),
- ?assert(is_record(Request,dubbo_request)).
+ dubbo_id_generator:start_link(),
+ Invocation = #dubbo_rpc_invocation{
+ className = <<"testname">>,
+ classVersion = <<"testversion">>,
+ methodName = <<"getUserInfo">>,
+ parameterDesc = <<"Ljava/lang/String;"/utf8>>,
+ parameterTypes = [
+ #type_def{foreign_type = <<"java.lang.String">>,
+ native_type = string,
+ fieldnames = []}
+ ],
+ parameters = [
+ <<"test">>
+ ],
+ attachments = [
+ {<<"path">>, <<"testname">>},
+ {<<"interface">>, <<"testname">>}
+ ]
+ },
+ Request = dubbo_adapter:reference(Invocation),
+ ?assert(is_record(Request, dubbo_request)).
diff --git a/test/dubbo_common_fun_tests.erl b/test/dubbo_common_fun_tests.erl
index c2cebbb..cc52132 100644
--- a/test/dubbo_common_fun_tests.erl
+++ b/test/dubbo_common_fun_tests.erl
@@ -1,14 +1,20 @@
-%%%-------------------------------------------------------------------
-%%% @author dlive
-%%% @copyright (C) 2019, <COMPANY>
-%%% @doc
-%%%
-%%% @end
-%%% Created : 24. Apr 2019 11:28 PM
-%%%-------------------------------------------------------------------
+%%------------------------------------------------------------------------------
+%% Licensed to the Apache Software Foundation (ASF) under one or more
+%% contributor license agreements. See the NOTICE file distributed with
+%% this work for additional information regarding copyright ownership.
+%% The ASF licenses this file to You under the Apache License, Version 2.0
+%% (the "License"); you may not use this file except in compliance with
+%% the License. You may obtain a copy of the License at
+%%
+%% http://www.apache.org/licenses/LICENSE-2.0
+%%
+%% Unless required by applicable law or agreed to in writing, software
+%% distributed under the License is distributed on an "AS IS" BASIS,
+%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+%% See the License for the specific language governing permissions and
+%% limitations under the License.
+%%------------------------------------------------------------------------------
-module(dubbo_common_fun_tests).
--author("dlive").
-
-include_lib("eunit/include/eunit.hrl").
request_gen_test() ->
@@ -16,17 +22,17 @@
Id = dubbo_id_generator:gen_id(),
?assert(is_integer(Id)).
-string_join_test()->
- Result1 = lists_util:join([<<"a">>,<<"b">>],<<",">>),
- ?assertEqual(Result1,<<"a,b">>),
+string_join_test() ->
+ Result1 = lists_util:join([<<"a">>, <<"b">>], <<",">>),
+ ?assertEqual(Result1, <<"a,b">>),
- Result2 = lists_util:join([],<<",">>),
- ?assertEqual(Result2,<<"">>),
+ Result2 = lists_util:join([], <<",">>),
+ ?assertEqual(Result2, <<"">>),
- Result3 = lists_util:join([<<"a">>,"b",ttt],<<",">>),
- ?assertEqual(Result3,<<"a,b">>),
+ Result3 = lists_util:join([<<"a">>, "b", ttt], <<",">>),
+ ?assertEqual(Result3, <<"a,b">>),
ok.
-list_dup_test()->
- R = lists_util:del_duplicate([a,b,a]),
- ?assertEqual(length(R),2).
\ No newline at end of file
+list_dup_test() ->
+ R = lists_util:del_duplicate([a, b, a]),
+ ?assertEqual(length(R), 2).
\ No newline at end of file
diff --git a/test/dubbo_config_parser_tests.erl b/test/dubbo_config_parser_tests.erl
index 246ca10..9ff0be4 100644
--- a/test/dubbo_config_parser_tests.erl
+++ b/test/dubbo_config_parser_tests.erl
@@ -1,28 +1,34 @@
-%%%-------------------------------------------------------------------
-%%% @author dlive
-%%% @copyright (C) 2017, <COMPANY>
-%%% @doc
-%%%
-%%% @end
-%%% Created : 30. Dec 2017 2:52 PM
-%%%-------------------------------------------------------------------
+%%------------------------------------------------------------------------------
+%% Licensed to the Apache Software Foundation (ASF) under one or more
+%% contributor license agreements. See the NOTICE file distributed with
+%% this work for additional information regarding copyright ownership.
+%% The ASF licenses this file to You under the Apache License, Version 2.0
+%% (the "License"); you may not use this file except in compliance with
+%% the License. You may obtain a copy of the License at
+%%
+%% http://www.apache.org/licenses/LICENSE-2.0
+%%
+%% Unless required by applicable law or agreed to in writing, software
+%% distributed under the License is distributed on an "AS IS" BASIS,
+%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+%% See the License for the specific language governing permissions and
+%% limitations under the License.
+%%------------------------------------------------------------------------------
-module(dubbo_config_parser_tests).
--author("dlive").
-
-include_lib("eunit/include/eunit.hrl").
-include("dubbo.hrl").
-gen_provice_config_test()->
- ProviderConfigInfo = dubbo_config_util:gen_provider(<<"defaultApp">>,20880,<<"org.apache.dubbo.test.interface">>,[method1],[]),
+gen_provice_config_test() ->
+ ProviderConfigInfo = dubbo_config_util:gen_provider(<<"defaultApp">>, 20880, <<"org.apache.dubbo.test.interface">>, [method1], []),
ProvideNode = dubbo_node_config_util:gen_provider_info(ProviderConfigInfo),
?assert(is_binary(ProvideNode)).
provider_parse_test() ->
- {ok,ProviderConfig} = dubbo_node_config_util:parse_provider_info(<<"dubbo%3A%2F%2F127.0.0.1%3A20880%2Forg.apache.dubbo.test.interface%3Finterface=org.apache.dubbo.test.interface&application=defaultApp&anyhost=true&dubbo=2.5.3&executes=10&methods=method1&side=provider×tamp=1556095933071">>),
- ?assertEqual(ProviderConfig#provider_config.protocol,dubbo),
- ?assertEqual(ProviderConfig#provider_config.host,"127.0.0.1"),
- ?assertEqual(ProviderConfig#provider_config.port,20880),
- ?assertEqual(ProviderConfig#provider_config.interface,<<"org.apache.dubbo.test.interface">>),
+ {ok, ProviderConfig} = dubbo_node_config_util:parse_provider_info(<<"dubbo%3A%2F%2F127.0.0.1%3A20880%2Forg.apache.dubbo.test.interface%3Finterface=org.apache.dubbo.test.interface&application=defaultApp&anyhost=true&dubbo=2.5.3&executes=10&methods=method1&side=provider×tamp=1556095933071">>),
+ ?assertEqual(ProviderConfig#provider_config.protocol, dubbo),
+ ?assertEqual(ProviderConfig#provider_config.host, "127.0.0.1"),
+ ?assertEqual(ProviderConfig#provider_config.port, 20880),
+ ?assertEqual(ProviderConfig#provider_config.interface, <<"org.apache.dubbo.test.interface">>),
?assert(true).
diff --git a/test/dubbo_heartbeat_tests.erl b/test/dubbo_heartbeat_tests.erl
index bdc2d49..4cf237e 100644
--- a/test/dubbo_heartbeat_tests.erl
+++ b/test/dubbo_heartbeat_tests.erl
@@ -1,20 +1,26 @@
-%%%-------------------------------------------------------------------
-%%% @author dlive
-%%% @copyright (C) 2019, <COMPANY>
-%%% @doc
-%%%
-%%% @end
-%%% Created : 15. May 2019 23:57
-%%%-------------------------------------------------------------------
+%%------------------------------------------------------------------------------
+%% Licensed to the Apache Software Foundation (ASF) under one or more
+%% contributor license agreements. See the NOTICE file distributed with
+%% this work for additional information regarding copyright ownership.
+%% The ASF licenses this file to You under the Apache License, Version 2.0
+%% (the "License"); you may not use this file except in compliance with
+%% the License. You may obtain a copy of the License at
+%%
+%% http://www.apache.org/licenses/LICENSE-2.0
+%%
+%% Unless required by applicable law or agreed to in writing, software
+%% distributed under the License is distributed on an "AS IS" BASIS,
+%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+%% See the License for the specific language governing permissions and
+%% limitations under the License.
+%%------------------------------------------------------------------------------
-module(dubbo_heartbeat_tests).
--author("dlive").
-
-include_lib("eunit/include/eunit.hrl").
-heartbeat1_test()->
- dubbo_id_generator:start_link(),
- {ok,Data} = dubbo_heartbeat:generate_request(undefined,false),
- ?assert(is_binary(Data)).
+heartbeat1_test() ->
+ dubbo_id_generator:start_link(),
+ {ok, Data} = dubbo_heartbeat:generate_request(undefined, false),
+ ?assert(is_binary(Data)).
simple_test() ->
- ?assert(true).
+ ?assert(true).
diff --git a/test/dubbo_service.hrl b/test/dubbo_service.hrl
index e8a01e9..1153844 100644
--- a/test/dubbo_service.hrl
+++ b/test/dubbo_service.hrl
@@ -1,14 +1,30 @@
+%%------------------------------------------------------------------------------
+%% Licensed to the Apache Software Foundation (ASF) under one or more
+%% contributor license agreements. See the NOTICE file distributed with
+%% this work for additional information regarding copyright ownership.
+%% The ASF licenses this file to You under the Apache License, Version 2.0
+%% (the "License"); you may not use this file except in compliance with
+%% the License. You may obtain a copy of the License at
+%%
+%% http://www.apache.org/licenses/LICENSE-2.0
+%%
+%% Unless required by applicable law or agreed to in writing, software
+%% distributed under the License is distributed on an "AS IS" BASIS,
+%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+%% See the License for the specific language governing permissions and
+%% limitations under the License.
+%%------------------------------------------------------------------------------
--record(userInfoRequest,{
- username ::list(),
- requestId ::list()}).
+-record(userInfoRequest, {
+ username :: list(),
+ requestId :: list()}).
--record(userInfo,{
- userName ::list(),
- userId ::list(),
- userAge ::integer()}).
+-record(userInfo, {
+ userName :: list(),
+ userId :: list(),
+ userAge :: integer()}).
--record(userRes,{
- userlist ::[]}).
+-record(userRes, {
+ userlist :: []}).
diff --git a/test/dubbo_service_app.erl b/test/dubbo_service_app.erl
index 8f9d336..bde5980 100644
--- a/test/dubbo_service_app.erl
+++ b/test/dubbo_service_app.erl
@@ -1,8 +1,19 @@
-%%%-------------------------------------------------------------------
-%% @doc dubbo_service public API
-%% @end
-%%%-------------------------------------------------------------------
-
+%%------------------------------------------------------------------------------
+%% Licensed to the Apache Software Foundation (ASF) under one or more
+%% contributor license agreements. See the NOTICE file distributed with
+%% this work for additional information regarding copyright ownership.
+%% The ASF licenses this file to You under the Apache License, Version 2.0
+%% (the "License"); you may not use this file except in compliance with
+%% the License. You may obtain a copy of the License at
+%%
+%% http://www.apache.org/licenses/LICENSE-2.0
+%%
+%% Unless required by applicable law or agreed to in writing, software
+%% distributed under the License is distributed on an "AS IS" BASIS,
+%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+%% See the License for the specific language governing permissions and
+%% limitations under the License.
+%%------------------------------------------------------------------------------
-module(dubbo_service_app).
-behaviour(application).
@@ -31,10 +42,10 @@
%%====================================================================
-register_type_list()->
+register_type_list() ->
List = dubbo_service_type_list:get_list(),
lists:map(
- fun({NativeType,ForeignType,Fields}) ->
- dubbo_type_transfer:pre_process_typedef(NativeType,ForeignType,Fields)
- end,List),
+ fun({NativeType, ForeignType, Fields}) ->
+ dubbo_type_transfer:pre_process_typedef(NativeType, ForeignType, Fields)
+ end, List),
ok.
\ No newline at end of file
diff --git a/test/dubbo_service_sup.erl b/test/dubbo_service_sup.erl
index 7a9e48c..eb95c4d 100644
--- a/test/dubbo_service_sup.erl
+++ b/test/dubbo_service_sup.erl
@@ -1,8 +1,19 @@
-%%%-------------------------------------------------------------------
-%% @doc dubbo_service top level supervisor.
-%% @end
-%%%-------------------------------------------------------------------
-
+%%------------------------------------------------------------------------------
+%% Licensed to the Apache Software Foundation (ASF) under one or more
+%% contributor license agreements. See the NOTICE file distributed with
+%% this work for additional information regarding copyright ownership.
+%% The ASF licenses this file to You under the Apache License, Version 2.0
+%% (the "License"); you may not use this file except in compliance with
+%% the License. You may obtain a copy of the License at
+%%
+%% http://www.apache.org/licenses/LICENSE-2.0
+%%
+%% Unless required by applicable law or agreed to in writing, software
+%% distributed under the License is distributed on an "AS IS" BASIS,
+%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+%% See the License for the specific language governing permissions and
+%% limitations under the License.
+%%------------------------------------------------------------------------------
-module(dubbo_service_sup).
-behaviour(supervisor).
@@ -28,7 +39,7 @@
%% Child :: {Id,StartFunc,Restart,Shutdown,Type,Modules}
init([]) ->
- {ok, { {one_for_all, 0, 1}, []} }.
+ {ok, {{one_for_all, 0, 1}, []}}.
%%====================================================================
%% Internal functions
diff --git a/test/dubbo_service_type_list.erl b/test/dubbo_service_type_list.erl
index 1f01868..6c8f04d 100644
--- a/test/dubbo_service_type_list.erl
+++ b/test/dubbo_service_type_list.erl
@@ -1,15 +1,31 @@
+%%------------------------------------------------------------------------------
+%% Licensed to the Apache Software Foundation (ASF) under one or more
+%% contributor license agreements. See the NOTICE file distributed with
+%% this work for additional information regarding copyright ownership.
+%% The ASF licenses this file to You under the Apache License, Version 2.0
+%% (the "License"); you may not use this file except in compliance with
+%% the License. You may obtain a copy of the License at
+%%
+%% http://www.apache.org/licenses/LICENSE-2.0
+%%
+%% Unless required by applicable law or agreed to in writing, software
+%% distributed under the License is distributed on an "AS IS" BASIS,
+%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+%% See the License for the specific language governing permissions and
+%% limitations under the License.
+%%------------------------------------------------------------------------------
-module(dubbo_service_type_list).
%% API
--export([register_type_list/0,get_list/0]).
+-export([register_type_list/0, get_list/0]).
-include("dubbo_service.hrl").
-get_list()->
+get_list() ->
[
- {userInfoRequest,<<"com.ifcoder.demo.bean.UserInfoRequest">>,record_info(fields,userInfoRequest)},
- {userInfo,<<"com.ifcoder.demo.bean.UserInfo">>,record_info(fields,userInfo)},
- {userRes,<<"com.ifcoder.demo.bean.UserRes">>,record_info(fields,userRes)} ].
+ {userInfoRequest, <<"com.ifcoder.demo.bean.UserInfoRequest">>, record_info(fields, userInfoRequest)},
+ {userInfo, <<"com.ifcoder.demo.bean.UserInfo">>, record_info(fields, userInfo)},
+ {userRes, <<"com.ifcoder.demo.bean.UserRes">>, record_info(fields, userRes)}].
-register_type_list()->
+register_type_list() ->
ok.
\ No newline at end of file
diff --git a/test/dubbo_service_user_impl.erl b/test/dubbo_service_user_impl.erl
index 417e3fa..ce0d5c5 100644
--- a/test/dubbo_service_user_impl.erl
+++ b/test/dubbo_service_user_impl.erl
@@ -1,13 +1,21 @@
-%%%-------------------------------------------------------------------
-%%% @author dlive
-%%% @copyright (C) 2019, <COMPANY>
-%%% @doc
-%%%
-%%% @end
-%%% Created : 08. May 2019 11:06
-%%%-------------------------------------------------------------------
+%%------------------------------------------------------------------------------
+%% Licensed to the Apache Software Foundation (ASF) under one or more
+%% contributor license agreements. See the NOTICE file distributed with
+%% this work for additional information regarding copyright ownership.
+%% The ASF licenses this file to You under the Apache License, Version 2.0
+%% (the "License"); you may not use this file except in compliance with
+%% the License. You may obtain a copy of the License at
+%%
+%% http://www.apache.org/licenses/LICENSE-2.0
+%%
+%% Unless required by applicable law or agreed to in writing, software
+%% distributed under the License is distributed on an "AS IS" BASIS,
+%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+%% See the License for the specific language governing permissions and
+%% limitations under the License.
+%%------------------------------------------------------------------------------
-module(dubbo_service_user_impl).
--author("dlive").
+
-behaviour(user2).
@@ -15,25 +23,25 @@
-include_lib("dubboerl/include/hessian.hrl").
-include_lib("dubboerl/include/dubbo.hrl").
%% API
--export([getUserInfo/1,queryUserList/1,genUserId/0,queryUserInfo/1]).
+-export([getUserInfo/1, queryUserList/1, genUserId/0, queryUserInfo/1]).
-genUserId()->
- "newid".
+genUserId() ->
+ "newid".
getUserInfo(Args) ->
- io:format(user,"do invokeWs ~p",[Args]),
- #userInfo{userAge = 88,userName = "one", userId = "id123"}.
+ io:format(user, "do invokeWs ~p", [Args]),
+ #userInfo{userAge = 88, userName = "one", userId = "id123"}.
-queryUserList(Args)->
- User = #userInfo{userAge = 88,userName = "two", userId = "id123"},
- List = #list{len=1,type="java.util.ArrayList",values=[User]},
+queryUserList(Args) ->
+ User = #userInfo{userAge = 88, userName = "two", userId = "id123"},
+ List = #list{len = 1, type = "java.util.ArrayList", values = [User]},
- Res = #userRes{
- userlist = List
- },
- Res.
+ Res = #userRes{
+ userlist = List
+ },
+ Res.
-queryUserInfo(Arg0)->
- io:format(user,"do invoker queryUserInfo ~p",[Arg0]),
- #userInfo{userName = "uuname",userAge = 10,userId = "44"}.
\ No newline at end of file
+queryUserInfo(Arg0) ->
+ io:format(user, "do invoker queryUserInfo ~p", [Arg0]),
+ #userInfo{userName = "uuname", userAge = 10, userId = "44"}.
\ No newline at end of file
diff --git a/test/dubbo_traffic_control_tests.erl b/test/dubbo_traffic_control_tests.erl
index 141d3a3..e0ffff5 100644
--- a/test/dubbo_traffic_control_tests.erl
+++ b/test/dubbo_traffic_control_tests.erl
@@ -1,14 +1,20 @@
-%%%-------------------------------------------------------------------
-%%% @author dlive
-%%% @copyright (C) 2019, <COMPANY>
-%%% @doc
-%%%
-%%% @end
-%%% Created : 25. Apr 2019 12:41 AM
-%%%-------------------------------------------------------------------
+%%------------------------------------------------------------------------------
+%% Licensed to the Apache Software Foundation (ASF) under one or more
+%% contributor license agreements. See the NOTICE file distributed with
+%% this work for additional information regarding copyright ownership.
+%% The ASF licenses this file to You under the Apache License, Version 2.0
+%% (the "License"); you may not use this file except in compliance with
+%% the License. You may obtain a copy of the License at
+%%
+%% http://www.apache.org/licenses/LICENSE-2.0
+%%
+%% Unless required by applicable law or agreed to in writing, software
+%% distributed under the License is distributed on an "AS IS" BASIS,
+%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+%% See the License for the specific language governing permissions and
+%% limitations under the License.
+%%------------------------------------------------------------------------------
-module(dubbo_traffic_control_tests).
--author("dlive").
-
-include_lib("eunit/include/eunit.hrl").
init_test() ->
@@ -16,11 +22,11 @@
dubbo_traffic_control:init(),
?assert(true).
-goon_test()->
+goon_test() ->
dubbo_traffic_control:init(),
- ?assertEqual(dubbo_traffic_control:check_goon(key1,2),ok),
- ?assertEqual(dubbo_traffic_control:check_goon(key1,2),ok),
- ?assertEqual(dubbo_traffic_control:check_goon(key1,2),full),
- ?assertEqual(dubbo_traffic_control:check_goon(key1,2),full),
- ?assertEqual(dubbo_traffic_control:decr_count(key1),ok),
+ ?assertEqual(dubbo_traffic_control:check_goon(key1, 2), ok),
+ ?assertEqual(dubbo_traffic_control:check_goon(key1, 2), ok),
+ ?assertEqual(dubbo_traffic_control:check_goon(key1, 2), full),
+ ?assertEqual(dubbo_traffic_control:check_goon(key1, 2), full),
+ ?assertEqual(dubbo_traffic_control:decr_count(key1), ok),
ok.
diff --git a/test/dubbo_zookeeper_tests.erl b/test/dubbo_zookeeper_tests.erl
index 8d59b56..499feb6 100644
--- a/test/dubbo_zookeeper_tests.erl
+++ b/test/dubbo_zookeeper_tests.erl
@@ -1,19 +1,25 @@
-%%%-------------------------------------------------------------------
-%%% @author dlive
-%%% @copyright (C) 2017, <COMPANY>
-%%% @doc
-%%%
-%%% @end
-%%% Created : 26. Dec 2017 4:55 PM
-%%%-------------------------------------------------------------------
+%%------------------------------------------------------------------------------
+%% Licensed to the Apache Software Foundation (ASF) under one or more
+%% contributor license agreements. See the NOTICE file distributed with
+%% this work for additional information regarding copyright ownership.
+%% The ASF licenses this file to You under the Apache License, Version 2.0
+%% (the "License"); you may not use this file except in compliance with
+%% the License. You may obtain a copy of the License at
+%%
+%% http://www.apache.org/licenses/LICENSE-2.0
+%%
+%% Unless required by applicable law or agreed to in writing, software
+%% distributed under the License is distributed on an "AS IS" BASIS,
+%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+%% See the License for the specific language governing permissions and
+%% limitations under the License.
+%%------------------------------------------------------------------------------
-module(dubbo_zookeeper_tests).
--author("dlive").
-
-include_lib("eunit/include/eunit.hrl").
-include("dubbo.hrl").
exist_test() ->
- Consumer=#consumer_config{interface = <<"com.ifcoder.demo.facade.User">>,
- methods = [<<"a">>,<<"b">>]},
- V= dubbo_zookeeper:gen_consumer_node_info(Consumer),
- ?debugFmt("consumer info ~p",[V]),
+ Consumer = #consumer_config{interface = <<"com.ifcoder.demo.facade.User">>,
+ methods = [<<"a">>, <<"b">>]},
+ V = dubbo_zookeeper:gen_consumer_node_info(Consumer),
+ ?debugFmt("consumer info ~p", [V]),
?assert(is_binary(V)).
diff --git a/test/hessian_encode_tests.erl b/test/hessian_encode_tests.erl
index 5b951cb..ddb3502 100644
--- a/test/hessian_encode_tests.erl
+++ b/test/hessian_encode_tests.erl
@@ -1,39 +1,45 @@
-%%%-------------------------------------------------------------------
-%%% @author dlive
-%%% @copyright (C) 2016, <COMPANY>
-%%% @doc
-%%%
-%%% @end
-%%% Created : 18. 十月 2016 上午10:46
-%%%-------------------------------------------------------------------
+%%------------------------------------------------------------------------------
+%% Licensed to the Apache Software Foundation (ASF) under one or more
+%% contributor license agreements. See the NOTICE file distributed with
+%% this work for additional information regarding copyright ownership.
+%% The ASF licenses this file to You under the Apache License, Version 2.0
+%% (the "License"); you may not use this file except in compliance with
+%% the License. You may obtain a copy of the License at
+%%
+%% http://www.apache.org/licenses/LICENSE-2.0
+%%
+%% Unless required by applicable law or agreed to in writing, software
+%% distributed under the License is distributed on an "AS IS" BASIS,
+%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+%% See the License for the specific language governing permissions and
+%% limitations under the License.
+%%------------------------------------------------------------------------------
-module(hessian_encode_tests).
--author("dlive").
-
-include("hessian.hrl").
-include_lib("eunit/include/eunit.hrl").
%% API
-export([object_test/0]).
--record(de_TestReq, {name, nick,age}).
--record(de_reg2, {reqinfo,age}).
+-record(de_TestReq, {name, nick, age}).
+-record(de_reg2, {reqinfo, age}).
-object_test()->
+object_test() ->
ForeignTypeA = <<"com.ifcoder.demo.bean.UserInfoRequest">>,
TypeDefA = #type_def{foreign_type = ForeignTypeA,
native_type = de_TestReq,
- fieldnames = record_info(fields,de_TestReq)},
+ fieldnames = record_info(fields, de_TestReq)},
EncodingState0 = type_encoding:enlist(TypeDefA),
- RequestArg0 = #de_TestReq{name = <<"nameinfo">>, nick = <<"nickname">> ,age=10 },
+ RequestArg0 = #de_TestReq{name = <<"nameinfo">>, nick = <<"nickname">>, age = 10},
{Bin, State0} = cotton_hessian:encode(RequestArg0, EncodingState0),
type_register:init(),
- dubbo_type_transfer:pre_process_typedef(de_TestReq,<<"com.ifcoder.demo.bean.UserInfoRequest">>,record_info(fields,de_TestReq)),
- {<<>>,Data,State2 } = cotton_hessian:decode(Bin,cotton_hessian:init()),
- DecodeResult = dubbo_type_transfer:java_to_native(Data,State2),
- ?assert(is_record(DecodeResult,de_TestReq)),
- ?assertEqual(DecodeResult#de_TestReq.name,<<"nameinfo">>),
- ?assertEqual(DecodeResult#de_TestReq.nick,<<"nickname">>),
- ?assertEqual(DecodeResult#de_TestReq.age,10),
- ?debugFmt("get decode info ~p",[DecodeResult]),
+ dubbo_type_transfer:pre_process_typedef(de_TestReq, <<"com.ifcoder.demo.bean.UserInfoRequest">>, record_info(fields, de_TestReq)),
+ {<<>>, Data, State2} = cotton_hessian:decode(Bin, cotton_hessian:init()),
+ DecodeResult = dubbo_type_transfer:java_to_native(Data, State2),
+ ?assert(is_record(DecodeResult, de_TestReq)),
+ ?assertEqual(DecodeResult#de_TestReq.name, <<"nameinfo">>),
+ ?assertEqual(DecodeResult#de_TestReq.nick, <<"nickname">>),
+ ?assertEqual(DecodeResult#de_TestReq.age, 10),
+ ?debugFmt("get decode info ~p", [DecodeResult]),
ok.
diff --git a/test/user2.erl b/test/user2.erl
index 3b406e1..7a9daaf 100644
--- a/test/user2.erl
+++ b/test/user2.erl
@@ -1,10 +1,26 @@
+%%------------------------------------------------------------------------------
+%% Licensed to the Apache Software Foundation (ASF) under one or more
+%% contributor license agreements. See the NOTICE file distributed with
+%% this work for additional information regarding copyright ownership.
+%% The ASF licenses this file to You under the Apache License, Version 2.0
+%% (the "License"); you may not use this file except in compliance with
+%% the License. You may obtain a copy of the License at
+%%
+%% http://www.apache.org/licenses/LICENSE-2.0
+%%
+%% Unless required by applicable law or agreed to in writing, software
+%% distributed under the License is distributed on an "AS IS" BASIS,
+%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+%% See the License for the specific language governing permissions and
+%% limitations under the License.
+%%------------------------------------------------------------------------------
-module(user2).
-include_lib("dubboerl/include/dubbo.hrl").
-include_lib("dubboerl/include/hessian.hrl").
--define(CURRENT_CLASS_NAME,<<"com.ifcoder.demo.facade.User"/utf8>>).
--define(CURRENT_CLASS_VERSION,<<"0.0.0"/utf8>>).
+-define(CURRENT_CLASS_NAME, <<"com.ifcoder.demo.facade.User"/utf8>>).
+-define(CURRENT_CLASS_VERSION, <<"0.0.0"/utf8>>).
-include("dubbo_service.hrl").
@@ -25,29 +41,29 @@
-export([get_method_999_list/0]).
%% behaviour
--callback getUserInfo(Arg0::list())-> #userInfo{}.
--callback genUserId()-> list().
--callback queryUserInfo(Arg0::#userInfoRequest{})-> #userInfo{}.
--callback queryUserList(Arg0::list())-> #userRes{}.
+-callback getUserInfo(Arg0 :: list()) -> #userInfo{}.
+-callback genUserId() -> list().
+-callback queryUserInfo(Arg0 :: #userInfoRequest{}) -> #userInfo{}.
+-callback queryUserList(Arg0 :: list()) -> #userRes{}.
-get_method_999_list()->
+get_method_999_list() ->
[
- getUserInfo,
- genUserId,
- queryUserInfo,
- queryUserList].
+ getUserInfo,
+ genUserId,
+ queryUserInfo,
+ queryUserList].
--spec getUserInfo(Arg0::list())->
- {ok,reference()}|
- {ok,reference(),Data::#userInfo{},RpcContent::list()}|
- {error,Reason::timeout|no_provider|any()}.
-getUserInfo(Arg0)->
- getUserInfo(Arg0 ,#{}).
+-spec getUserInfo(Arg0 :: list()) ->
+ {ok, reference()}|
+ {ok, reference(), Data :: #userInfo{}, RpcContent :: list()}|
+ {error, Reason :: timeout|no_provider|any()}.
+getUserInfo(Arg0) ->
+ getUserInfo(Arg0, #{}).
-getUserInfo(Arg0, RequestOption)->
-
+getUserInfo(Arg0, RequestOption) ->
+
Data = #dubbo_rpc_invocation{
className = ?CURRENT_CLASS_NAME,
classVersion = ?CURRENT_CLASS_VERSION,
@@ -55,59 +71,59 @@
parameterDesc = <<"Ljava/lang/String;"/utf8>>,
parameterTypes = [
#type_def{foreign_type = <<"java.lang.String">>,
- native_type = string,
- fieldnames = []}
+ native_type = string,
+ fieldnames = []}
],
parameters = [
Arg0
],
attachments = [
{<<"path">>, ?CURRENT_CLASS_NAME},
- {<<"interface">> , ?CURRENT_CLASS_NAME}
+ {<<"interface">>, ?CURRENT_CLASS_NAME}
]
},
Request = dubbo_adapter:reference(Data),
- dubbo_invoker:invoke_request(?CURRENT_CLASS_NAME,Request,RequestOption).
+ dubbo_invoker:invoke_request(?CURRENT_CLASS_NAME, Request, RequestOption).
--spec genUserId()->
- {ok,reference()}|
- {ok,reference(),Data::list(),RpcContent::list()}|
- {error,Reason::timeout|no_provider|any()}.
-genUserId()->
- genUserId( #{}).
+-spec genUserId() ->
+ {ok, reference()}|
+ {ok, reference(), Data :: list(), RpcContent :: list()}|
+ {error, Reason :: timeout|no_provider|any()}.
+genUserId() ->
+ genUserId(#{}).
-genUserId( RequestOption)->
-
+genUserId(RequestOption) ->
+
Data = #dubbo_rpc_invocation{
className = ?CURRENT_CLASS_NAME,
classVersion = ?CURRENT_CLASS_VERSION,
methodName = <<"genUserId">>,
parameterDesc = <<""/utf8>>,
parameterTypes = [
-
+
],
parameters = [
-
+
],
attachments = [
{<<"path">>, ?CURRENT_CLASS_NAME},
- {<<"interface">> , ?CURRENT_CLASS_NAME}
+ {<<"interface">>, ?CURRENT_CLASS_NAME}
]
},
Request = dubbo_adapter:reference(Data),
- dubbo_invoker:invoke_request(?CURRENT_CLASS_NAME,Request,RequestOption).
+ dubbo_invoker:invoke_request(?CURRENT_CLASS_NAME, Request, RequestOption).
--spec queryUserInfo(Arg0::#userInfoRequest{})->
- {ok,reference()}|
- {ok,reference(),Data::#userInfo{},RpcContent::list()}|
- {error,Reason::timeout|no_provider|any()}.
-queryUserInfo(Arg0)->
- queryUserInfo(Arg0 ,#{}).
+-spec queryUserInfo(Arg0 :: #userInfoRequest{}) ->
+ {ok, reference()}|
+ {ok, reference(), Data :: #userInfo{}, RpcContent :: list()}|
+ {error, Reason :: timeout|no_provider|any()}.
+queryUserInfo(Arg0) ->
+ queryUserInfo(Arg0, #{}).
-queryUserInfo(Arg0, RequestOption)->
-
+queryUserInfo(Arg0, RequestOption) ->
+
Data = #dubbo_rpc_invocation{
className = ?CURRENT_CLASS_NAME,
classVersion = ?CURRENT_CLASS_VERSION,
@@ -115,30 +131,30 @@
parameterDesc = <<"Lcom/ifcoder/demo/bean/UserInfoRequest;"/utf8>>,
parameterTypes = [
#type_def{foreign_type = <<"com.ifcoder.demo.bean.UserInfoRequest">>,
- native_type = userInfoRequest,
- fieldnames = record_info(fields,userInfoRequest)}
+ native_type = userInfoRequest,
+ fieldnames = record_info(fields, userInfoRequest)}
],
parameters = [
Arg0
],
attachments = [
{<<"path">>, ?CURRENT_CLASS_NAME},
- {<<"interface">> , ?CURRENT_CLASS_NAME}
+ {<<"interface">>, ?CURRENT_CLASS_NAME}
]
},
Request = dubbo_adapter:reference(Data),
- dubbo_invoker:invoke_request(?CURRENT_CLASS_NAME,Request,RequestOption).
+ dubbo_invoker:invoke_request(?CURRENT_CLASS_NAME, Request, RequestOption).
--spec queryUserList(Arg0::list())->
- {ok,reference()}|
- {ok,reference(),Data::#userRes{},RpcContent::list()}|
- {error,Reason::timeout|no_provider|any()}.
-queryUserList(Arg0)->
- queryUserList(Arg0 ,#{}).
+-spec queryUserList(Arg0 :: list()) ->
+ {ok, reference()}|
+ {ok, reference(), Data :: #userRes{}, RpcContent :: list()}|
+ {error, Reason :: timeout|no_provider|any()}.
+queryUserList(Arg0) ->
+ queryUserList(Arg0, #{}).
-queryUserList(Arg0, RequestOption)->
-
+queryUserList(Arg0, RequestOption) ->
+
Data = #dubbo_rpc_invocation{
className = ?CURRENT_CLASS_NAME,
classVersion = ?CURRENT_CLASS_VERSION,
@@ -146,20 +162,20 @@
parameterDesc = <<"Ljava/lang/String;"/utf8>>,
parameterTypes = [
#type_def{foreign_type = <<"java.lang.String">>,
- native_type = string,
- fieldnames = []}
+ native_type = string,
+ fieldnames = []}
],
parameters = [
Arg0
],
attachments = [
{<<"path">>, ?CURRENT_CLASS_NAME},
- {<<"interface">> , ?CURRENT_CLASS_NAME}
+ {<<"interface">>, ?CURRENT_CLASS_NAME}
]
},
Request = dubbo_adapter:reference(Data),
- dubbo_invoker:invoke_request(?CURRENT_CLASS_NAME,Request,RequestOption).
+ dubbo_invoker:invoke_request(?CURRENT_CLASS_NAME, Request, RequestOption).
-test()->
- queryUserInfo(#userInfoRequest{username = "name",requestId = "111"},#{sync=> true}).
\ No newline at end of file
+test() ->
+ queryUserInfo(#userInfoRequest{username = "name", requestId = "111"}, #{sync=> true}).
\ No newline at end of file
diff --git a/tools/erlanalysis/src/main/java/org/apache/dubbo/erlang/analysis/App.java b/tools/erlanalysis/src/main/java/org/apache/dubbo/erlang/analysis/App.java
index 9362bc0..e00c2ff 100644
--- a/tools/erlanalysis/src/main/java/org/apache/dubbo/erlang/analysis/App.java
+++ b/tools/erlanalysis/src/main/java/org/apache/dubbo/erlang/analysis/App.java
@@ -1,3 +1,20 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
package org.apache.dubbo.erlang.analysis;
import com.caucho.hessian.io.HessianInput;
@@ -9,14 +26,9 @@
import static java.lang.System.exit;
-/**
- * Hello world!
- *
- */
-public class App
-{
+public class App {
public static void writesome() throws IOException {
- UserInfo user=new UserInfo();
+ UserInfo user = new UserInfo();
user.setAge(10);
user.setUsername("userabc");
user.setPassword("password");
@@ -40,21 +52,22 @@
ByteArrayInputStream is = new ByteArrayInputStream(buffer);
HessianInput hi = new HessianInput(is);
Object obj = hi.readObject();
- System.out.println("obj:"+obj);
- UserInfo user = (UserInfo)obj;
- System.out.println("user:"+user);
+ System.out.println("obj:" + obj);
+ UserInfo user = (UserInfo) obj;
+ System.out.println("user:" + user);
}
- public static void main( String[] args ){
- if (args.length<3){
+
+ public static void main(String[] args) {
+ if (args.length < 3) {
System.out.println("please input args: group artifactid version");
exit(1);
}
- String group=args[0];
- String artifactid=args[1];
+ String group = args[0];
+ String artifactid = args[1];
String version = args[2];
- System.out.println("will parse facade "+ group+":"+artifactid+":"+version);
+ System.out.println("will parse facade " + group + ":" + artifactid + ":" + version);
InterfaceParse parser = new InterfaceParse();
- parser.parse(group,artifactid,version);
+ parser.parse(group, artifactid, version);
//
// try {
//// readsome();
diff --git a/tools/erlanalysis/src/main/java/org/apache/dubbo/erlang/analysis/Start.java b/tools/erlanalysis/src/main/java/org/apache/dubbo/erlang/analysis/Start.java
index f968517..24e4453 100644
--- a/tools/erlanalysis/src/main/java/org/apache/dubbo/erlang/analysis/Start.java
+++ b/tools/erlanalysis/src/main/java/org/apache/dubbo/erlang/analysis/Start.java
@@ -1,3 +1,20 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
package org.apache.dubbo.erlang.analysis;
import org.apache.dubbo.erlang.analysis.parse.InterfaceParse;
diff --git a/tools/erlanalysis/src/main/java/org/apache/dubbo/erlang/analysis/erltool/UserInfo.java b/tools/erlanalysis/src/main/java/org/apache/dubbo/erlang/analysis/erltool/UserInfo.java
index d4651d9..2e71e3c 100644
--- a/tools/erlanalysis/src/main/java/org/apache/dubbo/erlang/analysis/erltool/UserInfo.java
+++ b/tools/erlanalysis/src/main/java/org/apache/dubbo/erlang/analysis/erltool/UserInfo.java
@@ -1,16 +1,30 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
package org.apache.dubbo.erlang.analysis.erltool;
import java.io.Serializable;
-/**
- * Created by dlive on 16/9/29.
- */
public class UserInfo implements Serializable {
private String username;
private Integer age;
private String password;
- public UserInfo(){
+ public UserInfo() {
}
diff --git a/tools/erlanalysis/src/main/java/org/apache/dubbo/erlang/analysis/generater/ErlProjectGenerater.java b/tools/erlanalysis/src/main/java/org/apache/dubbo/erlang/analysis/generater/ErlProjectGenerater.java
index 638960e..f648700 100644
--- a/tools/erlanalysis/src/main/java/org/apache/dubbo/erlang/analysis/generater/ErlProjectGenerater.java
+++ b/tools/erlanalysis/src/main/java/org/apache/dubbo/erlang/analysis/generater/ErlProjectGenerater.java
@@ -1,3 +1,20 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
package org.apache.dubbo.erlang.analysis.generater;
import org.apache.dubbo.erlang.analysis.parse.CommonTypeInfo;
@@ -12,9 +29,6 @@
import java.io.*;
import java.util.List;
-/**
- * Created by dlive on 22/02/2018.
- */
public class ErlProjectGenerater {
private VelocityEngine ve = new VelocityEngine();
@@ -22,8 +36,9 @@
private String projectSaveDir;
private String projectSrcDir;
private String projectIncludeDir;
- public ErlProjectGenerater(ProjectInfo projectInfo){
- this.projectInfo=projectInfo;
+
+ public ErlProjectGenerater(ProjectInfo projectInfo) {
+ this.projectInfo = projectInfo;
ve.setProperty(RuntimeConstants.RESOURCE_LOADER, "classpath");
ve.setProperty("classpath.resource.loader.class", ClasspathResourceLoader.class.getName());
@@ -31,7 +46,8 @@
makeProjectDir();
}
- public void genProject(List<InterfaceInfo> list_interfaces){
+
+ public void genProject(List<InterfaceInfo> list_interfaces) {
for (InterfaceInfo interfaceItem : list_interfaces) {
genInterface(interfaceItem);
}
@@ -40,26 +56,26 @@
genProjectTypeList();
}
- private boolean genInterface(InterfaceInfo interfaceItem){
+ private boolean genInterface(InterfaceInfo interfaceItem) {
// 获取模板文件
Template t = ve.getTemplate("templates/interface.vm");
// 设置变量
VelocityContext ctx = new VelocityContext();
- ctx.put("appName",projectInfo.getAppName());
+ ctx.put("appName", projectInfo.getAppName());
ctx.put("moduleName", interfaceItem.getModuleName());
- ctx.put("className",interfaceItem.getInterfaceName());
- ctx.put("methodList",interfaceItem.getMethods());
+ ctx.put("className", interfaceItem.getInterfaceName());
+ ctx.put("methodList", interfaceItem.getMethods());
// 输出
StringWriter sw = new StringWriter();
- t.merge(ctx,sw);
+ t.merge(ctx, sw);
FileWriter sourceFile = null;
try {
- sourceFile = new FileWriter(this.projectSrcDir+ File.separator+interfaceItem.getModuleName()+".erl");
+ sourceFile = new FileWriter(this.projectSrcDir + File.separator + interfaceItem.getModuleName() + ".erl");
sourceFile.write(sw.toString());
} catch (IOException e) {
e.printStackTrace();
- }finally {
+ } finally {
try {
sourceFile.close();
} catch (IOException e) {
@@ -69,28 +85,28 @@
return true;
}
- private boolean makeProjectDir(){
+ private boolean makeProjectDir() {
String savedir = System.getProperty("user.dir") + File.separator + "genProjectDir";
- projectSaveDir=String.format("%s%s%s",savedir,File.separator,projectInfo.getAppName());
+ projectSaveDir = String.format("%s%s%s", savedir, File.separator, projectInfo.getAppName());
File rootDir = new File(projectSaveDir);
- if(!rootDir.exists()){
- if(!rootDir.mkdirs()){
+ if (!rootDir.exists()) {
+ if (!rootDir.mkdirs()) {
return false;
}
}
- projectSrcDir=String.format("%s%ssrc",projectSaveDir,File.separator);
- File projectSrcFile= new File(projectSrcDir);
- if(!projectSrcFile.exists()){
- if(!projectSrcFile.mkdirs()){
+ projectSrcDir = String.format("%s%ssrc", projectSaveDir, File.separator);
+ File projectSrcFile = new File(projectSrcDir);
+ if (!projectSrcFile.exists()) {
+ if (!projectSrcFile.mkdirs()) {
return false;
}
}
- projectIncludeDir=String.format("%s%sinclude",projectSaveDir,File.separator);
- File projectIncludeFile= new File(projectIncludeDir);
- if(!projectIncludeFile.exists()){
- if(!projectIncludeFile.mkdirs()){
+ projectIncludeDir = String.format("%s%sinclude", projectSaveDir, File.separator);
+ File projectIncludeFile = new File(projectIncludeDir);
+ if (!projectIncludeFile.exists()) {
+ if (!projectIncludeFile.mkdirs()) {
return false;
}
}
@@ -99,14 +115,15 @@
/**
* 生成项目公共文件
+ *
* @return
*/
- private boolean genProjectCommonFile(){
+ private boolean genProjectCommonFile() {
// 获取模板文件
VelocityContext ctx = new VelocityContext();
- ctx.put("appName",projectInfo.getAppName());
- ctx.put("appVersion",projectInfo.getAppVersion());
+ ctx.put("appName", projectInfo.getAppName());
+ ctx.put("appVersion", projectInfo.getAppVersion());
FileWriter appFile = null;
@@ -116,26 +133,26 @@
// 输出
Template appTpl = ve.getTemplate("templates/app.vm");
StringWriter appFileWriter = new StringWriter();
- appTpl.merge(ctx,appFileWriter);
+ appTpl.merge(ctx, appFileWriter);
- appFile = new FileWriter(this.projectSrcDir+ File.separator+projectInfo.getAppName()+"_app.erl");
+ appFile = new FileWriter(this.projectSrcDir + File.separator + projectInfo.getAppName() + "_app.erl");
appFile.write(appFileWriter.toString());
// 输出
Template appSrcTpl = ve.getTemplate("templates/app_src.vm");
StringWriter appSrcFileWriter = new StringWriter();
- appSrcTpl.merge(ctx,appSrcFileWriter);
- appSrcFile = new FileWriter(this.projectSrcDir+ File.separator+projectInfo.getAppName()+".app.src");
+ appSrcTpl.merge(ctx, appSrcFileWriter);
+ appSrcFile = new FileWriter(this.projectSrcDir + File.separator + projectInfo.getAppName() + ".app.src");
appSrcFile.write(appSrcFileWriter.toString());
Template appSupTpl = ve.getTemplate("templates/app_sup.vm");
StringWriter appSupFileWriter = new StringWriter();
- appSupTpl.merge(ctx,appSupFileWriter);
- appSupFile = new FileWriter(this.projectSrcDir+ File.separator+projectInfo.getAppName()+"_sup.erl");
+ appSupTpl.merge(ctx, appSupFileWriter);
+ appSupFile = new FileWriter(this.projectSrcDir + File.separator + projectInfo.getAppName() + "_sup.erl");
appSupFile.write(appSupFileWriter.toString());
} catch (IOException e) {
e.printStackTrace();
- }finally {
+ } finally {
try {
appFile.close();
} catch (IOException e) {
@@ -155,7 +172,7 @@
return true;
}
- private void genProjectIncludeInfo(){
+ private void genProjectIncludeInfo() {
// 获取模板文件
Template t = ve.getTemplate("templates/app_type_include.vm");
// 设置变量
@@ -163,25 +180,25 @@
ctx.put("typeList", CommonTypeInfo.getInstances().getCommonTypeList());
// 输出
StringWriter sw = new StringWriter();
- t.merge(ctx,sw);
- writeFile(this.projectIncludeDir+File.separator+projectInfo.getAppName()+".hrl",sw.toString());
+ t.merge(ctx, sw);
+ writeFile(this.projectIncludeDir + File.separator + projectInfo.getAppName() + ".hrl", sw.toString());
}
- private void genProjectTypeList(){
+ private void genProjectTypeList() {
// 获取模板文件
Template t = ve.getTemplate("templates/app_type_list.vm");
// 设置变量
VelocityContext ctx = new VelocityContext();
- ctx.put("appName",projectInfo.getAppName());
+ ctx.put("appName", projectInfo.getAppName());
ctx.put("typeList", CommonTypeInfo.getInstances().getCommonTypeList());
// 输出
StringWriter sw = new StringWriter();
- t.merge(ctx,sw);
- writeFile(this.projectSrcDir+File.separator+projectInfo.getAppName()+"_type_list.erl",sw.toString());
+ t.merge(ctx, sw);
+ writeFile(this.projectSrcDir + File.separator + projectInfo.getAppName() + "_type_list.erl", sw.toString());
}
- private boolean writeFile(String filePath,String content){
+ private boolean writeFile(String filePath, String content) {
FileWriter sourceFile = null;
try {
sourceFile = new FileWriter(filePath);
@@ -189,7 +206,7 @@
} catch (IOException e) {
e.printStackTrace();
return false;
- }finally {
+ } finally {
try {
sourceFile.close();
} catch (IOException e) {
diff --git a/tools/erlanalysis/src/main/java/org/apache/dubbo/erlang/analysis/generater/ProjectInfo.java b/tools/erlanalysis/src/main/java/org/apache/dubbo/erlang/analysis/generater/ProjectInfo.java
index 819aa9c..45795d0 100644
--- a/tools/erlanalysis/src/main/java/org/apache/dubbo/erlang/analysis/generater/ProjectInfo.java
+++ b/tools/erlanalysis/src/main/java/org/apache/dubbo/erlang/analysis/generater/ProjectInfo.java
@@ -1,19 +1,33 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
package org.apache.dubbo.erlang.analysis.generater;
-/**
- * Created by dlive on 22/02/2018.
- */
public class ProjectInfo {
private String appName;
private String appVersion;
private String prefix;
public String getAppName() {
- return appName.replace("-","_");
+ return appName.replace("-", "_");
}
public void setAppName(String appName) {
- this.appName = appName.replace("-","_");
+ this.appName = appName.replace("-", "_");
}
public String getPrefix() {
diff --git a/tools/erlanalysis/src/main/java/org/apache/dubbo/erlang/analysis/parse/CommonTypeFieldInfo.java b/tools/erlanalysis/src/main/java/org/apache/dubbo/erlang/analysis/parse/CommonTypeFieldInfo.java
index 041271a..00a262c 100644
--- a/tools/erlanalysis/src/main/java/org/apache/dubbo/erlang/analysis/parse/CommonTypeFieldInfo.java
+++ b/tools/erlanalysis/src/main/java/org/apache/dubbo/erlang/analysis/parse/CommonTypeFieldInfo.java
@@ -1,10 +1,24 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
package org.apache.dubbo.erlang.analysis.parse;
import org.apache.dubbo.erlang.analysis.utils.ErlTypeTransformUtil;
-/**
- * Created by dlive on 26/02/2018.
- */
public class CommonTypeFieldInfo {
private String fieldName;
private Class<?> fieldType;
@@ -25,7 +39,7 @@
this.fieldType = fieldType;
}
- public String getFieldErlType(){
+ public String getFieldErlType() {
return ErlTypeTransformUtil.fullClassNameToErlType(fieldType.getName());
}
}
diff --git a/tools/erlanalysis/src/main/java/org/apache/dubbo/erlang/analysis/parse/CommonTypeInfo.java b/tools/erlanalysis/src/main/java/org/apache/dubbo/erlang/analysis/parse/CommonTypeInfo.java
index 4cdf1b0..6a2a6f2 100644
--- a/tools/erlanalysis/src/main/java/org/apache/dubbo/erlang/analysis/parse/CommonTypeInfo.java
+++ b/tools/erlanalysis/src/main/java/org/apache/dubbo/erlang/analysis/parse/CommonTypeInfo.java
@@ -1,3 +1,20 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
package org.apache.dubbo.erlang.analysis.parse;
import java.beans.IntrospectionException;
@@ -11,44 +28,42 @@
public class CommonTypeInfo {
- private static CommonTypeInfo obj;
- private final static Logger logger= LoggerFactory.getLogger(CommonTypeInfo.class);
+ private static CommonTypeInfo obj;
+ private final static Logger logger = LoggerFactory.getLogger(CommonTypeInfo.class);
-// private Set commonTypeList=new HashSet();
- private Map<String,CommonTypeItem> commonTypeList= new HashMap<>();
+ private Map<String, CommonTypeItem> commonTypeList = new HashMap<>();
- public static CommonTypeInfo getInstances(){
- if(obj==null){
- obj=new CommonTypeInfo();
+ public static CommonTypeInfo getInstances() {
+ if (obj == null) {
+ obj = new CommonTypeInfo();
}
return obj;
}
- public static void add(String commonArgType){
+ public static void add(String commonArgType) {
CommonTypeInfo typeinfo = getInstances();
typeinfo.parseTypeinfo(commonArgType);
}
-
- private void addCommonTypeList(String typeName,CommonTypeItem item){
+ private void addCommonTypeList(String typeName, CommonTypeItem item) {
}
- private void parseTypeinfo(String typeName){
- if(commonTypeList.get(typeName)!=null){
+ private void parseTypeinfo(String typeName) {
+ if (commonTypeList.get(typeName) != null) {
return;
}
- logger.info("will parse type info {}",typeName);
+ logger.info("will parse type info {}", typeName);
Type type = Type.getObjectType(typeName);
- switch (type.getSort()){
+ switch (type.getSort()) {
case Type.ARRAY:
//todo
break;
case Type.OBJECT:
- if(isTypeNeedParse(type.getClassName())){
+ if (isTypeNeedParse(type.getClassName())) {
parseTypeDetailInfo(type);
- }else if(type.getClassName().startsWith("java.util.List")){
+ } else if (type.getClassName().startsWith("java.util.List")) {
}
break;
@@ -56,21 +71,21 @@
}
}
- private void parseTypeDetailInfo(Type type){
+ private void parseTypeDetailInfo(Type type) {
CommonTypeItem typeItem = new CommonTypeItem();
typeItem.setClassName(type.getClassName());
Class classObj = null;
try {
- classObj = Class.forName(type.getClassName(),false,Thread.currentThread().getContextClassLoader());
+ classObj = Class.forName(type.getClassName(), false, Thread.currentThread().getContextClassLoader());
Field[] fields = classObj.getDeclaredFields();
- for (Field field: fields) {
+ for (Field field : fields) {
try {
- PropertyDescriptor propertyDesc = new PropertyDescriptor(field.getName(),classObj);
- if(propertyDesc.getReadMethod()==null && propertyDesc.getWriteMethod()==null){
+ PropertyDescriptor propertyDesc = new PropertyDescriptor(field.getName(), classObj);
+ if (propertyDesc.getReadMethod() == null && propertyDesc.getWriteMethod() == null) {
continue;
}
} catch (IntrospectionException e) {
- logger.warn("get field property error",e);
+ logger.warn("get field property error", e);
continue;
}
CommonTypeFieldInfo fieldInfo = new CommonTypeFieldInfo();
@@ -80,8 +95,8 @@
//判断该类型是否需要继续解析
parseTypeinfo(field.getType().getName());
}
- commonTypeList.put(type.getClassName(),typeItem);
- logger.debug("parse type detail success {}",type.getClassName());
+ commonTypeList.put(type.getClassName(), typeItem);
+ logger.debug("parse type detail success {}", type.getClassName());
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
@@ -89,19 +104,20 @@
}
- public List<CommonTypeItem> getCommonTypeList(){
- List<CommonTypeItem> list=new ArrayList<>(commonTypeList.size());
- for (Map.Entry<String, CommonTypeItem> item:commonTypeList.entrySet()){
- CommonTypeItem type=item.getValue();
- if(type.getTypeName().equals("list")){
+ public List<CommonTypeItem> getCommonTypeList() {
+ List<CommonTypeItem> list = new ArrayList<>(commonTypeList.size());
+ for (Map.Entry<String, CommonTypeItem> item : commonTypeList.entrySet()) {
+ CommonTypeItem type = item.getValue();
+ if (type.getTypeName().equals("list")) {
continue;
}
list.add(item.getValue());
}
return list;
}
- public boolean isTypeNeedParse(String typeName){
- if(typeName.startsWith("java.lang")|| typeName.equals("int") || typeName.equals("double") || typeName.equals("float")){
+
+ public boolean isTypeNeedParse(String typeName) {
+ if (typeName.startsWith("java.lang") || typeName.equals("int") || typeName.equals("double") || typeName.equals("float")) {
return false;
}
return true;
diff --git a/tools/erlanalysis/src/main/java/org/apache/dubbo/erlang/analysis/parse/CommonTypeItem.java b/tools/erlanalysis/src/main/java/org/apache/dubbo/erlang/analysis/parse/CommonTypeItem.java
index cbe96e2..ab6b571 100644
--- a/tools/erlanalysis/src/main/java/org/apache/dubbo/erlang/analysis/parse/CommonTypeItem.java
+++ b/tools/erlanalysis/src/main/java/org/apache/dubbo/erlang/analysis/parse/CommonTypeItem.java
@@ -1,3 +1,20 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
package org.apache.dubbo.erlang.analysis.parse;
import org.apache.dubbo.erlang.analysis.utils.ErlTypeTransformUtil;
@@ -5,12 +22,9 @@
import java.util.HashSet;
import java.util.Set;
-/**
- * Created by dlive on 26/02/2018.
- */
public class CommonTypeItem {
private String className;
- private Set fields=new HashSet();
+ private Set fields = new HashSet();
public String getClassName() {
return className;
@@ -27,20 +41,22 @@
public void setFields(Set fields) {
this.fields = fields;
}
- public void addField(CommonTypeFieldInfo field){
+
+ public void addField(CommonTypeFieldInfo field) {
fields.add(field);
}
/**
* 获取类型名称
+ *
* @return
*/
- public String getTypeName(){
+ public String getTypeName() {
return ErlTypeTransformUtil.fullClassNameToLowerShortName(className);
}
- public CommonTypeFieldInfo[] getFieldList(){
- CommonTypeFieldInfo[] ret=new CommonTypeFieldInfo[fields.size()];
+ public CommonTypeFieldInfo[] getFieldList() {
+ CommonTypeFieldInfo[] ret = new CommonTypeFieldInfo[fields.size()];
fields.toArray(ret);
return ret;
}
diff --git a/tools/erlanalysis/src/main/java/org/apache/dubbo/erlang/analysis/parse/InterfaceInfo.java b/tools/erlanalysis/src/main/java/org/apache/dubbo/erlang/analysis/parse/InterfaceInfo.java
index 76d568d..b6c4dd9 100644
--- a/tools/erlanalysis/src/main/java/org/apache/dubbo/erlang/analysis/parse/InterfaceInfo.java
+++ b/tools/erlanalysis/src/main/java/org/apache/dubbo/erlang/analysis/parse/InterfaceInfo.java
@@ -1,3 +1,20 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
package org.apache.dubbo.erlang.analysis.parse;
import java.util.ArrayList;
@@ -11,10 +28,10 @@
return interfaceName;
}
- public String getModuleName(){
- String moduleName= interfaceName.substring(interfaceName.lastIndexOf(".")+1);
+ public String getModuleName() {
+ String moduleName = interfaceName.substring(interfaceName.lastIndexOf(".") + 1);
moduleName = moduleName.substring(0, 1).toLowerCase() + moduleName.substring(1);
- moduleName = moduleName.replace('-','_');
+ moduleName = moduleName.replace('-', '_');
return moduleName;
}
@@ -27,9 +44,10 @@
return methods;
}
- public void getMethodExportList(){
+ public void getMethodExportList() {
}
+
public void addMethods(MethodInfo method) {
this.methods.add(method);
}
diff --git a/tools/erlanalysis/src/main/java/org/apache/dubbo/erlang/analysis/parse/InterfaceParse.java b/tools/erlanalysis/src/main/java/org/apache/dubbo/erlang/analysis/parse/InterfaceParse.java
index 136741c..444264e 100644
--- a/tools/erlanalysis/src/main/java/org/apache/dubbo/erlang/analysis/parse/InterfaceParse.java
+++ b/tools/erlanalysis/src/main/java/org/apache/dubbo/erlang/analysis/parse/InterfaceParse.java
@@ -1,3 +1,20 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
package org.apache.dubbo.erlang.analysis.parse;
import org.apache.dubbo.erlang.analysis.generater.ErlProjectGenerater;
@@ -15,18 +32,18 @@
import java.util.List;
public class InterfaceParse {
- private final static Logger logger= LoggerFactory.getLogger(InterfaceParse.class);
+ private final static Logger logger = LoggerFactory.getLogger(InterfaceParse.class);
- public void parse(String group,String artifactid,String version){
+ public void parse(String group, String artifactid, String version) {
MavenJarUtil mavenInfo = new MavenJarUtil(group, artifactid, version);
- if(!mavenInfo.copyDependence()){
+ if (!mavenInfo.copyDependence()) {
logger.error("download maven jar error");
}
- String parserJarPath=mavenInfo.getMainJarPath();
- logger.info("parse main jar "+ parserJarPath);
- loadDependencyJar(mavenInfo.getRootDir()+File.separator+"lib");
+ String parserJarPath = mavenInfo.getMainJarPath();
+ logger.info("parse main jar " + parserJarPath);
+ loadDependencyJar(mavenInfo.getRootDir() + File.separator + "lib");
ParseJarInterfaceInfo parser = new ParseJarInterfaceInfo();
List<InterfaceInfo> interfaceList = parser.parseJar(parserJarPath);
@@ -40,32 +57,32 @@
}
- private boolean loadDependencyJar(String rootPath){
+ private boolean loadDependencyJar(String rootPath) {
File jarPathFile = new File(rootPath);
- if(!jarPathFile.exists() || jarPathFile.isFile() ){
- logger.error("load dependency error target dir unexist {}",rootPath);
+ if (!jarPathFile.exists() || jarPathFile.isFile()) {
+ logger.error("load dependency error target dir unexist {}", rootPath);
return false;
}
- List urlList=new ArrayList<URL>();
+ List urlList = new ArrayList<URL>();
File[] fileList = jarPathFile.listFiles();
- for(int i =0;i<fileList.length;i++){
+ for (int i = 0; i < fileList.length; i++) {
File item = fileList[i];
- if(item.isDirectory()){
+ if (item.isDirectory()) {
continue;
}
try {
- if(item.getAbsolutePath().endsWith(".jar")) {
+ if (item.getAbsolutePath().endsWith(".jar")) {
urlList.add(item.toURI().toURL());
logger.debug("url class load add lib {}", item.getAbsolutePath());
}
} catch (MalformedURLException e) {
- logger.error("get jar list error ",e);
+ logger.error("get jar list error ", e);
}
}
URL[] urls = new URL[urlList.size()];
urlList.toArray(urls);
- URLClassLoader cl = new URLClassLoader(urls,Thread.currentThread().getContextClassLoader());
+ URLClassLoader cl = new URLClassLoader(urls, Thread.currentThread().getContextClassLoader());
Thread.currentThread().setContextClassLoader(cl);
return true;
}
diff --git a/tools/erlanalysis/src/main/java/org/apache/dubbo/erlang/analysis/parse/MethodInfo.java b/tools/erlanalysis/src/main/java/org/apache/dubbo/erlang/analysis/parse/MethodInfo.java
index 1979cc8..bb0ddc6 100644
--- a/tools/erlanalysis/src/main/java/org/apache/dubbo/erlang/analysis/parse/MethodInfo.java
+++ b/tools/erlanalysis/src/main/java/org/apache/dubbo/erlang/analysis/parse/MethodInfo.java
@@ -1,3 +1,20 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
package org.apache.dubbo.erlang.analysis.parse;
@@ -40,47 +57,48 @@
}
- public String getParameterNameString(){
- return String.join(",",parameterName);
+ public String getParameterNameString() {
+ return String.join(",", parameterName);
}
public void setParameterName(String[] parameterName) {
- for(int i=0;i<parameterName.length;i++){
+ for (int i = 0; i < parameterName.length; i++) {
parameterName[i] = parameterName[i].substring(0, 1).toUpperCase() + parameterName[i].substring(1);
}
this.parameterName = parameterName;
}
- public String getParameterTypeDef(){
+ public String getParameterTypeDef() {
ArrayList<String> retList = new ArrayList<>();
Type[] types = Type.getArgumentTypes(methodDescriptor);
- for(int i=0;i<types.length;i++){
- String def= ErlTypeTransformUtil.fullClassNameToTypeDef(types[i].getClassName());
+ for (int i = 0; i < types.length; i++) {
+ String def = ErlTypeTransformUtil.fullClassNameToTypeDef(types[i].getClassName());
retList.add(def);
}
- return String.join(",\n",retList);
+ return String.join(",\n", retList);
}
- public Map<String,String> getParameterTypeList(){
+ public Map<String, String> getParameterTypeList() {
Type[] types = Type.getArgumentTypes(methodDescriptor);
- Map<String,String> retInfo = new LinkedHashMap<>();
- for(int i=0;i<types.length;i++){
- String def=ErlTypeTransformUtil.fullClassNameToErlType(types[i].getClassName());
- retInfo.put(parameterName[i],def);
+ Map<String, String> retInfo = new LinkedHashMap<>();
+ for (int i = 0; i < types.length; i++) {
+ String def = ErlTypeTransformUtil.fullClassNameToErlType(types[i].getClassName());
+ retInfo.put(parameterName[i], def);
}
return retInfo;
}
/**
* get -spec return type
+ *
* @return
*/
- public String getReturnErlType(){
+ public String getReturnErlType() {
Type types = Type.getReturnType(methodDescriptor);
return ErlTypeTransformUtil.fullClassNameToErlType(types.getClassName());
}
- public String getResponseTypeDef(){
+ public String getResponseTypeDef() {
Type types = Type.getReturnType(methodDescriptor);
return ErlTypeTransformUtil.fullClassNameToTypeDef(types.getClassName());
}
diff --git a/tools/erlanalysis/src/main/java/org/apache/dubbo/erlang/analysis/parse/ParseJarInterfaceInfo.java b/tools/erlanalysis/src/main/java/org/apache/dubbo/erlang/analysis/parse/ParseJarInterfaceInfo.java
index 1985c67..fc23dac 100644
--- a/tools/erlanalysis/src/main/java/org/apache/dubbo/erlang/analysis/parse/ParseJarInterfaceInfo.java
+++ b/tools/erlanalysis/src/main/java/org/apache/dubbo/erlang/analysis/parse/ParseJarInterfaceInfo.java
@@ -1,3 +1,20 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
package org.apache.dubbo.erlang.analysis.parse;
import org.objectweb.asm.Type;
@@ -15,7 +32,7 @@
import java.util.jar.JarInputStream;
public class ParseJarInterfaceInfo {
- private final static Logger logger= LoggerFactory.getLogger(ParseJarInterfaceInfo.class);
+ private final static Logger logger = LoggerFactory.getLogger(ParseJarInterfaceInfo.class);
static final String CLAZZ = ".class";
@@ -31,20 +48,20 @@
}
} catch (IOException e) {
- logger.debug("parse:",e);
- }finally {
- if(jarFile!=null) {
+ logger.debug("parse:", e);
+ } finally {
+ if (jarFile != null) {
try {
jarFile.close();
} catch (IOException e) {
- logger.error("",e);
+ logger.error("", e);
}
}
- if(inputInteface!=null)
+ if (inputInteface != null)
try {
inputInteface.close();
} catch (IOException e) {
- logger.error("",e);
+ logger.error("", e);
}
}
// parseArgs(jarfile);
@@ -63,39 +80,39 @@
name = jarEntry.getName();
if (name.endsWith(CLAZZ)) {
logger.debug(name);
- if(name.indexOf("WEB-INF/classes/")>-1)
- name = name.substring(16,name.length());
- name = name.replace("/",".").substring(0,name.length()-6);
- logger.debug("get interfaceName {}",name);
- Class tmpClass = Class.forName(name,false,Thread.currentThread().getContextClassLoader());
- if(tmpClass.isInterface()){
+ if (name.indexOf("WEB-INF/classes/") > -1)
+ name = name.substring(16, name.length());
+ name = name.replace("/", ".").substring(0, name.length() - 6);
+ logger.debug("get interfaceName {}", name);
+ Class tmpClass = Class.forName(name, false, Thread.currentThread().getContextClassLoader());
+ if (tmpClass.isInterface()) {
InterfaceInfo newInterface = new InterfaceInfo();
newInterface.setInterfaceName(name);
- parseClassMethods(tmpClass,newInterface);
+ parseClassMethods(tmpClass, newInterface);
list_interfaces.add(newInterface);
}
}
jarEntry = jarFile.getNextJarEntry();
}
} catch (IOException e) {
- logger.error("",e);
- }catch (Exception e){
- logger.error("",e);
- }finally {
+ logger.error("", e);
+ } catch (Exception e) {
+ logger.error("", e);
+ } finally {
if (jarFile != null) {
try {
jarFile.close();
} catch (IOException e) {
- logger.error("",e);
+ logger.error("", e);
}
}
}
return list_interfaces;
}
- private void parseClassMethods(Class classObj,InterfaceInfo interfaceInfo){
+ private void parseClassMethods(Class classObj, InterfaceInfo interfaceInfo) {
Method[] methodsList = classObj.getDeclaredMethods();
- for(int i=0;i<methodsList.length;i++){
+ for (int i = 0; i < methodsList.length; i++) {
Method method = methodsList[i];
MethodInfo methodInfo = new MethodInfo();
methodInfo.setName(method.getName());
@@ -103,17 +120,17 @@
methodInfo.setMethodDescriptor(methodDescriptor);
int tmpIndex = methodDescriptor.indexOf(")");
- String argsDescriptor=methodDescriptor.substring(1,tmpIndex);
- String returnDescriptor=methodDescriptor.substring(tmpIndex);
+ String argsDescriptor = methodDescriptor.substring(1, tmpIndex);
+ String returnDescriptor = methodDescriptor.substring(tmpIndex);
methodInfo.setArgsType(argsDescriptor);
methodInfo.setReturnType(returnDescriptor);
methodInfo.setArgsLength(Type.getArgumentTypes(method).length);
Parameter[] parameters = method.getParameters();
- String[] paramterNames=new String[parameters.length];
- for(int index=0;index < parameters.length;index++){
- paramterNames[index]=parameters[index].getName();
+ String[] paramterNames = new String[parameters.length];
+ for (int index = 0; index < parameters.length; index++) {
+ paramterNames[index] = parameters[index].getName();
}
methodInfo.setParameterName(paramterNames);
// 通过asm获取存在为null的情况。
@@ -137,12 +154,14 @@
checkCommonType(Type.getReturnType(method));
}
}
- private void checkCommonType(Type[] types){
- for(int i=0;i<types.length;i++){
+
+ private void checkCommonType(Type[] types) {
+ for (int i = 0; i < types.length; i++) {
checkCommonType(types[i]);
}
}
- private void checkCommonType(Type type){
+
+ private void checkCommonType(Type type) {
CommonTypeInfo.add(type.getClassName());
// switch (type.getSort()){
@@ -178,19 +197,19 @@
// return methodIds;
// }
- private String formatData(List<String> list,String prefix,String suffix,boolean isJsonFormat){
+ private String formatData(List<String> list, String prefix, String suffix, boolean isJsonFormat) {
StringBuilder jsonSb = new StringBuilder(prefix);
- for(String key : list){
- if(jsonSb.length()>1)
+ for (String key : list) {
+ if (jsonSb.length() > 1)
jsonSb.append(",");
- if(isJsonFormat)
- jsonSb.append("\""+key+"\":"+",\"\"") ;
+ if (isJsonFormat)
+ jsonSb.append("\"" + key + "\":" + ",\"\"");
else
jsonSb.append(key);
}
jsonSb.append(suffix);
- if(jsonSb.length()<2)
- jsonSb.delete(0,jsonSb.length());
+ if (jsonSb.length() < 2)
+ jsonSb.delete(0, jsonSb.length());
return jsonSb.toString();
}
}
diff --git a/tools/erlanalysis/src/main/java/org/apache/dubbo/erlang/analysis/utils/ErlTypeTransformUtil.java b/tools/erlanalysis/src/main/java/org/apache/dubbo/erlang/analysis/utils/ErlTypeTransformUtil.java
index 163ee8c..c3471e7 100644
--- a/tools/erlanalysis/src/main/java/org/apache/dubbo/erlang/analysis/utils/ErlTypeTransformUtil.java
+++ b/tools/erlanalysis/src/main/java/org/apache/dubbo/erlang/analysis/utils/ErlTypeTransformUtil.java
@@ -1,63 +1,77 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
package org.apache.dubbo.erlang.analysis.utils;
import java.util.List;
import java.util.Map;
import java.util.Set;
-/**
- * Created by dlive on 23/02/2018.
- */
public class ErlTypeTransformUtil {
- public static String fullClassNameToTypeDef(String fullClassName){
- String className = fullClassName.substring(fullClassName.lastIndexOf(".")+1);
+ public static String fullClassNameToTypeDef(String fullClassName) {
+ String className = fullClassName.substring(fullClassName.lastIndexOf(".") + 1);
className = className.substring(0, 1).toLowerCase() + className.substring(1);
String fieldNames = "";
- switch (className){
+ switch (className) {
case "string":
- fieldNames="[]";
+ fieldNames = "[]";
break;
default:
- fieldNames = String.format("record_info(fields,%s)",className);
+ fieldNames = String.format("record_info(fields,%s)", className);
}
return String.format("#type_def{foreign_type = <<\"%s\">>,\n" +
" native_type = %s,\n" +
- " fieldnames = %s}",fullClassName,className,fieldNames);
+ " fieldnames = %s}", fullClassName, className, fieldNames);
}
- public static String fullClassNameToLowerShortName(String fullClassName){
- String className = fullClassName.substring(fullClassName.lastIndexOf(".")+1);
+ public static String fullClassNameToLowerShortName(String fullClassName) {
+ String className = fullClassName.substring(fullClassName.lastIndexOf(".") + 1);
className = className.substring(0, 1).toLowerCase() + className.substring(1);
return className;
}
- public static String stringFirstToLower(String str){
+ public static String stringFirstToLower(String str) {
str = str.substring(0, 1).toLowerCase() + str.substring(1);
return str;
}
- public static String fullClassNameToErlType(String fullClassName){
+ public static String fullClassNameToErlType(String fullClassName) {
try {
- String type=null;
- if(fullClassName.startsWith("java.lang")|| fullClassName.equals("int") || fullClassName.equals("double") || fullClassName.equals("float")){
- switch (fullClassName){
+ String type = null;
+ if (fullClassName.startsWith("java.lang") || fullClassName.equals("int") || fullClassName.equals("double") || fullClassName.equals("float")) {
+ switch (fullClassName) {
case "java.lang.String":
- type="list()";
+ type = "list()";
break;
case "java.lang.Integer":
- type="integer()";
+ type = "integer()";
break;
case "java.lang.Boolean":
- type="boolean()";
+ type = "boolean()";
break;
case "java.lang.Float":
- type="float()";
+ type = "float()";
break;
case "int":
- type="integer()";
+ type = "integer()";
break;
case "double":
- type="float()";
+ type = "float()";
break;
default:
return "unkonw";
@@ -67,14 +81,14 @@
}
Class<?> classInfo = Class.forName(fullClassName, false, Thread.currentThread().getContextClassLoader());
- if(classInfo.isAssignableFrom(List.class) ){
- type="[]";
- }else if(classInfo.isAssignableFrom(Map.class) ){
- type="Map";
- }else if(classInfo.isAssignableFrom(Set.class) ){
- type="Set";
- }else{
- type = "#"+fullClassNameToLowerShortName(fullClassName)+"{}";
+ if (classInfo.isAssignableFrom(List.class)) {
+ type = "[]";
+ } else if (classInfo.isAssignableFrom(Map.class)) {
+ type = "Map";
+ } else if (classInfo.isAssignableFrom(Set.class)) {
+ type = "Set";
+ } else {
+ type = "#" + fullClassNameToLowerShortName(fullClassName) + "{}";
}
return type;
} catch (ClassNotFoundException e) {
diff --git a/tools/erlanalysis/src/main/java/org/apache/dubbo/erlang/analysis/utils/MavenJarUtil.java b/tools/erlanalysis/src/main/java/org/apache/dubbo/erlang/analysis/utils/MavenJarUtil.java
index 1269955..fe6e26f 100644
--- a/tools/erlanalysis/src/main/java/org/apache/dubbo/erlang/analysis/utils/MavenJarUtil.java
+++ b/tools/erlanalysis/src/main/java/org/apache/dubbo/erlang/analysis/utils/MavenJarUtil.java
@@ -1,5 +1,21 @@
-package org.apache.dubbo.erlang.analysis.utils;
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.dubbo.erlang.analysis.utils;
import org.apache.maven.shared.invoker.*;
import org.slf4j.Logger;
@@ -10,9 +26,6 @@
import java.io.IOException;
import java.util.Collections;
-/**
- * Created by dlive on 16/5/31.
- */
public class MavenJarUtil {
private String groupid;
private String artifactId;
@@ -21,7 +34,7 @@
private String rootDir;
private static Logger log = LoggerFactory.getLogger(MavenJarUtil.class);
- public MavenJarUtil(String groupid, String artifactId, String version){
+ public MavenJarUtil(String groupid, String artifactId, String version) {
this.groupid = groupid;
this.artifactId = artifactId;
this.version = version;
@@ -29,38 +42,38 @@
}
- public boolean copyDependence(){
- String mvn_home = System.getenv("MAVEN_HOME");
- this.rootDir = genProjectDir(System.getProperty("project_save_dir",System.getProperty("user.dir")+File.separator+"mavenDown"));
- if(rootDir==null){
+ public boolean copyDependence() {
+ String mvn_home = System.getenv("MAVEN_HOME");
+ this.rootDir = genProjectDir(System.getProperty("project_save_dir", System.getProperty("user.dir") + File.separator + "mavenDown"));
+ if (rootDir == null) {
return false;
}
- log.info("down load lib jar dir:"+rootDir);
- String pomPathJar = genPomFile(this.rootDir,"jar");
+ log.info("down load lib jar dir:" + rootDir);
+ String pomPathJar = genPomFile(this.rootDir, "jar");
InvocationRequest request = new DefaultInvocationRequest();
- request.setPomFile( new File( pomPathJar ) );
- request.setGoals( Collections.singletonList( "compile" ) );
+ request.setPomFile(new File(pomPathJar));
+ request.setGoals(Collections.singletonList("compile"));
Invoker invoker = new DefaultInvoker();
try {
- if(mvn_home!=null){
- log.info("use MAVEN_HOME:"+mvn_home);
+ if (mvn_home != null) {
+ log.info("use MAVEN_HOME:" + mvn_home);
invoker.setMavenHome(new File(mvn_home));
}
invoker.setWorkingDirectory(new File(rootDir));
- InvocationResult result = invoker.execute( request );
- if(result.getExitCode()!=0){
- String pomPathWar = genPomFile(this.rootDir,"war");
+ InvocationResult result = invoker.execute(request);
+ if (result.getExitCode() != 0) {
+ String pomPathWar = genPomFile(this.rootDir, "war");
InvocationRequest requestWar = new DefaultInvocationRequest();
requestWar.setPomFile(new File(pomPathWar));
requestWar.setGoals(Collections.singletonList("compile"));
invoker.setWorkingDirectory(new File(rootDir));
- InvocationResult resultWar = invoker.execute( requestWar );
- if(resultWar.getExitCode()!=0){
- log.error("mvn run result exception:"+resultWar.getExecutionException());
+ InvocationResult resultWar = invoker.execute(requestWar);
+ if (resultWar.getExitCode() != 0) {
+ log.error("mvn run result exception:" + resultWar.getExecutionException());
return false;
}
}
@@ -71,7 +84,7 @@
return true;
}
- private String genPomFile(String rootDir,String pomDependenType ){
+ private String genPomFile(String rootDir, String pomDependenType) {
String pomContent = String.format("<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n" +
" xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd\">\n" +
@@ -92,7 +105,7 @@
" <groupId>log4j</groupId>\n" +
" <artifactId>log4j</artifactId>\n" +
" </exclusion>\n" +
- " </exclusions>"+
+ " </exclusions>" +
"\t </dependency>\n" +
" </dependencies>\n" +
" <build>\n" +
@@ -113,23 +126,23 @@
" <excludeScope>provided</excludeScope>\n" +
" </configuration> -->\n" +
" </execution>\n" +
- " </executions>"+
+ " </executions>" +
" <configuration>\n" +
"\t\t\t\t\t <outputDirectory>${basedir}/lib</outputDirectory>\n" +
"\t\t\t\t\t <excludeScope>provided</excludeScope>\n" +
" <excludeArtifactIds>commons-logging</excludeArtifactIds>\n" +
- " </configuration>"+
+ " </configuration>" +
" </plugin>\n" +
" </plugins>\n" +
" </build>\n" +
- "</project>\n",groupid,artifactId,version,pomDependenType);
+ "</project>\n", groupid, artifactId, version, pomDependenType);
//logback-core,logback-classic,
- String pompath = rootDir+File.separator+"pom.xml";
- log.info("will create pom file:"+pompath);
+ String pompath = rootDir + File.separator + "pom.xml";
+ log.info("will create pom file:" + pompath);
File pomfile = new File(pompath);
try {
//pomfile.createNewFile();
- FileOutputStream out=new FileOutputStream(pomfile);
+ FileOutputStream out = new FileOutputStream(pomfile);
out.write(pomContent.getBytes());
out.close();
} catch (IOException e) {
@@ -139,18 +152,18 @@
return pompath;
}
- private String genProjectDir(String savedir){
+ private String genProjectDir(String savedir) {
String tmpSavePath;
- if(savedir.endsWith(File.separator)){
- tmpSavePath=String.format("%s%s%s%s",savedir,this.artifactId,File.separator,this.version);
- }else{
- tmpSavePath=String.format("%s%s%s%s%s",savedir,File.separator,this.artifactId,File.separator,this.version);
+ if (savedir.endsWith(File.separator)) {
+ tmpSavePath = String.format("%s%s%s%s", savedir, this.artifactId, File.separator, this.version);
+ } else {
+ tmpSavePath = String.format("%s%s%s%s%s", savedir, File.separator, this.artifactId, File.separator, this.version);
}
File rootDir = new File(tmpSavePath);
- if(!rootDir.exists()){
- if(!rootDir.mkdirs()){
+ if (!rootDir.exists()) {
+ if (!rootDir.mkdirs()) {
return null;
}
}
@@ -158,8 +171,8 @@
}
public String getMainJarPath() {
- if(mainJarPath==null){
- mainJarPath=String.format("%s%slib%s%s-%s.jar",rootDir,File.separator,File.separator,artifactId,version);
+ if (mainJarPath == null) {
+ mainJarPath = String.format("%s%slib%s%s-%s.jar", rootDir, File.separator, File.separator, artifactId, version);
}
return mainJarPath;
}
@@ -168,7 +181,7 @@
return rootDir;
}
- public String getArtifactId(){
+ public String getArtifactId() {
return artifactId;
}
diff --git a/tools/erlanalysis/src/main/java/org/apache/dubbo/erlang/analysis/utils/MethodParseUtil.java b/tools/erlanalysis/src/main/java/org/apache/dubbo/erlang/analysis/utils/MethodParseUtil.java
index 04b3b25..f14a870 100644
--- a/tools/erlanalysis/src/main/java/org/apache/dubbo/erlang/analysis/utils/MethodParseUtil.java
+++ b/tools/erlanalysis/src/main/java/org/apache/dubbo/erlang/analysis/utils/MethodParseUtil.java
@@ -1,3 +1,20 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
package org.apache.dubbo.erlang.analysis.utils;
import org.objectweb.asm.*;
@@ -7,9 +24,6 @@
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
-/**
- * Created by dlive on 23/02/2018.
- */
public class MethodParseUtil {
public static String[] getMethodParamNames(final Method method) throws IOException {
@@ -22,7 +36,7 @@
ClassReader cr = new ClassReader(Thread.currentThread().getContextClassLoader().getResourceAsStream(className.replace('.', '/') + ".class"));
ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS);
- cr.accept(new ClassVisitor(Opcodes.ASM5,cw) {
+ cr.accept(new ClassVisitor(Opcodes.ASM5, cw) {
public MethodVisitor visitMethod(int access, String name, String desc, String signature, String[] exceptions) {
MethodVisitor mv = super.visitMethod(access, name, desc, signature, exceptions);
@@ -34,7 +48,7 @@
return mv;
}
- return new MethodVisitor(Opcodes.ASM5,mv) {
+ return new MethodVisitor(Opcodes.ASM5, mv) {
public void visitLocalVariable(String name, String desc, String signature, Label start, Label end, int index) {
//如果是静态方法,第一个参数就是方法参数,非静态方法,则第一个参数是 this ,然后才是方法的参数
int methodParameterIndex = isStatic ? index : index - 1;
diff --git a/tools/erlanalysis/src/main/resources/log4j.properties b/tools/erlanalysis/src/main/resources/log4j.properties
index d6e4cfe..6b34c8a 100644
--- a/tools/erlanalysis/src/main/resources/log4j.properties
+++ b/tools/erlanalysis/src/main/resources/log4j.properties
@@ -1,5 +1,4 @@
log4j.rootLogger=DEBUG,console
-
log4j.appender.console=org.apache.log4j.ConsoleAppender
log4j.appender.console.Threshold=DEBUG
#log4j.appender.console.ImmediateFlush=true
diff --git a/tools/erlanalysis/src/test/java/org/apache/dubbo/erlang/analysis/parse/InterfaceParseTest.java b/tools/erlanalysis/src/test/java/org/apache/dubbo/erlang/analysis/parse/InterfaceParseTest.java
index 4b57303..8f1b4b5 100644
--- a/tools/erlanalysis/src/test/java/org/apache/dubbo/erlang/analysis/parse/InterfaceParseTest.java
+++ b/tools/erlanalysis/src/test/java/org/apache/dubbo/erlang/analysis/parse/InterfaceParseTest.java
@@ -1,3 +1,20 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
package org.apache.dubbo.erlang.analysis.parse;
import junit.framework.TestCase;
@@ -5,6 +22,6 @@
public class InterfaceParseTest extends TestCase {
public void testParse() throws Exception {
InterfaceParse parser = new InterfaceParse();
- parser.parse("org.apache.dubbo.erlang","dubbo-sample-service","1.3");
+ parser.parse("org.apache.dubbo.erlang", "dubbo-sample-service", "1.3");
}
}
\ No newline at end of file