Веб сервис из Java в C#
17.09.2013, 19:40. Показов 1061. Ответов 0
Есть веб сервис на Java нужно перевести в веб сервис на C#
Передача синхронных сообщений при помощи протокола JSON-RPS
Файл ISyncClient.java
Java | 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
| package com.user.Transport.Sync;
import java.lang.reflect.Type;
public interface ISyncClient {
Object invokeAndReadResponse(String methodName, Object[] arguments, Type returnType,
String serverAddress, int serverPort) throws Throwable;
@SuppressWarnings("unchecked")
<T> T invokeAndReadResponse(String methodName, Object[] arguments, Class<T> clazz,
String serverAddress, int serverPort) throws Throwable;
Object invokeAndReadResponse(String methodName, Object[] arguments, Type returnType,
String serverAddress, int serverPort, String id) throws Throwable;
@SuppressWarnings("unchecked")
<T> T invokeAndReadResponse(String methodName, Object[] arguments, Class<T> clazz,
String serverAddress, int serverPort, String id) throws Throwable;
} |
|
файл ISyncServer.java
Java | 1
2
3
4
5
6
7
8
| package com.user.Transport.Sync;
import java.io.IOException;
public interface ISyncServer {
void start(Object handler, Class<?> remoteInterface) throws IOException;
void stop() throws InterruptedException;
} |
|
файл JsomRpsClient.java
Java | 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
| package com.user.Transport.Sync;
import com.fasterxml.jackson.databind.node.ObjectNode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Type;
import java.net.InetAddress;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
public class JsonRpcClient implements ISyncClient {
private static Logger logger = LoggerFactory.getLogger(JsonRpcClient.class);
private com.googlecode.jsonrpc4j.JsonRpcClient client;
public com.googlecode.jsonrpc4j.JsonRpcClient getClient() {
return client;
}
private List<Socket> sockets;
public JsonRpcClient() {
client = new com.googlecode.jsonrpc4j.JsonRpcClient();
client.setRequestListener(new com.googlecode.jsonrpc4j.JsonRpcClient.RequestListener() {
public void onBeforeRequestSent(com.googlecode.jsonrpc4j.JsonRpcClient client, ObjectNode request) {
logger.info("Request: {}", request.toString());
}
public void onBeforeResponseProcessed(com.googlecode.jsonrpc4j.JsonRpcClient client, ObjectNode response) {
logger.info("Response: {}", response.toString());
}
});
sockets = new ArrayList<>();
}
private Socket FindSocket(String serverAddress, int serverPort) throws IOException {
boolean contains = false;
Socket result = null;
InetAddress address = InetAddress.getByName(serverAddress);
for (Socket s : sockets) {
if (s.getInetAddress().equals(address) && s.getPort() == serverPort) {
result = s;
contains = true;
break;
}
}
if (!contains) {
result = new Socket(address, serverPort);
sockets.add(result);
}
return result;
}
private Object invokeAndReadResponse(String methodName, Object[] arguments, Type returnType,
OutputStream ops, InputStream ips) throws Throwable {
return client.invokeAndReadResponse(methodName, arguments, returnType, ops, ips);
}
public Object invokeAndReadResponse(String methodName, Object[] arguments, Type returnType,
String serverAddress, int serverPort) throws Throwable {
Socket socket = FindSocket(serverAddress, serverPort);
return invokeAndReadResponse(methodName, arguments, returnType,
socket.getOutputStream(), socket.getInputStream());
}
@SuppressWarnings("unchecked")
public <T> T invokeAndReadResponse(String methodName, Object[] arguments, Class<T> clazz,
String serverAddress, int serverPort) throws Throwable {
return (T)invokeAndReadResponse(methodName, arguments, Type.class.cast(clazz), serverAddress, serverPort);
}
@SuppressWarnings("unchecked")
public <T> T invokeAndReadResponse(String methodName, Object[] arguments, Class<T> clazz,
String serverAddress, int serverPort, String id) throws Throwable {
return (T)invokeAndReadResponse(methodName, arguments, Type.class.cast(clazz), serverAddress, serverPort, id);
}
public Object invokeAndReadResponse(String methodName, Object[] arguments, Type returnType,
String serverAddress, int serverPort, String id) throws Throwable {
Socket socket = FindSocket(serverAddress, serverPort);
// invoke it
client.invoke(methodName, arguments, socket.getOutputStream(), id);
// read it
return client.readResponse(returnType, socket.getInputStream());
}
} |
|
файл JsonRpsServer.java
Java | 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
| ackage com.user.Transport.Sync;
import com.googlecode.jsonrpc4j.StreamServer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.net.InetAddress;
import java.net.ServerSocket;
public class JsonRpcServer implements ISyncServer {
private static Logger logger = LoggerFactory.getLogger(JsonRpcServer.class);
private String address;
private int port;
private int maxThreads;
public String getAddress() {
return address;
}
public int getPort() {
return port;
}
public int getMaxThreads() {
return maxThreads;
}
public JsonRpcServer(String address, int port) {
this(address, port, 50);
}
public JsonRpcServer(String address, int port, int maxThreads) {
this.address = address;
this.port = port;
this.maxThreads = maxThreads;
}
private StreamServer streamServer;
public void start(Object handler, Class<?> remoteInterface) throws IOException {
logger.info("JsonRpc server started on {}:{}, threads: {}",
new Object[] {address, port, maxThreads});
com.googlecode.jsonrpc4j.JsonRpcServer server = new com.googlecode.jsonrpc4j.JsonRpcServer(handler, remoteInterface);
InetAddress bindAddress = InetAddress.getByName(address);
ServerSocket serverSocket = new ServerSocket(port, port, bindAddress);
streamServer = new StreamServer(server, maxThreads, serverSocket);
// start server
streamServer.start();
}
public void stop() throws InterruptedException {
if (streamServer.isStarted()) {
streamServer.stop();
logger.info("JsonRpc server stopped on {}:{}", address, port);
}
}
} |
|
Передача асинхронных сообщений при помощи протокола SMTP
файл IAsyncTransport.java
Java | 1
2
3
4
5
6
7
8
9
10
11
12
13
| package com.user.Transport.Async;
public interface IAsyncTransport {
void start();
void stop();
int sendAsyncMessage(String methodName, Object param, String recipientAddress);
int receiveAsyncMessage();
void setMessageHandler(IMessageHandler messageHandler);
} |
|
файл ImessageHandler.java
Java | 1
2
3
4
5
| package com.user.Transport.Async;
public interface IMessageHandler {
void handler(String methodName, Object param);
} |
|
файл ListenTask.java
Java | 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
| package com.user.Transport.Async;
import java.util.TimerTask;
public class ListenTask extends TimerTask {
private IAsyncTransport asyncTransport;
public ListenTask(IAsyncTransport asyncTransport) {
this.asyncTransport = asyncTransport;
}
@Override
public void run() {
asyncTransport.receiveAsyncMessage();
}
} |
|
файл SmtpTransport.java
Java | 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
| ackage com.user.Transport.Async;
import net.minidev.json.JSONObject;
import net.minidev.json.JSONValue;
import net.minidev.json.parser.ParseException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.search.FlagTerm;
import java.util.Date;
import java.util.Properties;
import java.util.Timer;
import java.util.TimerTask;
public class SmtpTransport implements IAsyncTransport {
private static Logger logger = LoggerFactory.getLogger(SmtpTransport.class);
private Timer timer;
private String server;
private String login;
private String password;
private String address;
private int smtpPort;
private int pop3Port;
private IMessageHandler messageHandler;
public String getServer() {
return server;
}
public String getLogin() {
return login;
}
public String getPassword() {
return password;
}
public String getAddress() {
return address;
}
public int getSmtpPort() {
return smtpPort;
}
public int getPop3Port() {
return pop3Port;
}
public SmtpTransport() {
this("", "", "", 1, 1);
}
public SmtpTransport(String server, String login, String password, int smtpPort, int pop3Port) {
this.server = server;
this.login = login;
this.password = password;
this.address = login + '@' + server;
this.smtpPort = smtpPort;
this.pop3Port = pop3Port;
}
public void setMessageHandler(IMessageHandler messageHandler) {
this.messageHandler = messageHandler;
}
public int sendAsyncMessage(String methodName, Object param, String recipientAddress) {
int error = 1;
JSONObject obj = new JSONObject();
obj.put("methodName", methodName);
obj.put("param", param);
String text = obj.toJSONString();
Properties properties = new Properties();
properties.put("mail.smtp.auth", "true");
properties.put("mail.smtp.host", server);
properties.put("mail.smtp.port", smtpPort);
Session session = Session.getInstance(properties, new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(address, password);
}
});
try {
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(address));
message.setRecipients(Message.RecipientType.TO, recipientAddress);
message.setSentDate(new Date());
message.setText(text, "UTF-8");
Transport.send(message);
error = 0;
logger.info("{} > message '{}' was sent to {}", new Object[] {address, text, recipientAddress});
} catch (MessagingException ex) {
logger.error("{} > sent failed to {}, exception: {}",
new Object[] {address, recipientAddress, ex.getMessage()});
}
return error;
}
public int receiveAsyncMessage() {
int error = 1;
Properties properties = new Properties();
properties.put("mail.pop3.host", server);
properties.put("mail.pop3.port", pop3Port);
Store store = null;
Folder folder = null;
try {
Session session = Session.getDefaultInstance(properties, null);
store = session.getStore("pop3");
store.connect(address, password);
folder = store.getFolder("INBOX");
folder.open(Folder.READ_WRITE);
if (folder.getUnreadMessageCount() != 0) {
Message[] messages = folder.search(new FlagTerm(new Flags(Flags.Flag.SEEN), false));
for (Message m : messages) {
try {
Address[] from = m.getFrom();
String senderAddress = (from != null && from.length > 0) ?
from[0].toString() : "unknown";
m.setFlag(Flags.Flag.DELETED, true);
Object text = m.getContent();
logger.info("{} > message '{}' was receive from {}",
new Object[] {address, text, senderAddress});
try {
JSONObject obj = (JSONObject)JSONValue.parseWithException(text.toString());
String methodName = null;
if (obj.containsKey("methodName")) {
methodName = (String) obj.get("methodName");
}
Object param = null;
if (obj.containsKey("param")) {
param = obj.get("param");
}
if (methodName != null && param != null) {
messageHandler.handler(methodName, param);
}
} catch (ParseException e) {
logger.error("Parse exception: {}", e.getMessage());
}
} catch (MessagingException ex) {
logger.error("{} > message wasn't receive, exception: {}", address, ex.getMessage());
}
}
}
error = 0;
} catch (Exception ex) {
logger.error("{} > receive failed, exception: {}", address, ex.getMessage());
} finally {
try {
if (folder != null) {
folder.close(true);
}
if (store != null) {
store.close();
}
} catch (MessagingException ex) {
ex.printStackTrace();
}
}
return error;
}
public void start() {
timer = new Timer();
TimerTask timerTask = new ListenTask(this);
timer.schedule(timerTask, 0, 1000);
logger.info("Asynchronous transport is started on address {}", address);
}
public void stop() {
if (timer != null) {
timer.cancel();
timer.purge();
}
logger.info("Asynchronous transport is stoped on address {}", address);
}
} |
|
Заранее спасибо за оказанную помощь и ответы
|