├── README.md
├── .gitignore
├── src
├── main
│ └── java
│ │ └── com
│ │ └── weibo
│ │ └── yar
│ │ ├── packager
│ │ ├── Packager.java
│ │ ├── JsonPackager.java
│ │ ├── PackagerFactory.java
│ │ ├── PherializePackager.java
│ │ └── MsgpackPackager.java
│ │ ├── yarclient
│ │ ├── YarClient.java
│ │ ├── HttpYarClient.java
│ │ └── AbstractYarClient.java
│ │ ├── YarException.java
│ │ ├── yarserver
│ │ ├── HttpServerHandler.java
│ │ └── NettyYarServer.java
│ │ ├── YarRequest.java
│ │ ├── YarHeader.java
│ │ ├── YarResponse.java
│ │ ├── YarProtocol.java
│ │ └── codec
│ │ └── PHPUnserializer.java
└── test
│ └── java
│ └── com
│ └── weibo
│ └── yar
│ ├── packager
│ ├── MsgpackPackagerTest.java
│ ├── PherializePackagerTest.java
│ └── BasePackagerTest.java
│ └── YarProtocolTest.java
├── pom.xml
└── LICENSE
/README.md:
--------------------------------------------------------------------------------
1 | # yar-java
2 | Java implementation of Yar protocol
3 |
4 | ## Usage
5 |
6 | ### maven
7 |
8 | ```xml
9 | ...
10 |
11 |
12 | com.weibo
13 | yar-java
14 | 0.0.3
15 |
16 |
17 | ...
18 | ```
19 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | .target/
2 | .logs/
3 | */logs/
4 | */*/logs/
5 | */target/
6 |
7 | # maven ignore
8 | target/
9 | *.war
10 | *.zip
11 | *.tar
12 | *.tar.gz
13 |
14 | # eclipse ignore
15 | .settings/
16 | .project
17 | .classpath
18 |
19 | # idea ignore
20 | .idea/
21 | *.ipr
22 | *.iml
23 | *.iws
24 |
25 | # temp ignore
26 | *.log
27 | *.cache
28 | *.diff
29 | *.patch
30 | *.tmp
31 |
32 | # system ignore
33 | .DS_Store
34 | Thumbs.db
35 | logs/
36 | bin/
37 |
--------------------------------------------------------------------------------
/src/main/java/com/weibo/yar/packager/Packager.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2009-2016 Weibo, Inc.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
5 | * in compliance with the License. You may obtain a copy of the License at
6 | *
7 | * http://www.apache.org/licenses/LICENSE-2.0
8 | *
9 | * Unless required by applicable law or agreed to in writing, software distributed under the License
10 | * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
11 | * or implied. See the License for the specific language governing permissions and limitations under
12 | * the License.
13 | */
14 | package com.weibo.yar.packager;
15 |
16 | import java.io.IOException;
17 |
18 |
19 | public interface Packager {
20 |
21 | byte[] encode(E value) throws IOException;
22 |
23 | E decode(byte[] data, Class messageType) throws IOException;
24 |
25 | }
26 |
--------------------------------------------------------------------------------
/src/test/java/com/weibo/yar/packager/MsgpackPackagerTest.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2009-2016 Weibo, Inc.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.weibo.yar.packager;
17 |
18 |
19 | public class MsgpackPackagerTest extends BasePackagerTest {
20 |
21 | protected void setUp() throws Exception {
22 | packager = new MsgpackPackager();
23 | }
24 |
25 | protected void tearDown() throws Exception {
26 | super.tearDown();
27 | }
28 |
29 | }
30 |
--------------------------------------------------------------------------------
/src/test/java/com/weibo/yar/packager/PherializePackagerTest.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2009-2016 Weibo, Inc.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.weibo.yar.packager;
17 |
18 |
19 | public class PherializePackagerTest extends BasePackagerTest {
20 |
21 | protected void setUp() throws Exception {
22 | packager = new PherializePackager();
23 | }
24 |
25 | protected void tearDown() throws Exception {
26 | super.tearDown();
27 | }
28 |
29 | }
30 |
--------------------------------------------------------------------------------
/src/main/java/com/weibo/yar/yarclient/YarClient.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2009-2016 Weibo, Inc.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
5 | * in compliance with the License. You may obtain a copy of the License at
6 | *
7 | * http://www.apache.org/licenses/LICENSE-2.0
8 | *
9 | * Unless required by applicable law or agreed to in writing, software distributed under the License
10 | * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
11 | * or implied. See the License for the specific language governing permissions and limitations under
12 | * the License.
13 | */
14 | package com.weibo.yar.yarclient;
15 |
16 | import java.io.IOException;
17 |
18 | public interface YarClient {
19 | public E call(String path, String method, Class responseClass, Object... parameterObject) throws IOException;
20 |
21 | public E call(String path, String method, String packageName, Class responseClass, Object... parameterObject) throws IOException;
22 |
23 | }
24 |
--------------------------------------------------------------------------------
/src/main/java/com/weibo/yar/YarException.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2009-2016 Weibo, Inc.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
5 | * in compliance with the License. You may obtain a copy of the License at
6 | *
7 | * http://www.apache.org/licenses/LICENSE-2.0
8 | *
9 | * Unless required by applicable law or agreed to in writing, software distributed under the License
10 | * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
11 | * or implied. See the License for the specific language governing permissions and limitations under
12 | * the License.
13 | */
14 | package com.weibo.yar;
15 |
16 | import java.io.Serializable;
17 |
18 | public class YarException extends RuntimeException implements Serializable {
19 |
20 | private static final long serialVersionUID = -8940458039636061045L;
21 |
22 | public YarException(String message) {
23 | super(message);
24 | }
25 | public YarException(String message, Throwable cause) {
26 | super(message, cause);
27 | }
28 |
29 | }
30 |
--------------------------------------------------------------------------------
/src/main/java/com/weibo/yar/packager/JsonPackager.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2009-2016 Weibo, Inc.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
5 | * in compliance with the License. You may obtain a copy of the License at
6 | *
7 | * http://www.apache.org/licenses/LICENSE-2.0
8 | *
9 | * Unless required by applicable law or agreed to in writing, software distributed under the License
10 | * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
11 | * or implied. See the License for the specific language governing permissions and limitations under
12 | * the License.
13 | */
14 | package com.weibo.yar.packager;
15 |
16 | import com.fasterxml.jackson.databind.ObjectMapper;
17 |
18 | import java.io.IOException;
19 |
20 | public class JsonPackager implements Packager {
21 |
22 | private ObjectMapper objectMapper = new ObjectMapper();
23 |
24 |
25 | public JsonPackager() {
26 | objectMapper = new ObjectMapper();
27 | }
28 |
29 | public byte[] encode(E value) throws IOException {
30 | return objectMapper.writeValueAsBytes(value);
31 | }
32 |
33 | public E decode(byte[] data, Class messageType) throws IOException {
34 | return objectMapper.readValue(data, messageType);
35 | }
36 |
37 | public ObjectMapper getObjectMapper() {
38 | return objectMapper;
39 | }
40 | }
41 |
--------------------------------------------------------------------------------
/src/main/java/com/weibo/yar/packager/PackagerFactory.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2009-2016 Weibo, Inc.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
5 | * in compliance with the License. You may obtain a copy of the License at
6 | *
7 | * http://www.apache.org/licenses/LICENSE-2.0
8 | *
9 | * Unless required by applicable law or agreed to in writing, software distributed under the License
10 | * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
11 | * or implied. See the License for the specific language governing permissions and limitations under
12 | * the License.
13 | */
14 | package com.weibo.yar.packager;
15 |
16 | public class PackagerFactory {
17 |
18 | /**
19 | * Create a new packager by name
20 | *
21 | * @param packagerName
22 | * @return
23 | */
24 | public static Packager createPackager(String packagerName) {
25 | if (packagerName == null) {
26 | throw new IllegalArgumentException("Packager name should not be null.");
27 | }
28 | if (packagerName.equalsIgnoreCase("PHP")) {
29 | return new PherializePackager();
30 | } else if (packagerName.equalsIgnoreCase("JSON")) {
31 | return new JsonPackager();
32 | } else if (packagerName.equalsIgnoreCase("MSGPACK")) {
33 | return new MsgpackPackager();
34 | } else {
35 | throw new IllegalArgumentException("Unknown packager type " + packagerName + ".");
36 | }
37 | }
38 | }
39 |
--------------------------------------------------------------------------------
/src/test/java/com/weibo/yar/YarProtocolTest.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2009-2016 Weibo, Inc.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.weibo.yar;
17 |
18 | import java.io.IOException;
19 |
20 | import org.json.simple.JSONObject;
21 |
22 | import junit.framework.TestCase;
23 |
24 | public class YarProtocolTest extends TestCase {
25 |
26 | String methodName = "testMethod";
27 | Object[] params = new Object[]{"123", 456, 789};
28 | String packagerName = "JSON";
29 |
30 | public void testProtocolYarRequest() throws IOException {
31 | YarRequest request = new YarRequest();
32 | request.setId(45454516);
33 | request.setMethodName(methodName);
34 | request.setPackagerName(packagerName);
35 | request.setParameters(params);
36 | byte[] requestBytes = YarProtocol.toProtocolBytes(request);
37 |
38 | YarRequest newRequest = YarProtocol.buildRequest(requestBytes);
39 | assertNotNull(newRequest);
40 | assertEquals(request, newRequest);
41 | }
42 |
43 | @SuppressWarnings("unchecked")
44 | public void testProtocolYarResponse() throws IOException {
45 | YarResponse response = new YarResponse();
46 | response.setError("eee");
47 | response.setId(623746);
48 | response.setOutput("tt");
49 | response.setPackagerName(packagerName);
50 | JSONObject jo = new JSONObject();
51 | jo.put("k1", "v1");
52 | jo.put("k2", "v2");
53 | response.setRet(jo);
54 | response.setStatus("0");
55 |
56 | byte[] responseBytes = YarProtocol.toProtocolBytes(response);
57 |
58 | YarResponse newResponse = YarProtocol.buildResponse(responseBytes);
59 | assertNotNull(newResponse);
60 | assertEquals(response, newResponse);
61 | }
62 |
63 | }
64 |
--------------------------------------------------------------------------------
/src/main/java/com/weibo/yar/yarserver/HttpServerHandler.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2009-2016 Weibo, Inc.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
5 | * in compliance with the License. You may obtain a copy of the License at
6 | *
7 | * http://www.apache.org/licenses/LICENSE-2.0
8 | *
9 | * Unless required by applicable law or agreed to in writing, software distributed under the License
10 | * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
11 | * or implied. See the License for the specific language governing permissions and limitations under
12 | * the License.
13 | */
14 | package com.weibo.yar.yarserver;
15 |
16 | import org.json.simple.JSONObject;
17 |
18 | import io.netty.buffer.ByteBuf;
19 | import io.netty.buffer.Unpooled;
20 | import io.netty.channel.ChannelHandlerContext;
21 | import io.netty.channel.SimpleChannelInboundHandler;
22 | import io.netty.handler.codec.http.DefaultFullHttpResponse;
23 | import io.netty.handler.codec.http.FullHttpRequest;
24 | import io.netty.handler.codec.http.FullHttpResponse;
25 | import io.netty.handler.codec.http.HttpHeaders;
26 | import io.netty.handler.codec.http.HttpHeaders.Values;
27 | import io.netty.handler.codec.http.HttpResponseStatus;
28 | import io.netty.handler.codec.http.HttpVersion;
29 |
30 | import com.weibo.yar.YarProtocol;
31 | import com.weibo.yar.YarRequest;
32 | import com.weibo.yar.YarResponse;
33 |
34 | public class HttpServerHandler extends SimpleChannelInboundHandler {
35 |
36 | @Override
37 | protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest msg) throws Exception {
38 |
39 | ByteBuf buf = msg.content();
40 | byte[] bytes = new byte[buf.readableBytes()];
41 | buf.getBytes(0, bytes);
42 |
43 | YarRequest yarRequest = YarProtocol.buildRequest(bytes);
44 | YarResponse yarResponse = process(yarRequest);
45 |
46 | FullHttpResponse response =
47 | new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, Unpooled.wrappedBuffer(YarProtocol
48 | .toProtocolBytes(yarResponse)));
49 | response.headers().set(HttpHeaders.Names.CONTENT_TYPE, "application/x-www-form-urlencoded");
50 | response.headers().set(HttpHeaders.Names.CONTENT_LENGTH, response.content().readableBytes());
51 | if (HttpHeaders.isKeepAlive(msg)) {
52 | response.headers().set(HttpHeaders.Names.CONNECTION, Values.KEEP_ALIVE);
53 | }
54 | ctx.write(response);
55 | ctx.flush();
56 | ctx.close();
57 | }
58 |
59 |
60 | private YarResponse process(YarRequest request) {
61 | YarResponse response = new YarResponse();
62 | response.setId(request.getId());
63 | response.setPackagerName(request.getPackagerName());
64 | JSONObject jo = new JSONObject();
65 | jo.put("key", "test");
66 | response.setRet(jo);
67 |
68 | return response;
69 |
70 | }
71 |
72 | }
73 |
--------------------------------------------------------------------------------
/src/main/java/com/weibo/yar/yarclient/HttpYarClient.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2009-2016 Weibo, Inc.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
5 | * in compliance with the License. You may obtain a copy of the License at
6 | *
7 | * http://www.apache.org/licenses/LICENSE-2.0
8 | *
9 | * Unless required by applicable law or agreed to in writing, software distributed under the License
10 | * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
11 | * or implied. See the License for the specific language governing permissions and limitations under
12 | * the License.
13 | */
14 | package com.weibo.yar.yarclient;
15 |
16 | import java.util.Map;
17 |
18 | import org.apache.commons.logging.Log;
19 | import org.apache.commons.logging.LogFactory;
20 | import org.apache.http.HttpEntity;
21 | import org.apache.http.HttpResponse;
22 | import org.apache.http.client.HttpClient;
23 | import org.apache.http.client.config.RequestConfig;
24 | import org.apache.http.client.methods.HttpPost;
25 | import org.apache.http.entity.ByteArrayEntity;
26 | import org.apache.http.entity.ContentType;
27 | import org.apache.http.impl.client.HttpClients;
28 | import org.apache.http.util.EntityUtils;
29 |
30 |
31 |
32 | public class HttpYarClient extends AbstractYarClient {
33 | private static Log log = LogFactory.getLog(HttpYarClient.class);
34 | private HttpClient httpClient = HttpClients.createDefault();
35 | private int soTimeout;
36 | private int connectTimeout;
37 |
38 | public HttpYarClient() {
39 | this(3000, 5000);
40 |
41 | }
42 |
43 | public HttpYarClient(int soTimeout, int connectTimeout) {
44 | httpClient = HttpClients.createDefault();
45 | this.soTimeout = soTimeout;
46 | this.connectTimeout = connectTimeout;
47 | }
48 |
49 |
50 | @Override
51 | protected byte[] httpPost(String url, Map headers, byte[] content) {
52 | RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(soTimeout).setSocketTimeout(soTimeout).setConnectTimeout(connectTimeout).build();
53 | HttpPost httpPost = new HttpPost(url);
54 | httpPost.setConfig(requestConfig);
55 | httpPost.setEntity(new ByteArrayEntity(content, ContentType.APPLICATION_FORM_URLENCODED));
56 | try {
57 | HttpResponse response = httpClient.execute(httpPost);
58 | int status = response.getStatusLine().getStatusCode();
59 | if (status >= 200 && status < 300) {
60 | HttpEntity entity = response.getEntity();
61 | return entity != null ? EntityUtils.toByteArray(entity) : null;
62 | } else {
63 | log.error("Unexpected response status: " + status);
64 | return null;
65 | }
66 | } catch (Exception e) {
67 | log.error("httpclient execute fail.", e);
68 | return null;
69 | } finally{
70 | httpPost.releaseConnection();
71 | }
72 | }
73 |
74 |
75 | }
76 |
--------------------------------------------------------------------------------
/src/main/java/com/weibo/yar/yarserver/NettyYarServer.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2009-2016 Weibo, Inc.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
5 | * in compliance with the License. You may obtain a copy of the License at
6 | *
7 | * http://www.apache.org/licenses/LICENSE-2.0
8 | *
9 | * Unless required by applicable law or agreed to in writing, software distributed under the License
10 | * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
11 | * or implied. See the License for the specific language governing permissions and limitations under
12 | * the License.
13 | */
14 | package com.weibo.yar.yarserver;
15 |
16 | import io.netty.bootstrap.ServerBootstrap;
17 | import io.netty.channel.ChannelFuture;
18 | import io.netty.channel.ChannelInitializer;
19 | import io.netty.channel.ChannelOption;
20 | import io.netty.channel.EventLoopGroup;
21 | import io.netty.channel.nio.NioEventLoopGroup;
22 | import io.netty.channel.socket.SocketChannel;
23 | import io.netty.channel.socket.nio.NioServerSocketChannel;
24 | import io.netty.handler.codec.http.HttpObjectAggregator;
25 | import io.netty.handler.codec.http.HttpRequestDecoder;
26 | import io.netty.handler.codec.http.HttpResponseEncoder;
27 | import io.netty.handler.stream.ChunkedWriteHandler;
28 |
29 | /**
30 | *
31 | * @Description an example for NettyYarServer
32 | * @author zhanglei
33 | * @date 2016年6月23日
34 | *
35 | */
36 | public class NettyYarServer {
37 |
38 | public static void main(String[] args) throws Exception {
39 | NettyYarServer server = new NettyYarServer();
40 | System.out.println("Http Server listening on 8844 ...");
41 | server.start(8844);
42 |
43 | }
44 |
45 | public void start(int port) throws Exception {
46 | EventLoopGroup bossGroup = new NioEventLoopGroup();
47 | EventLoopGroup workerGroup = new NioEventLoopGroup();
48 | try {
49 | ServerBootstrap b = new ServerBootstrap();
50 | b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class).childHandler(new ChannelInitializer() {
51 | @Override
52 | public void initChannel(SocketChannel ch) throws Exception {
53 | ch.pipeline().addLast("http-decoder", new HttpRequestDecoder());
54 | ch.pipeline().addLast("http-aggregator", new HttpObjectAggregator(65536));
55 | ch.pipeline().addLast("http-encoder", new HttpResponseEncoder());
56 | ch.pipeline().addLast("http-chunked", new ChunkedWriteHandler());
57 | ch.pipeline().addLast("serverHandler", new HttpServerHandler());
58 | }
59 | }).option(ChannelOption.SO_BACKLOG, 1024).childOption(ChannelOption.SO_KEEPALIVE, true);
60 |
61 | ChannelFuture f = b.bind(port).sync();
62 |
63 | f.channel().closeFuture().sync();
64 | } finally {
65 | workerGroup.shutdownGracefully();
66 | bossGroup.shutdownGracefully();
67 | }
68 | }
69 |
70 | }
71 |
--------------------------------------------------------------------------------
/src/main/java/com/weibo/yar/yarclient/AbstractYarClient.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2009-2016 Weibo, Inc.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
5 | * in compliance with the License. You may obtain a copy of the License at
6 | *
7 | * http://www.apache.org/licenses/LICENSE-2.0
8 | *
9 | * Unless required by applicable law or agreed to in writing, software distributed under the License
10 | * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
11 | * or implied. See the License for the specific language governing permissions and limitations under
12 | * the License.
13 | */
14 | package com.weibo.yar.yarclient;
15 |
16 | import java.io.IOException;
17 | import java.util.Map;
18 |
19 | import com.weibo.yar.YarException;
20 | import com.weibo.yar.YarProtocol;
21 | import com.weibo.yar.YarRequest;
22 | import com.weibo.yar.YarResponse;
23 |
24 | /**
25 | *
26 | * @Description Abstract YarClient.
27 | * @author zhanglei28
28 | * @date 2016年5月20日
29 | *
30 | */
31 | public abstract class AbstractYarClient implements YarClient {
32 |
33 | protected String packageName = "JSON";// default packageName
34 |
35 | public E call(String path, String method, Class responseClass, Object... parameterObject) throws IOException {
36 | return call(path, method, packageName, responseClass, parameterObject);
37 | }
38 |
39 | public E call(String path, String method, String packageName, Class responseClass, Object... parameterObject) throws IOException {
40 | byte[] requestBytes = buildRequestBtyes(generateId(), path, method, packageName, parameterObject);
41 | byte[] responseBytes = httpPost(path, null, requestBytes);
42 | E value = buildResponse(responseBytes, responseClass);
43 | return value;
44 | }
45 |
46 | protected byte[] buildRequestBtyes(String path, String method, String packageName, Object... parameterObject) throws IOException {
47 | return buildRequestBtyes(generateId(), path, method, packageName, parameterObject);
48 | }
49 |
50 | protected byte[] buildRequestBtyes(long id, String path, String method, String packageName, Object... parameterObject)
51 | throws IOException {
52 | YarRequest yarRequest = new YarRequest(id, packageName, method, parameterObject);
53 | return YarProtocol.toProtocolBytes(yarRequest);
54 | }
55 |
56 | protected E buildResponse(byte[] responseBytes, Class responseClass) throws IOException {
57 | YarResponse yarResponse = YarProtocol.buildResponse(responseBytes);
58 | if (yarResponse == null || yarResponse.getError() != null) {
59 | throw new YarException(yarResponse == null ? "yar response is null" : yarResponse.getError());
60 | }
61 | E value = yarResponse.getValue(responseClass);
62 | return value;
63 | }
64 |
65 | protected abstract byte[] httpPost(String url, Map headers, byte[] content);
66 |
67 | protected long generateId() {
68 | // TODO common id. can override by sub class
69 | return System.currentTimeMillis();
70 | }
71 |
72 | public String getPackageName() {
73 | return packageName;
74 | }
75 |
76 | public void setPackageName(String packageName) {
77 | this.packageName = packageName;
78 | }
79 |
80 |
81 |
82 | }
83 |
--------------------------------------------------------------------------------
/src/main/java/com/weibo/yar/packager/PherializePackager.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2009-2016 Weibo, Inc.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
5 | * in compliance with the License. You may obtain a copy of the License at
6 | *
7 | * http://www.apache.org/licenses/LICENSE-2.0
8 | *
9 | * Unless required by applicable law or agreed to in writing, software distributed under the License
10 | * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
11 | * or implied. See the License for the specific language governing permissions and limitations under
12 | * the License.
13 | */
14 | package com.weibo.yar.packager;
15 |
16 | import com.fasterxml.jackson.databind.ObjectMapper;
17 | import com.weibo.yar.codec.PHPUnserializer;
18 | import de.ailis.pherialize.Mixed;
19 | import de.ailis.pherialize.Pherialize;
20 |
21 | import java.io.IOException;
22 | import java.io.UnsupportedEncodingException;
23 | import java.util.ArrayList;
24 | import java.util.LinkedHashMap;
25 | import java.util.Map;
26 |
27 | /**
28 | *
29 | * @Description php serialize packager
30 | * @author chengya
31 | * @date 2016年6月7日
32 | *
33 | */
34 | public class PherializePackager implements Packager {
35 | public byte[] encode(E value) throws IOException {
36 | return Pherialize.serialize(value).getBytes();
37 | }
38 |
39 | public E decode(byte[] data, Class messageType) throws IOException {
40 | PHPUnserializer unserializer = new PHPUnserializer(new String(data, 0, data.length, "ISO-8859-1"));
41 | Mixed mixed = unserializer.unserializeObject();
42 | Object o = convert(mixed);
43 | return new ObjectMapper().convertValue(o, messageType);
44 | }
45 |
46 | private Object convert(Mixed mixed) throws UnsupportedEncodingException {
47 | if(mixed == null){
48 | return null;
49 | }
50 | Map map = new LinkedHashMap();
51 | if (mixed.getType() != Mixed.TYPE_ARRAY) {
52 | return convertNonArray(mixed);
53 | } else {
54 | boolean flag = true;
55 | int counter = 0;
56 | for (Map.Entry