Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Code translation and small changes #1

Open
wants to merge 7 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Binary file removed .README_images/classDiagram.jpeg
Binary file not shown.
Binary file removed .README_images/goaldiagram.png
Binary file not shown.
3 changes: 2 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
@@ -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.

Expand Down
30 changes: 9 additions & 21 deletions jsonrpc/src/jsonrpc/AbstractRequest.java
Original file line number Diff line number Diff line change
Expand Up @@ -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");

Expand All @@ -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;
Expand All @@ -31,50 +31,38 @@ 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();
}

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);
}
}
}
15 changes: 10 additions & 5 deletions jsonrpc/src/jsonrpc/AbstractResponse.java
Original file line number Diff line number Diff line change
Expand Up @@ -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)) {
Expand All @@ -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();
}
Expand All @@ -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) {
Expand All @@ -74,4 +79,4 @@ public boolean equals(Object other){
return this.error.equals(o.error) && o.result == null;
}
}
}
}
49 changes: 25 additions & 24 deletions jsonrpc/src/jsonrpc/Batch.java
Original file line number Diff line number Diff line change
Expand Up @@ -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<Request> reqs;
private ArrayList<Response> 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<Request> requests) { //public solo per test
public Batch(ArrayList<Request> requests) { // public only for test
JSONArray array = new JSONArray();
for (Request r : requests) {
array.put( r == null ? null : r.getObj() );
Expand All @@ -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 {
Expand All @@ -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<Response> 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<Response> 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
}
}

Expand All @@ -87,11 +88,11 @@ void put(JSONArray responses) {
this.put(resps);
}

public ArrayList<Request> getAllRequests() {
public ArrayList<Request> getAllRequests() { // public only for test
return reqs;
} //solo per test
}

public ArrayList<Request> getValidRequests() { //public solo per test
public ArrayList<Request> getValidRequests() { // public only for test
ArrayList<Request> rq = new ArrayList<>();
for (Request r : reqs) {
if (r!=null) {
Expand All @@ -101,11 +102,11 @@ public ArrayList<Request> getValidRequests() { //public solo per test
return rq;
}

public ArrayList<Response> getAllResponses() {
public ArrayList<Response> getAllResponses() { // public only for test
return resps;
} //solo per test
}

public ArrayList<Response> getValidResponses() { //public solo per test
public ArrayList<Response> getValidResponses() { // public only for test
ArrayList<Response> rp = new ArrayList<>();
for (Response r : resps) {
if (r!=null) {
Expand All @@ -115,17 +116,17 @@ public ArrayList<Response> 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());
Expand All @@ -136,4 +137,4 @@ public String getRequestJSON() { //public solo per test
public boolean isOnlyNotifies() {
return onlyNotifies;
}
}
}
16 changes: 9 additions & 7 deletions jsonrpc/src/jsonrpc/Client.java
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@

public class Client implements IClient {
private IZmqClient zmqClient;

public Client(int port) {
zmqClient = new ZmqClient(port);
}
Expand All @@ -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());
}
Expand All @@ -50,15 +52,15 @@ public ArrayList<Response> sendBatch(ArrayList<Request> 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<String, Member> 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<String, Member> 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<Response> resp = new ArrayList<>();
resp.add(errorResp);
return resp;
}
}
}
}
}
Loading