diff --git a/.README_images/classDiagram.jpeg b/.README_images/classDiagram.jpeg deleted file mode 100644 index e24fa60..0000000 Binary files a/.README_images/classDiagram.jpeg and /dev/null differ diff --git a/.README_images/goaldiagram.png b/.README_images/goaldiagram.png deleted file mode 100644 index c583a56..0000000 Binary files a/.README_images/goaldiagram.png and /dev/null differ diff --git a/README.md b/README.md index f97871a..4665e0c 100644 --- a/README.md +++ b/README.md @@ -1,7 +1,8 @@ # JSON-RPC 2.0 Java library Project for Software Engineering at Polimi. Java library for use of JSON-RPC 2.0 communication protocol. -This module is part of a bigger project that uses this library for remote communication between clients and a server in order to request and give authorizations to specific users for specific resources. +This module is part of a bigger project that uses this library for remote communication between clients and a server in order to request and give authorizations to specific users for specific resources. +Further details can be found within the [AuthOK project documentation](https://github.com/taygumus/auth-ok). This library implements JSON-RPC 2.0 communication protocol (spec: https://www.jsonrpc.org/specification) over sockets, using ZeroMQ. diff --git a/jsonrpc/src/jsonrpc/AbstractRequest.java b/jsonrpc/src/jsonrpc/AbstractRequest.java index 12f8214..93925f7 100644 --- a/jsonrpc/src/jsonrpc/AbstractRequest.java +++ b/jsonrpc/src/jsonrpc/AbstractRequest.java @@ -2,7 +2,7 @@ import java.security.InvalidParameterException; -public abstract class AbstractRequest extends JsonRpcMessage { +public abstract class AbstractRequest extends JsonRpcMessage { enum Members { JSONRPC("jsonrpc"), METHOD("method"), ID("id"), PARAMS("params"); @@ -16,7 +16,7 @@ enum Members { boolean notify; String method; - StructuredMember params; //è un oggetto strutturato che può essere array o mappa key-value + StructuredMember params; // structured object that can be either an array or a key-value map AbstractRequest(String method, StructuredMember params, Id id) { this.notify = id == null; @@ -31,18 +31,6 @@ enum Members { this.jsonRpcString = obj.toString(); } - /*AbstractRequest(String method, StructuredMember params) throws JSONRPCException{ - this(method, params, null); - - this.notify = true; - this.id = null; - this.method = method; - this.params = params; - this.obj = toJsonObj(); - this.jsonRpcString = obj.toString(); - - //chiamare this(method, params, null) per non ripetere il codice non funzionerebbe perché il toJsonRpc leggere il parametro notify false - }*/ AbstractRequest() { super(); } @@ -50,31 +38,31 @@ enum Members { public String getMethod() { return method; } + public StructuredMember getParams() { return params; } + public boolean isNotify() { return notify; } @Override - public boolean equals(Object other){ + public boolean equals(Object other) { if (other == null) return false; if (other == this) return true; - if (!(other instanceof AbstractRequest))return false; + if (!(other instanceof AbstractRequest)) return false; AbstractRequest o = (AbstractRequest) other; - //jsonobj, jsonRpcString - if (this.id != null) { if (!this.id.equals(o.id)) {return false;} } else { if (o.id != null) {return false;} } - if (this.params==null) - return this.notify == o.notify && this.method.equals(o.method) && o.params==null; + if (this.params == null) + return this.notify == o.notify && this.method.equals(o.method) && o.params == null; else return this.notify == o.notify && this.method.equals(o.method) && this.params.equals(o.params); } -} +} \ No newline at end of file diff --git a/jsonrpc/src/jsonrpc/AbstractResponse.java b/jsonrpc/src/jsonrpc/AbstractResponse.java index faa70ad..236caa0 100644 --- a/jsonrpc/src/jsonrpc/AbstractResponse.java +++ b/jsonrpc/src/jsonrpc/AbstractResponse.java @@ -14,10 +14,10 @@ enum Members { public String toString() {return text;} } - Member result; //primitive o structure + Member result; // primitive or structured Error error; - //setup + // setup private AbstractResponse(Id id, Member result, Error error) { if (id == null) {id = new Id();} if (result != null && (error != null) || (result == null && error == null)) { @@ -33,12 +33,15 @@ private AbstractResponse(Id id, Member result, Error error) { } this.jsonRpcString = obj.toString(); } + AbstractResponse(Id id, Member result) { this(id, result, null); } + AbstractResponse(Id id, Error error) { this(id, null, error); } + AbstractResponse() { super(); } @@ -47,19 +50,21 @@ public Member getResult() { if (result == null) {throw new NullPointerException("No result");} return result; } + public Error getError() { if (error == null) {throw new NullPointerException("No error");} return error; } + public boolean hasError() { return this.result == null; } @Override - public boolean equals(Object other){ + public boolean equals(Object other) { if (other == null) return false; if (other == this) return true; - if (!(other instanceof AbstractResponse))return false; + if (!(other instanceof AbstractResponse)) return false; AbstractResponse o = (AbstractResponse) other; if (this.id != null) { @@ -74,4 +79,4 @@ public boolean equals(Object other){ return this.error.equals(o.error) && o.result == null; } } -} +} \ No newline at end of file diff --git a/jsonrpc/src/jsonrpc/Batch.java b/jsonrpc/src/jsonrpc/Batch.java index b74cefc..712c4b8 100644 --- a/jsonrpc/src/jsonrpc/Batch.java +++ b/jsonrpc/src/jsonrpc/Batch.java @@ -6,16 +6,16 @@ import java.security.InvalidParameterException; import java.util.ArrayList; -public class Batch { //public solo per test +public class Batch { // public only for test private ArrayList reqs; private ArrayList resps; private boolean onlyNotifies; - public Batch(JSONArray requestArray) { //public solo per test + public Batch(JSONArray requestArray) { // public only for test setup(requestArray); } - public Batch(ArrayList requests) { //public solo per test + public Batch(ArrayList requests) { // public only for test JSONArray array = new JSONArray(); for (Request r : requests) { array.put( r == null ? null : r.getObj() ); @@ -36,12 +36,12 @@ private void setup(JSONArray requestArray) { JSONObject o = requestArray.getJSONObject(i); stringReq = o.toString(); req = new Request(stringReq); - //resp = null; + // resp = null; if (!req.isNotify()) {onlyNotifies = false;} } catch (InvalidParameterException | JSONException e) { - Id id = stringReq != null ? Id.getIdFromRequest(stringReq) : new Id(); //tenta di recuperarne l'id, altrimenti id null + Id id = stringReq != null ? Id.getIdFromRequest(stringReq) : new Id(); // attempt to retrieve the ID; otherwise, ID is null Error err = new Error(Error.Errors.INVALID_REQUEST); - //req = null; + // req = null; resp = new Response(id, err); onlyNotifies = false; } finally { @@ -50,28 +50,29 @@ private void setup(JSONArray requestArray) { } } } + private void put(Request req, Response resp) { int i = reqs.indexOf(req); resps.set(i, resp); } - public void put(ArrayList responses) { //public solo per teset - //devono essere passate le risposte in numero esatto (pari al numero di richieste non notifiche valide) - - int c; //conta le richieste a cui non va inserita la risposta corrispondente perché non valide o notifiche + + public void put(ArrayList responses) { // public only for test + // responses must be passed in exact number (equal to the number of valid non-notification requests) + int c; // count requests where corresponding responses should not be inserted because they are either invalid or notifications int i; for (i = 0, c = 0; i < responses.size() + c; i++) { - Request req = reqs.get(i); //IndexOutOfBoundsException se le risposte sono troppe + Request req = reqs.get(i); // IndexOutOfBoundsException if there are too many responses if (req == null || req.isNotify()) { - //la risposta ad una richiesta non valida o notifica non deve esserci + // there should not be a response to an invalid request or notification c++; } else { this.put(req, responses.get(i-c)); } } for (; i < reqs.size(); i++) { - //se ci sono ancora richieste non notifiche a cui non è stata assegnata una risposta + // if there are still non-notification requests without a response assigned if (reqs.get(i)!=null && !reqs.get(i).isNotify()) {throw new IndexOutOfBoundsException("Not enough responses");} - //troppe poche risposte + // too few responses } } @@ -87,11 +88,11 @@ void put(JSONArray responses) { this.put(resps); } - public ArrayList getAllRequests() { + public ArrayList getAllRequests() { // public only for test return reqs; - } //solo per test + } - public ArrayList getValidRequests() { //public solo per test + public ArrayList getValidRequests() { // public only for test ArrayList rq = new ArrayList<>(); for (Request r : reqs) { if (r!=null) { @@ -101,11 +102,11 @@ public ArrayList getValidRequests() { //public solo per test return rq; } - public ArrayList getAllResponses() { + public ArrayList getAllResponses() { // public only for test return resps; - } //solo per test + } - public ArrayList getValidResponses() { //public solo per test + public ArrayList getValidResponses() { // public only for test ArrayList rp = new ArrayList<>(); for (Response r : resps) { if (r!=null) { @@ -115,17 +116,17 @@ public ArrayList getValidResponses() { //public solo per test return rp; } - public String getResponseJSON() { //public solo per test + public String getResponseJSON() { // public only for test JSONArray arr = new JSONArray(); for (Response r : resps) { - if (r != null) { //le risposte alle notifiche non vengono inviate + if (r != null) { // responses to notifications are not sent arr.put(r.getObj()); } } return arr.toString(); } - public String getRequestJSON() { //public solo per test + public String getRequestJSON() { // public only for test JSONArray arr = new JSONArray(); for (Request r : reqs) { arr.put(r.getObj()); @@ -136,4 +137,4 @@ public String getRequestJSON() { //public solo per test public boolean isOnlyNotifies() { return onlyNotifies; } -} +} \ No newline at end of file diff --git a/jsonrpc/src/jsonrpc/Client.java b/jsonrpc/src/jsonrpc/Client.java index 9999d96..16254ae 100644 --- a/jsonrpc/src/jsonrpc/Client.java +++ b/jsonrpc/src/jsonrpc/Client.java @@ -9,6 +9,7 @@ public class Client implements IClient { private IZmqClient zmqClient; + public Client(int port) { zmqClient = new ZmqClient(port); } @@ -31,7 +32,8 @@ public Response sendRequest(Request request) throws JSONRPCException { @Override public void sendNotify(Request notify) throws JSONRPCException { - if (!notify.isNotify()) {throw new JSONRPCException("Not a notify");} //funzionerebbe ma la specifica jsonrpc prevede che se è una richiesta deve essere restituita una risposta + // it would work, but the JSON-RPC specification requires that a response be returned if it is a request + if (!notify.isNotify()) {throw new JSONRPCException("Not a notify");} zmqClient.send(notify.getJsonString()); } @@ -50,15 +52,15 @@ public ArrayList sendBatch(ArrayList requests) { batch.put(arr); return batch.getValidResponses(); } catch (JSONException e) { - Id id = new Id(); //da un batch di richieste non è possibile recuperare UN id - //HashMap errorData = new HashMap<>(); - //errorData.put("Invalid response received", new Member(e.getMessage())); - Error err = new Error(Error.Errors.PARSE/*, new Member(new StructuredMember(errorData))*/); - Response errorResp = new Response(id, err); //la creazione è sicura non serve try catch + Id id = new Id(); // from a batch of requests, it is not possible to retrieve a single ID + // HashMap errorData = new HashMap<>(); + // errorData.put("Invalid response received", new Member(e.getMessage())); + Error err = new Error(Error.Errors.PARSE /*, new Member(new StructuredMember(errorData))*/ ); + Response errorResp = new Response(id, err); // it is safe to proceed; try-catch is unnecessary ArrayList resp = new ArrayList<>(); resp.add(errorResp); return resp; } } } -} +} \ No newline at end of file diff --git a/jsonrpc/src/jsonrpc/Error.java b/jsonrpc/src/jsonrpc/Error.java index fc1933e..df560f5 100644 --- a/jsonrpc/src/jsonrpc/Error.java +++ b/jsonrpc/src/jsonrpc/Error.java @@ -5,6 +5,10 @@ import java.security.InvalidParameterException; public class Error extends JsonRpcObj { + private String message; + private int code; // as per the specification, it must be an integer + private Member data; // primitive or structured + public enum ErrMembers { CODE("code"), MESSAGE("message"), DATA("data"); @@ -15,6 +19,7 @@ public enum ErrMembers { @Override public String toString() {return text;} } + public enum Errors { PARSE(-32700, "Parse error"), INVALID_REQUEST(-32600, "Invalid Request"), @@ -32,10 +37,7 @@ public enum Errors { public int getCode() {return code;} public String getMessage() {return message;} } - private String message; - private int code; //da specifica deve essere intero - private Member data;//primitive o structure - + public Error(String errorMessage, int errorCode, Member errorData) { if (errorMessage == null || errorMessage.isEmpty()) {throw new InvalidParameterException("Error message not defined");} this.message = errorMessage; @@ -48,9 +50,11 @@ public Error(String errorMessage, int errorCode, Member errorData) { } this.jsonRpcString = obj.toString(); } + public Error(String errorMessage, int errorCode) { this(errorMessage, errorCode, null); } + public Error(Errors error) { this.message = error.getMessage(); this.code = error.getCode(); @@ -70,20 +74,23 @@ public Error(Errors error, Member errorData) { public String getErrorMessage() { return message; } + public int getErrorCode() { return code; } + public Member getErrorData() throws NullPointerException { if (data == null) {throw new NullPointerException("No error data defined");} return data; } + public boolean hasErrorData() { return data!=null; } - JSONObject toJsonObj() throws JSONRPCException{ - //obbligatori - //if (code == null) {throw new JSONRPCException("Error code not defined");} code non è più Integer + JSONObject toJsonObj() throws JSONRPCException { + // mandatory + // if (code == null) {throw new JSONRPCException("Error code not defined");} code is no longer an Integer if (message == null) { throw new JSONRPCException("Error message not defined");} JSONObject object = new JSONObject(); @@ -94,7 +101,7 @@ JSONObject toJsonObj() throws JSONRPCException{ System.out.println(e.getMessage()); return null; } - if (data != null) { //opzionale + if (data != null) { // optional putMember(object, ErrMembers.DATA.toString(), data); } @@ -126,7 +133,7 @@ public Error(JSONObject error) { throw new InvalidParameterException(e.getMessage()); } - //verifica che non ci siano altri parametri + // check that there are no other parameters if (!checkMembersSubset(ErrMembers.values(), obj)) {throw new InvalidParameterException("Unexpected paramater");} this.jsonRpcString = obj.toString(); @@ -137,15 +144,15 @@ JSONObject getJsonObj() { } @Override - public boolean equals(Object other){ + public boolean equals(Object other) { if (other == null) return false; if (other == this) return true; - if (!(other instanceof Error))return false; + if (!(other instanceof Error)) return false; Error o = (Error) other; - if (this.data==null) - return this.code == o.code && this.message.equals(o.message) && o.data==null; + if (this.data == null) + return this.code == o.code && this.message.equals(o.message) && o.data == null; else return this.code == o.code && this.message.equals(o.message) && this.data.equals(o.data); } -} +} \ No newline at end of file diff --git a/jsonrpc/src/jsonrpc/IClient.java b/jsonrpc/src/jsonrpc/IClient.java index 2363f2b..2116203 100644 --- a/jsonrpc/src/jsonrpc/IClient.java +++ b/jsonrpc/src/jsonrpc/IClient.java @@ -3,4 +3,4 @@ public interface IClient { Response sendRequest(Request request) throws JSONRPCException; void sendNotify(Request notify) throws JSONRPCException; -} +} \ No newline at end of file diff --git a/jsonrpc/src/jsonrpc/IServer.java b/jsonrpc/src/jsonrpc/IServer.java index 84aacef..6ab2697 100644 --- a/jsonrpc/src/jsonrpc/IServer.java +++ b/jsonrpc/src/jsonrpc/IServer.java @@ -6,4 +6,4 @@ public interface IServer { ArrayList receive(); void reply(ArrayList response) throws JSONRPCException; void reply(Response response) throws JSONRPCException; -} +} \ No newline at end of file diff --git a/jsonrpc/src/jsonrpc/Id.java b/jsonrpc/src/jsonrpc/Id.java index c690d53..ef93457 100644 --- a/jsonrpc/src/jsonrpc/Id.java +++ b/jsonrpc/src/jsonrpc/Id.java @@ -5,16 +5,18 @@ import java.security.InvalidParameterException; public class Id { - //id = string o int o null - //da specifica id può essere un numero, ma non dovrebbe contenere parti decimali. per questo si usa Integer e non Number - public enum Types{NULL, STRING, INT} private Object value; private Types type; + + // ID can be a string, an integer or null + // as per the specification, the ID can be a number, but it should not contain decimal parts. This is why Integer is used instead of Number + public Id(int id) { value = id; type = Types.INT; } + public Id(String id) { if (id == null || id.isEmpty()) { value = null; @@ -25,8 +27,9 @@ public Id(String id) { type = Types.STRING; } } + public Id() { - value = null;//JSONObject.NULL; + value = null; // JSONObject.NULL; type = Types.NULL; } @@ -43,6 +46,7 @@ public String getString() { public boolean isNull() { return type==Types.NULL; } + public Types getType() { return type; } @@ -62,10 +66,10 @@ static Id toId(Object id) { } @Override - public boolean equals(Object other){ + public boolean equals(Object other) { if (other == null) return false; if (other == this) return true; - if (!(other instanceof Id))return false; + if (!(other instanceof Id)) return false; Id o = (Id) other; switch (this.type) { @@ -74,7 +78,6 @@ public boolean equals(Object other){ case INT: return o.type == Types.INT && ((Integer)getInt()).equals(o.getInt()); default: return false; } - } public static Id getIdFromRequest(String request) { @@ -82,7 +85,7 @@ public static Id getIdFromRequest(String request) { JSONObject obj = new JSONObject(request); return toId(obj.get(AbstractRequest.Members.ID.toString())); } catch (JSONException e) { - return new Id(); //se non è possibile recuperarlo della richiesta si crea un id nullo + return new Id(); // if it is not possible to retrieve the ID from the request, a null ID is created } } -} +} \ No newline at end of file diff --git a/jsonrpc/src/jsonrpc/JSONRPCException.java b/jsonrpc/src/jsonrpc/JSONRPCException.java index 8e8a600..ddcbc1f 100644 --- a/jsonrpc/src/jsonrpc/JSONRPCException.java +++ b/jsonrpc/src/jsonrpc/JSONRPCException.java @@ -4,5 +4,6 @@ public class JSONRPCException extends Exception { public JSONRPCException(String message) { super(message); } + public JSONRPCException() {super();} -} +} \ No newline at end of file diff --git a/jsonrpc/src/jsonrpc/JsonRpcMessage.java b/jsonrpc/src/jsonrpc/JsonRpcMessage.java index 21c4c1e..e4c999f 100644 --- a/jsonrpc/src/jsonrpc/JsonRpcMessage.java +++ b/jsonrpc/src/jsonrpc/JsonRpcMessage.java @@ -4,13 +4,13 @@ import org.json.JSONObject; abstract class JsonRpcMessage extends JsonRpcObj { - Id id; //può essere String o Integer (o null in alcuni casi (non notifica)) + Id id; // it can be a String or an Integer (or null in some cases (non-notification)) static final String VER = "2.0"; public Id getId() { - //id nullo è diverso da notifica + // a null ID is different from a notification if (id == null) { - throw new NullPointerException("Notify: id undefined"); //è notifica + throw new NullPointerException("Notify: id undefined"); // it is a notification } return id; } @@ -23,7 +23,7 @@ static void putId(JSONObject obj, String key, Id id) { case NULL: obj.put(key, JSONObject.NULL); break; } } catch (JSONException e) { - System.out.println(e.getMessage()); - } + System.out.println(e.getMessage()); + } } } \ No newline at end of file diff --git a/jsonrpc/src/jsonrpc/JsonRpcObj.java b/jsonrpc/src/jsonrpc/JsonRpcObj.java index 64344a8..779f511 100644 --- a/jsonrpc/src/jsonrpc/JsonRpcObj.java +++ b/jsonrpc/src/jsonrpc/JsonRpcObj.java @@ -5,23 +5,23 @@ import java.security.InvalidParameterException; import java.util.ArrayList; -public abstract class JsonRpcObj { //public per test +public abstract class JsonRpcObj { // public for test JSONObject obj; - //private boolean valid; + // private boolean valid; String jsonRpcString; - public String getJsonString() { + public String getJsonString() { // public for test return jsonRpcString; - } //public solo per tesy + } /*public boolean isValid() { return valid; }*/ - abstract JSONObject toJsonObj() throws JSONRPCException; //crea oggetto json rpc utilizzando attributi. implementata in maniera differente in richiesta, risposta e errore + abstract JSONObject toJsonObj() throws JSONRPCException; // build a JSON-RPC object using attributes; implemented differently in request, response and error static boolean checkMembersSubset(Enum members[], JSONObject obj) { - //verifica l'oggetto abbia solo i parametri contenuti nell'array dei membri + // verify that the object has only the parameters contained in the member array ArrayList memNames = new ArrayList<>(); for (Enum mem : members) { memNames.add(mem.toString()); @@ -34,7 +34,7 @@ static boolean checkMembersSubset(Enum members[], JSONObject obj) { return true; } - public static void putMember(JSONObject obj, String key, Member value) { //public per test + public static void putMember(JSONObject obj, String key, Member value) { // public for test try { switch (value.getType()) { case ARRAY: @@ -68,7 +68,7 @@ static void putStructuredMember(JSONObject obj, String key, StructuredMember mem } } - public JSONObject getObj() { + public JSONObject getObj() { // public for test return this.obj; - } //public solo per test -} + } +} \ No newline at end of file diff --git a/jsonrpc/src/jsonrpc/Member.java b/jsonrpc/src/jsonrpc/Member.java index 5c45bed..3f15f79 100644 --- a/jsonrpc/src/jsonrpc/Member.java +++ b/jsonrpc/src/jsonrpc/Member.java @@ -8,9 +8,6 @@ public class Member { public enum Types {NULL, STRING, NUMBER, BOOL, OBJ, ARRAY} - - //estendere id per avere già value, toString e to toInt, estendere o usare structured member ? - //definire interfacce private Object value; private Types type; @@ -18,31 +15,37 @@ public Member() { value = JSONObject.NULL; type = Types.NULL; } + public Member(String string) { if (string == null) {throw new NullPointerException("Member value is null");} if (string.isEmpty()) {throw new InvalidParameterException("Member value is empty");} value = string; type = Types.STRING; } + public Member(Number num) { if (num == null) {throw new NullPointerException("Member value is null");} value = num; type = Types.NUMBER; } + public Member(boolean bool) { value = bool; type = Types.BOOL; } + public Member(JSONObject obj) { if (obj == null) {throw new NullPointerException("Member value is null");} value = new StructuredMember(obj); type = Types.OBJ; } + public Member(JSONArray array) { if (array == null) {throw new NullPointerException("Member value is null");} value = new StructuredMember(array); type = Types.ARRAY; } + public Member(StructuredMember m) { if (m == null) {throw new NullPointerException("Member value is null");} value = m; @@ -52,24 +55,30 @@ public Member(StructuredMember m) { public Types getType() { return type; } + /*public boolean isStructured() { return (type == Types.OBJ || type == Types.ARRAY); }*/ + /*public boolean isNull() { return type == Types.NULL; }*/ + public boolean getBool() { if (type != Types.BOOL) {throw new ClassCastException("Not a boolean");} return (boolean)value; } + public Number getNumber() { if (type != Types.NUMBER) {throw new ClassCastException("Not a number");} return (Number)value; } + public int getInt() { if (!(value instanceof Integer)) {throw new ClassCastException("Not an integer");} return (int)value; } + public String getString() { if (type != Types.STRING) {throw new ClassCastException("Not a string");} return (String)value; @@ -79,10 +88,12 @@ public StructuredMember getStructuredMember() { if (type != Types.OBJ && type != Types.ARRAY) {throw new ClassCastException("Not a structured member");} return (StructuredMember)value; } + public ArrayList getList() { if (type != Types.ARRAY) {throw new ClassCastException("Not a json array");} return ((StructuredMember)value).getList(); } + public HashMap getMap() { if (type != Types.OBJ) {throw new ClassCastException("Not a json object");} return ((StructuredMember)value).getMap(); @@ -92,6 +103,7 @@ JSONObject getJSONObj() { if (type != Types.OBJ) {throw new ClassCastException("Not a json object");} return ((StructuredMember)value).getJSONObject(); } + JSONArray getJSONArray() { if (type != Types.ARRAY) {throw new ClassCastException("Not a json array");} return ((StructuredMember)value).getJSONArray(); @@ -120,10 +132,10 @@ public static Member toMember(Object obj) { } @Override - public boolean equals(Object other){ + public boolean equals(Object other) { if (other == null) return false; if (other == this) return true; - if (!(other instanceof Member))return false; + if (!(other instanceof Member)) return false; Member o = (Member) other; if (this.type != o.type) return false; @@ -135,4 +147,4 @@ public boolean equals(Object other){ default: return getStructuredMember().equals(o.getStructuredMember()); } } -} +} \ No newline at end of file diff --git a/jsonrpc/src/jsonrpc/Request.java b/jsonrpc/src/jsonrpc/Request.java index 32023d9..e67cbb8 100644 --- a/jsonrpc/src/jsonrpc/Request.java +++ b/jsonrpc/src/jsonrpc/Request.java @@ -4,21 +4,22 @@ import org.json.JSONObject; import java.security.InvalidParameterException; -public class Request extends AbstractRequest{ +public class Request extends AbstractRequest { public Request(String method, StructuredMember params) { super(method, params, null); } + public Request(String method, StructuredMember params, Id id) { super(method, params, id); } - public Request(String jsonRpcString) { //public solo per il test junit + public Request(String jsonRpcString) { // public only for junit test //https://stleary.github.io/JSON-java/ //https://stackoverflow.com/questions/21720759/convert-a-json-string-to-a-hashmap try { obj = new JSONObject(jsonRpcString); - /*definire eccezioni più specifiche*/ + /* define more specific exceptions */ if (!obj.has(Members.JSONRPC.toString()) || !obj.getString(Members.JSONRPC.toString()).equals(VER)) { throw new InvalidParameterException("Not jsonrpc 2.0"); } @@ -27,7 +28,7 @@ public Request(String jsonRpcString) { //public solo per il test junit } method = obj.getString(Members.METHOD.toString()); - //i parametri possono essere omessi, ma se presenti devono essere o un json array o un json object (non può essere una primitiva (es. "params" : "foo")) + // parameters can be omitted, but if present, they must be either a JSON array or a JSON object (they cannot be a primitive, e.g., "params": "foo") if (obj.has(Members.PARAMS.toString())) { params = StructuredMember.toStructuredMember(obj.get(Members.PARAMS.toString())); } else { @@ -40,7 +41,7 @@ public Request(String jsonRpcString) { //public solo per il test junit throw new InvalidParameterException(e.getMessage()); } - //verifica che non ci siano altri parametri + // verify that there are no other parameters if (!checkMembersSubset(Members.values(), obj)) {throw new InvalidParameterException("Unexpected member");} this.jsonRpcString = obj.toString(); @@ -59,10 +60,10 @@ JSONObject toJsonObj() throws JSONRPCException { } catch (JSONException e) { System.out.println(e.getMessage()); } - if (params != null) { putStructuredMember(object, Members.PARAMS.toString(), params);} //opzionale + if (params != null) { putStructuredMember(object, Members.PARAMS.toString(), params);} // optional if (!notify) { putId(object, Members.ID.toString(), id); } return object; } -} +} \ No newline at end of file diff --git a/jsonrpc/src/jsonrpc/Response.java b/jsonrpc/src/jsonrpc/Response.java index c51aa64..01049ab 100644 --- a/jsonrpc/src/jsonrpc/Response.java +++ b/jsonrpc/src/jsonrpc/Response.java @@ -13,7 +13,7 @@ public Response(Id id, Error error) { super(id, error); } - public Response(String jsonRpcString) { //public solo per test junit + public Response(String jsonRpcString) { // public only for junit test try { obj = new JSONObject(jsonRpcString); @@ -31,7 +31,7 @@ public Response(String jsonRpcString) { //public solo per test junit throw new InvalidParameterException("Method member not defined"); } - //obbligatorio nelle risposte + // mandatory in responses if (obj.has(Members.ID.toString())) { id = Id.toId(obj.get(Members.ID.toString())); } else { @@ -41,7 +41,7 @@ public Response(String jsonRpcString) { //public solo per test junit throw new InvalidParameterException(e.getMessage()); } - //verifica che non ci siano altri parametri + // check that there are no other parameters if (!checkMembersSubset(Members.values(), obj)) { throw new InvalidParameterException("Unexpected member"); } @@ -49,7 +49,6 @@ public Response(String jsonRpcString) { //public solo per test junit this.jsonRpcString = obj.toString(); } - @Override JSONObject toJsonObj() { JSONObject object = new JSONObject(); diff --git a/jsonrpc/src/jsonrpc/Server.java b/jsonrpc/src/jsonrpc/Server.java index 267b27d..d5cd68f 100644 --- a/jsonrpc/src/jsonrpc/Server.java +++ b/jsonrpc/src/jsonrpc/Server.java @@ -28,7 +28,7 @@ public ArrayList receive() { return currBatch.getValidRequests(); } else if (json instanceof JSONObject) { currBatch = null; - //una richiesta non batch: arraylist di dimensione 1 + // a non-batch request: ArrayList of size 1 Request req = new Request(receivedString); ArrayList requests = new ArrayList<>(); requests.add(req); @@ -37,15 +37,15 @@ public ArrayList receive() { throw new JSONRPCException("Invalid json received"); } } catch (JSONException | JSONRPCException e) { - //se json è invalido viene restituita in automatico un'unica risposta con errore di parsing (vedi documentazione) - //indifferentemente se era una richiesta o un array di richieste - Id id = Id.getIdFromRequest(receivedString); //se è una richiesta unica tenta di recuperarne l'id, altrimenti id null + // if the JSON is invalid, an automatic single response with parsing error is returned (see documentation) + // regardless of whether it was a single request or an array of requests + Id id = Id.getIdFromRequest(receivedString); // if it is a single request, it attempts to retrieve its ID; otherwise, the ID is null Error err = new Error(Error.Errors.PARSE); Response errorResp = new Response(id, err); server.reply(errorResp.getJsonString()); currBatch = null; } - return new ArrayList<>(); //se ci sono errori la lista di richieste da eseguire è vuota + return new ArrayList<>(); // if there are errors, the list of requests to execute is empty } public void reply(Response response) throws JSONRPCException { @@ -59,11 +59,11 @@ public void reply(ArrayList responses) throws JSONRPCException { throw new JSONRPCException("Single response needed"); } if (responses.size() == 0) { - //nessuna risposta a batch di sole notifiche + // no response to a batch of only notifications currBatch = null; } else if (responses.size() == 1 && currBatch == null) { - //risposta singola a richiesta singola - //currBatch == null evita di rispondere con una risposta singola a un batch di richieste di dimensione 1. in questo caso si risponde con un batch di risposte di dimensione 1 + // single response to a single request + // when currBatch == null, it prevents responding with a single response to a batch of requests of size 1. In this case, respond with a batch of responses of size 1 this.reply(responses.get(0)); } else { currBatch.put(responses); @@ -71,5 +71,4 @@ public void reply(ArrayList responses) throws JSONRPCException { currBatch = null; } } - -} +} \ No newline at end of file diff --git a/jsonrpc/src/jsonrpc/StructuredMember.java b/jsonrpc/src/jsonrpc/StructuredMember.java index 28ac0ed..e7713df 100644 --- a/jsonrpc/src/jsonrpc/StructuredMember.java +++ b/jsonrpc/src/jsonrpc/StructuredMember.java @@ -11,7 +11,6 @@ public class StructuredMember { private JSONArray list; private JSONObject map; - private boolean isArray; StructuredMember(JSONObject obj) { @@ -20,6 +19,7 @@ public class StructuredMember { list = null; isArray = false; } + StructuredMember(JSONArray array) { if (array.length() == 0) {throw new InvalidParameterException("Json array is empty");} list = array; @@ -41,7 +41,6 @@ public StructuredMember(ArrayList members) { isArray = true; } - public boolean isArray() { return isArray; } @@ -139,10 +138,10 @@ public static StructuredMember toStructuredMember(Object obj) { } @Override - public boolean equals(Object other){ + public boolean equals(Object other) { if (other == null) return false; if (other == this) return true; - if (!(other instanceof StructuredMember))return false; + if (!(other instanceof StructuredMember)) return false; StructuredMember o = (StructuredMember) other; if (this.isArray) { return o.isArray && getList().equals(o.getList()); diff --git a/jsonrpc/src/jsonrpc/Test.java b/jsonrpc/src/jsonrpc/Test.java index 43e50e7..a7b9e60 100644 --- a/jsonrpc/src/jsonrpc/Test.java +++ b/jsonrpc/src/jsonrpc/Test.java @@ -10,16 +10,17 @@ public class Test { public static void main(String args[]) { //testBatch(); - /*testRequestFromString(); + /* + testRequestFromString(); testResponseFromString(); testRequestFromParams(); - testResponseFromParams();*/ + testResponseFromParams(); + */ } - private static void testRequestFromParams() { ArrayList params = new ArrayList<>(); - params.add(null); //modo corretto per omettere i parametri opzionali + params.add(null); // correct way to omit optional parameters ArrayList pl = new ArrayList<>(); HashMap hm = new HashMap<>(); @@ -61,12 +62,9 @@ private static void testRequestFromParams() { memberlist.add(boolmap); membermap.put("map", boolmap); - - params.add(new StructuredMember(memberlist)); params.add(new StructuredMember(membermap)); - String method = "testmetodo"; ArrayList ids = new ArrayList<>(); ids.add(new Id()); @@ -86,9 +84,8 @@ private static void testRequestFromParams() { System.out.println(System.lineSeparator()); } } - - } + private static void testResponseFromParams() { ArrayList ids= new ArrayList<>(); ids.add(new Id(1)); @@ -121,6 +118,7 @@ private static void testResponseFromParams() { } } + private static void testResponseFromString() { ArrayList testStrings = new ArrayList<>(); testStrings.add("{\"jsonrpc\": \"2.0\", \"result\": 19, \"id\": 1}"); @@ -169,6 +167,7 @@ private static void readResp(AbstractResponse resp) { System.out.println("NON COSTRUTTORE: " + e.getClass().toString() + " - " + e.getMessage()); } } + private static void readReq(AbstractRequest req) { try { System.out.println("Notifica: " + req.isNotify()); @@ -199,10 +198,10 @@ private static void testRequestFromString() { testStrings.add("{\"jsonrpc\": \"2.0\", \"method\": \"test\", \"params\": {\"subtrahend\": 23, \"minuend\": 42, \"subobj\": {\"par1\": 34, \"par2\": \"value\", \"array\": [1,2,3]}}, \"id\": 3}"); testStrings.add(""); testStrings.add("test"); - testStrings.add("{\"method\": \"subtract\", \"params\": [42, 23], \"id\": 1}"); //no jsonrpc 2.0 - testStrings.add("{\"jsonrpc\": \"3.0\", \"method\": \"subtract\", \"params\": [42, 23], \"id\": 1}"); //jsonrpc <> 2.0 - testStrings.add("{\"jsonrpc\": \"2.0\", \"method\": \"subtract\", \"params\": 42, \"id\": 1}"); //parametri non structure - testStrings.add("{\"jsonrpc\": \"2.0\", \"method\": \"subtract\", \"params\": [42, 23], \"id\": null}"); //id nullo + testStrings.add("{\"method\": \"subtract\", \"params\": [42, 23], \"id\": 1}"); // no jsonrpc 2.0 + testStrings.add("{\"jsonrpc\": \"3.0\", \"method\": \"subtract\", \"params\": [42, 23], \"id\": 1}"); // jsonrpc <> 2.0 + testStrings.add("{\"jsonrpc\": \"2.0\", \"method\": \"subtract\", \"params\": 42, \"id\": 1}"); // unstructured parameters + testStrings.add("{\"jsonrpc\": \"2.0\", \"method\": \"subtract\", \"params\": [42, 23], \"id\": null}"); // null ID for (String ts : testStrings) { System.out.println(ts); @@ -210,11 +209,9 @@ private static void testRequestFromString() { System.out.println(System.lineSeparator()); System.out.println(System.lineSeparator()); System.out.println(System.lineSeparator()); - } } - private static String readStructured(StructuredMember params) throws JSONException, JSONRPCException { if (params == null) {return "";} if (params.isArray()) { @@ -222,8 +219,8 @@ private static String readStructured(StructuredMember params) throws JSONExcepti } else { return readObj(params.getJSONObject()); } - } + private static String readArray(JSONArray params) throws JSONRPCException { StringBuilder val= new StringBuilder(); for (int i = 0; i < params.length(); i++) { @@ -236,9 +233,9 @@ private static String readArray(JSONArray params) throws JSONRPCException { } return val.toString(); } + private static String readObj(JSONObject params) throws JSONRPCException { StringBuilder val= new StringBuilder(); - Iterator keys = params.keys(); while( keys.hasNext() ) { @@ -267,5 +264,4 @@ private static String readMember(Member m) throws JSONRPCException { default: throw new JSONRPCException("Unexpected member type"); } } - -} +} \ No newline at end of file diff --git a/jsonrpc/test/test/AllTest.java b/jsonrpc/test/test/AllTest.java index ff66dac..5225395 100644 --- a/jsonrpc/test/test/AllTest.java +++ b/jsonrpc/test/test/AllTest.java @@ -6,4 +6,4 @@ @RunWith(Suite.class) @Suite.SuiteClasses({RequestTest.class, ResponseTest.class, BatchTest.class, ClientTest.class, ServerTest.class}) public class AllTest { -} +} \ No newline at end of file diff --git a/jsonrpc/test/test/BatchTest.java b/jsonrpc/test/test/BatchTest.java index 93ce550..ede1ee4 100644 --- a/jsonrpc/test/test/BatchTest.java +++ b/jsonrpc/test/test/BatchTest.java @@ -26,7 +26,7 @@ public class BatchTest { @BeforeClass public static void setUpBeforeClass() { - //crea alcune richieste valide da usare nei test + // generate some valid requests to use in tests validReqs.add(new Request("method", null, new Id("a"))); validReqs.add(new Request("method", null, new Id(1))); @@ -82,8 +82,8 @@ private void testInvalidRequest(ArrayList reqs) { } private void testInvalidRequest(Batch b, int i) { - assertTrue(b.getAllRequests().get(i)==null); //l'ultima request è null perché invalida - assertTrue(b.getValidRequests().size()==i); //la request non viene inserita tra le valide + assertTrue(b.getAllRequests().get(i)==null); // last request is null because it is invalid + assertTrue(b.getValidRequests().size()==i); // request is not included among the valid ones b.put(validResps); assertEquals(b.getAllResponses(), b.getValidResponses()); assertTrue(b.getAllResponses().get(i).hasError()); @@ -215,6 +215,5 @@ public void testIsOnlyNotifies() throws JSONException { arr.put(r2.getObj().put("not", "a valid request")); assertFalse(new Batch(arr).isOnlyNotifies()); - } -} +} \ No newline at end of file diff --git a/jsonrpc/test/test/ClientTest.java b/jsonrpc/test/test/ClientTest.java index a358629..6f46bde 100644 --- a/jsonrpc/test/test/ClientTest.java +++ b/jsonrpc/test/test/ClientTest.java @@ -34,7 +34,7 @@ class RunServer implements Runnable { } public void run() { - //while(true) { + // while(true) { ArrayList reqs = s.receive(); ArrayList resps = new ArrayList<>(); for (Request r : reqs) { @@ -47,11 +47,10 @@ public void run() { } catch (JSONRPCException e) { fail(e.getMessage()); } - //} + // } } } - @Test public void sendRequest() throws JSONRPCException { Request req = new Request("method", null, new Id(1)); @@ -71,7 +70,7 @@ public void sendNull() throws JSONRPCException { public void sendNotify() throws JSONRPCException { Request notify = new Request("method", null); client.sendNotify(notify); - //no exception thrown + // no exception thrown } @Test(expected = JSONRPCException.class) @@ -133,5 +132,4 @@ public void sendMixedBatch() { assertEquals(id1, resps.get(0).getId()); assertEquals(id2, resps.get(1).getId()); } - } \ No newline at end of file diff --git a/jsonrpc/test/test/ErrorTest.java b/jsonrpc/test/test/ErrorTest.java index b73adf1..88b7b3d 100644 --- a/jsonrpc/test/test/ErrorTest.java +++ b/jsonrpc/test/test/ErrorTest.java @@ -27,7 +27,6 @@ public static void setUpBeforeClass() { errData = new Member(new StructuredMember(data)); } - @Test public void hasErrorData() { Error e = new Error(Error.Errors.INTERNAL_ERROR); diff --git a/jsonrpc/test/test/MemberTest.java b/jsonrpc/test/test/MemberTest.java index 79e4ddc..bb502ef 100644 --- a/jsonrpc/test/test/MemberTest.java +++ b/jsonrpc/test/test/MemberTest.java @@ -17,8 +17,8 @@ public class MemberTest extends Member { - //TODO: fix - /*@Test + /* TODO: fix + @Test public void toMember() throws JSONException { JSONArray array = new JSONArray(); JSONObject object = new JSONObject(); @@ -110,5 +110,4 @@ public void equals() { assertNotEquals(lm, Member.toMember(map)); assertEquals(lm, Member.toMember(list)); } - } \ No newline at end of file diff --git a/jsonrpc/test/test/RequestTest.java b/jsonrpc/test/test/RequestTest.java index aed8668..78d1318 100644 --- a/jsonrpc/test/test/RequestTest.java +++ b/jsonrpc/test/test/RequestTest.java @@ -31,7 +31,6 @@ public static void setUpBeforeClass() { paramsMap = new StructuredMember(par); } - @Test (expected = InvalidParameterException.class) public void testNullMethodConstructor() { new Request(null, paramsList); @@ -107,25 +106,25 @@ public void testFromInvalidJson() { @Rule public ExpectedException expectedEx = ExpectedException.none(); - @Test //(expected = InvalidParameterException.class) + @Test // (expected = InvalidParameterException.class) public void testNoVersion() { expectedEx.expect(InvalidParameterException.class); expectedEx.expectMessage("Not jsonrpc 2.0"); - //no jsonrpc 2.0 + // no jsonrpc 2.0 new Request("{\"method\": \"subtract\", \"params\": [42, 23], \"id\": 1}"); fail("Expected invalid parameter exception"); } - @Test //(expected = InvalidParameterException.class) + @Test // (expected = InvalidParameterException.class) public void testWrongVergion() { expectedEx.expect(InvalidParameterException.class); expectedEx.expectMessage("Not jsonrpc 2.0"); - //jsonrpc != 2.0 + // jsonrpc != 2.0 new Request("{\"jsonrpc\": \"3.0\", \"method\": \"subtract\", \"params\": [42, 23], \"id\": 1}"); fail("Expected invalid parameter exception"); } - @Test //(expected = InvalidParameterException.class) + @Test // (expected = InvalidParameterException.class) public void testNotStructuredParams() { expectedEx.expect(InvalidParameterException.class); expectedEx.expectMessage("Not a structured member"); diff --git a/jsonrpc/test/test/ResponseTest.java b/jsonrpc/test/test/ResponseTest.java index e9d8ba5..6cd7e0e 100644 --- a/jsonrpc/test/test/ResponseTest.java +++ b/jsonrpc/test/test/ResponseTest.java @@ -80,29 +80,27 @@ public void testInvlidJson() { fail("Expected invalid parameter exception"); } - @Rule public ExpectedException expectedEx = ExpectedException.none(); - @Test //(expected = InvalidParameterException.class) + @Test // (expected = InvalidParameterException.class) public void testNoVersion() { expectedEx.expect(InvalidParameterException.class); expectedEx.expectMessage("Not jsonrpc 2.0"); - //no jsonrpc 2.0 + // no jsonrpc 2.0 new Response("{\"result\": 19, \"id\": 1}"); fail("Expected invalid parameter exception"); } - @Test //(expected = InvalidParameterException.class) + @Test // (expected = InvalidParameterException.class) public void testWrongVersion() { expectedEx.expect(InvalidParameterException.class); expectedEx.expectMessage("Not jsonrpc 2.0"); - //no jsonrpc 2.0 + // no jsonrpc 2.0 new Response("{\"jsonrpc\": \"2\", \"result\": 19, \"id\": 1}"); fail("Expected invalid parameter exception"); } - @Test public void testExtraMembers() { try { @@ -131,6 +129,5 @@ public void testJson() { assertTrue(r.hasError()); e = new Error(Error.Errors.PARSE); assertEquals(e, r.getError()); - } } \ No newline at end of file diff --git a/jsonrpc/test/test/ServerTest.java b/jsonrpc/test/test/ServerTest.java index fcb34a5..c9f1629 100644 --- a/jsonrpc/test/test/ServerTest.java +++ b/jsonrpc/test/test/ServerTest.java @@ -28,12 +28,12 @@ public void setUp() { @Test public void receive() { - //receive single request (JSONObject) + // receive single request (JSONObject) client.send(req.getJsonString()); ArrayList r = server.receive(); assertEquals(1, r.size()); assertEquals(req, r.get(0)); - //receive batch of one request + // receive batch of one request ArrayList reqs = new ArrayList<>(); reqs.add(not); Batch b = new Batch(reqs); @@ -41,7 +41,7 @@ public void receive() { r = server.receive(); assertEquals(1, r.size()); assertEquals(not, r.get(0)); - //receive multiple request (batch) (JSONArray) + // receive multiple request (batch) (JSONArray) reqs = new ArrayList<>(); reqs.add(req); reqs.add(not); @@ -87,18 +87,11 @@ public void replySingleEx() throws JSONRPCException { fail("Expected Unsupported Operation exception"); } - /*testare invio risposta singola a batch e viceversa (invalido!) - testare invio risposta singola a batch di dim 1 (valido!) - testare invio a batch di sole notifiche - - testare invii normali*/ - @Test public void replySingleResponse() { } @Test public void replyMultiResponses() { - } } \ No newline at end of file diff --git a/jsonrpc/test/test/StructuredMemberTest.java b/jsonrpc/test/test/StructuredMemberTest.java index 7d13889..5c6a755 100644 --- a/jsonrpc/test/test/StructuredMemberTest.java +++ b/jsonrpc/test/test/StructuredMemberTest.java @@ -14,8 +14,8 @@ import static org.junit.Assert.*; public class StructuredMemberTest { - //i costruttori da jsonarray e jsonobject non sono testati perché assegnano semplicemente il valore - //stessa cosa per i getarray e getobj che sono dei semplici getter + // constructors from JSONArray and JSONObject are not tested because they simply assign the value + // same for getArray and getObj, which are simple getters @Test public void getMap() { @@ -26,10 +26,10 @@ public void getMap() { StructuredMember subobj = new StructuredMember(map); map.put("subobj", new Member(subobj)); - //la costruzione da map crea internamente un jsonobject + // construction from map internally creates a JSONObject StructuredMember tested = new StructuredMember(map); assertFalse(tested.isArray()); - //dal jsonobject viene ricava la mappa + // the map is extracted from the JSONObject assertEquals(map, tested.getMap()); } @@ -42,10 +42,10 @@ public void getList() { StructuredMember subarray = new StructuredMember(list); list.add(new Member(subarray)); - //la costruzione da lista crea internamente un jsonarray + // construction from list internally creates a JSONArray StructuredMember tested = new StructuredMember(list); assertTrue(tested.isArray()); - //dal jsonarray viene ricavata la lista + // the list is extracted from the JSONArray assertEquals(list, tested.getList()); } @@ -79,5 +79,4 @@ public void equals() throws JSONException { Collections.reverse(list); assertNotEquals(sm2, new StructuredMember(list)); } - } \ No newline at end of file diff --git a/zeromq/src/zeromq/IZmqClient.java b/zeromq/src/zeromq/IZmqClient.java index 4d1cdfa..8c2a02d 100644 --- a/zeromq/src/zeromq/IZmqClient.java +++ b/zeromq/src/zeromq/IZmqClient.java @@ -3,4 +3,4 @@ public interface IZmqClient { String request(String req); void send(String msg); -} +} \ No newline at end of file diff --git a/zeromq/src/zeromq/IZmqServer.java b/zeromq/src/zeromq/IZmqServer.java index d5f5e7f..0659d4c 100644 --- a/zeromq/src/zeromq/IZmqServer.java +++ b/zeromq/src/zeromq/IZmqServer.java @@ -3,4 +3,4 @@ public interface IZmqServer { String receive(); void reply(String string) throws UnsupportedOperationException; -} +} \ No newline at end of file diff --git a/zeromq/src/zeromq/ZmqClient.java b/zeromq/src/zeromq/ZmqClient.java index e32fe0b..1449a07 100644 --- a/zeromq/src/zeromq/ZmqClient.java +++ b/zeromq/src/zeromq/ZmqClient.java @@ -12,7 +12,7 @@ public ZmqClient(int port) { this.port = port; } - //usare pattern pool per le connessioni? + // use a connection pooling pattern for connections? @Override public String request(String req) { socket = ctx.socket(ZMQ.REQ); diff --git a/zeromq/src/zeromq/ZmqServer.java b/zeromq/src/zeromq/ZmqServer.java index 1672dee..d6eba36 100644 --- a/zeromq/src/zeromq/ZmqServer.java +++ b/zeromq/src/zeromq/ZmqServer.java @@ -4,7 +4,7 @@ import org.zeromq.ZMQ; import org.zeromq.ZMsg; -public class ZmqServer implements IZmqServer{ +public class ZmqServer implements IZmqServer { private ZMQ.Socket socket; private ZFrame identity; private ZFrame empty; @@ -23,23 +23,23 @@ public ZmqServer(int port) { @Override public String receive() { ZMsg msg = ZMsg.recvMsg(socket); - identity = msg.pop(); //i messaggi in arrivo dal dealer hanno una identity ed è quindi possibile rispondere - empty = msg.size() == 2 ? msg.pop() : null; //i messaggi inviati dal dealer non hanno frame vuoto + identity = msg.pop(); // incoming messages from the dealer have an identity, making it possible to reply + empty = msg.size() == 2 ? msg.pop() : null; // messages sent by the dealer do not have an empty frame return msg.pop().toString(); } @Override public void reply(String string) throws UnsupportedOperationException{ - if (identity == null) { throw new UnsupportedOperationException("Receiver undefined"); } //cambiare tipo eccezione + if (identity == null) { throw new UnsupportedOperationException("Receiver undefined"); } // change exception type ZMsg msg = new ZMsg(); msg.push(new ZFrame(string.getBytes())); - if (empty!=null) {msg.push(empty);} //i messaggi da inviare al dealer non devono avere empty frame + if (empty!=null) {msg.push(empty);} // messages to be sent to the dealer must not have empty frames msg.push(identity); msg.send(socket); - //in teoria un router può rispondere tante volte a un solo messaggio, non sapendo di che tipo è il client (non è detto sia un req) - //nel caso si voglia rendere possibile non vanno settati a null identity ed empty, ma il server potrebbe rispondere più volte solo all'ultimo client + // in theory, a router can reply multiple times to a single message, not knowing the client's type (it might not necessarily be a req) + // in case it is desired to make it possible, do not set identity and empty to null, but the server might reply multiple times only to the last client identity = null; empty = null; } -} +} \ No newline at end of file diff --git a/zeromq/test/test/ZmqTest.java b/zeromq/test/test/ZmqTest.java index 23d760f..8e6d3a2 100644 --- a/zeromq/test/test/ZmqTest.java +++ b/zeromq/test/test/ZmqTest.java @@ -23,7 +23,7 @@ public static void setUpBeforeClass() { @Before public void setUp() { - //ogni test ha un server che ascolta su una porta diversa + // each test has a server listening on a different port s = new ZmqServer(port); c = new ZmqClient(port); port++; @@ -48,7 +48,7 @@ public void testSendNull() { @Test public void testSendEmpty() { c.send(""); - //no exception thrown + // no exception thrown } @Test @@ -93,7 +93,7 @@ public void testMultipleRequestAndNotify() { public void testSendToNoServer() { c = new ZmqClient(5123); c.send(MSG); - //no exception thrown + // no exception thrown } @SuppressWarnings("InfiniteLoopStatement") @@ -107,6 +107,4 @@ public void run() { } } } - - } \ No newline at end of file