DS_project_SHARE

Implementation of SHARE command by Frankie: ----------------------------------------------------Resource.java------------------------------------------------------ package EZShare; import java.net.*; public class Resource { public String name; public String description; public String[] tags; public URI uri; private String channel; public String owner; public String ezserver; //public HashMap<String, Object> primarykey; // signals for string error??? //public boolean stringerror; //private String rule; public Resource() { name = ""; description = ""; tags= new String[]{}; uri = null; channel = ""; owner = ""; ezserver = "localhost:8080"; //rule = ""; //primarykey = null; } public String getChannel() { return channel; } public void changeChannel(String word) { channel = word; } /* public void primaryKey(String Owner, String Channel, URI Uri) { primarykey.put("owner",Owner); primarykey.put("channel",Channel); primarykey.put("uri",Uri); } public void breakRule() { rule = "broken"; } */ } -----------------------------------------------------Client.java------------------------------------------------------------- package EZShare; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.net.ServerSocket; import java.net.Socket; import java.net.URI; import java.net.URISyntaxException; import java.net.UnknownHostException; import java.util.Arrays; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; import org.json.simple.parser.ParseException; import com.google.gson.Gson; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.CommandLineParser; import org.apache.commons.cli.Options; import org.apache.commons.cli.DefaultParser; import org.apache.commons.cli.HelpFormatter; public class Client { private static String ip = "localhost"; // 127.0.0.1 private static int port = 8080; public static void main(String[] args) { try(Socket socket = new Socket(ip,port)) { DataInputStream input = new DataInputStream(socket.getInputStream()); DataOutputStream output = new DataOutputStream(socket.getOutputStream()); output.writeUTF("Hello server"); output.flush(); Options options = new Options(); JSONObject command = new JSONObject(); Resource resource = new Resource(); JSONObject send = new JSONObject(); // put resource in //JSONObject secret = new JSONObject(); // client command line arguments options.addOption("channel",true,"channel"); options.addOption("debug",false,"print debug information"); options.addOption("description",true,"resource description"); options.addOption("exchange",false,"exchange server list with server"); options.addOption("fetch",false,"fetch resources from server"); options.addOption("host",true,"server host, a domain name or IP address"); options.addOption("name",true,"resource name"); options.addOption("owner",true,"owner"); options.addOption("port",true,"server port, an integer"); options.addOption("publish",false,"publish resource on server"); options.addOption("query",false,"query for resources from server"); options.addOption("remove",false,"remove resource from server"); options.addOption("secret",true,"secret"); options.addOption("servers",true,"server list, host1:port1,host2:port2,..."); options.addOption("share",false,"share resource on server"); options.addOption("tags",true,"resource tags, tag1,tag2,tag3,..."); options.addOption("uri",true,"resource URI"); //options.addOption("email",true, "input email address"); CommandLineParser parser = new DefaultParser(); CommandLine cmd = null; try { cmd = parser.parse(options,args); } catch (org.apache.commons.cli.ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } // PUBLISH command if(cmd.hasOption("publish")){ if(cmd.hasOption("name")) { resource.name = cmd.getOptionValue("name"); } if(cmd.hasOption("description")) { resource.description = cmd.getOptionValue("description"); } if(cmd.hasOption("tags")) { resource.tags = cmd.getOptionValue("tags").split(","); System.out.println(Arrays.toString(resource.tags)); /* for(String tag:resource.tags) { if (tag.startsWith(" ") || tag.endsWith(" ") || tag.contains("\0")) { System.out.println("The server may silently remove these things from receive resource descriptions"); } }*/ } if(cmd.hasOption("channel")) { // "" is though of as public channel???????????????? resource.changeChannel(cmd.getOptionValue("channel")); } if(cmd.hasOption("owner")) { resource.owner = cmd.getOptionValue("owner"); /* if (resource.owner.startsWith(" ") || resource.owner.endsWith(" ") || resource.owner.contains("\0") || resource.owner.equals("*")) { System.out.println("The server may silently remove these things from receive resource descriptions"); }*/ } // Put resource into JSON command //resource.primaryKey(resource.owner, resource.getChannel(), resource.uri); /* Gson gson = new Gson(); String send = gson.toJson(resource); command.put("resource", send); */ // MANDANTORY URI if(cmd.hasOption("uri")) { resource.uri = new URI(cmd.getOptionValue("uri")); } send.put("name", resource.name); send.put("description",resource.description); //send.put("tags", Arrays.toString(resource.tags)); JSONArray arr = new JSONArray(); for(String tag: resource.tags) { arr.add(tag); } send.put("tags", arr); send.put("channel", resource.getChannel()); send.put("owner", resource.owner); send.put("uri", resource.uri.toString()); send.put("ezserver", resource.ezserver); command.put("resource", send); command.put("command", "PUBLISH"); } // REMOVE command // SHARE command if(cmd.hasOption("share")){ if(cmd.hasOption("name")) { resource.name = cmd.getOptionValue("name"); } if(cmd.hasOption("description")) { resource.description = cmd.getOptionValue("description"); } if(cmd.hasOption("tags")) { resource.tags = cmd.getOptionValue("tags").split(","); System.out.println(Arrays.toString(resource.tags)); /* for(String tag:resource.tags) { if (tag.startsWith(" ") || tag.endsWith(" ") || tag.contains("\0")) { System.out.println("The server may silently remove these things from receive resource descriptions"); } }*/ } if(cmd.hasOption("channel")) { // "" is though of as public channel???????????????? resource.changeChannel(cmd.getOptionValue("channel")); } if(cmd.hasOption("owner")) { resource.owner = cmd.getOptionValue("owner"); /* if (resource.owner.startsWith(" ") || resource.owner.endsWith(" ") || resource.owner.contains("\0") || resource.owner.equals("*")) { System.out.println("The server may silently remove these things from receive resource descriptions"); }*/ } // Put resource into JSON command //resource.primaryKey(resource.owner, resource.getChannel(), resource.uri); /* Gson gson = new Gson(); String send = gson.toJson(resource); command.put("resource", send); */ // MANDANTORY URI if(cmd.hasOption("uri")) { resource.uri = new URI(cmd.getOptionValue("uri")); } // MANDANTORY secret if(cmd.hasOption("secret")) { command.put("secret", cmd.getOptionValue("secret")); } send.put("name", resource.name); send.put("description",resource.description); //send.put("tags", Arrays.toString(resource.tags)); JSONArray arr = new JSONArray(); for(String tag: resource.tags) { arr.add(tag); } send.put("tags", arr); send.put("channel", resource.getChannel()); send.put("owner", resource.owner); send.put("uri", resource.uri.toString()); send.put("ezserver", resource.ezserver); command.put("resource", send); command.put("command", "SHARE"); } output.writeUTF(command.toJSONString()); JSONParser js_parser = new JSONParser(); //String message = input.readUTF(); while(true){ if(input.available() > 0) { JSONObject result = (JSONObject) js_parser.parse(input.readUTF()); System.out.println("Received from Server: "+ result.get("results")); } } } catch (UnknownHostException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (URISyntaxException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } -------------------------------------------------------Server.java--------------------------------------------------------- package EZShare; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.File; import java.io.IOException; import java.net.ServerSocket; import java.net.Socket; import java.net.URI; import java.net.URISyntaxException; import java.text.ParseException; import java.util.ArrayList; import java.util.List; import javax.net.ServerSocketFactory; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.CommandLineParser; import org.apache.commons.cli.DefaultParser; import org.apache.commons.cli.Options; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; import org.json.simple.JSONArray; public class Server { private static int port = 8080; private static String advertisedhostname; private static String secret = "whoami";//"5uv1ii7ec362me7hkch3s7l5c4"; private static int exchangeinterval = 600; // seconds private static List<Resource> resourcelist = new ArrayList<Resource>(); public static void main(String[] args) { ServerSocketFactory factory = ServerSocketFactory.getDefault(); try(ServerSocket server = factory.createServerSocket(port)) { boolean isActive = true; Options options = new Options(); JSONObject command = new JSONObject(); // server command line arguments options.addOption("advertisedhostname",true,"advertised host name"); options.addOption("connectionintervallimit",true,"connection interval limit in seconds"); options.addOption("exchangeinterval",true,"exchange interval in seconds"); options.addOption("port",true,"server port, an integer"); options.addOption("secret",true,"secret"); options.addOption("debug",false,"print debug information"); //options.addOption("email",true, "input email address"); CommandLineParser parser = new DefaultParser(); CommandLine cmd = null; try { cmd = parser.parse(options,args); } catch (org.apache.commons.cli.ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } while(isActive){ Socket Client = server.accept(); System.out.println("A client has connected."); Thread r =new Thread(()-> serverClient(Client)); r.start(); } } catch (IOException e) { e.printStackTrace(); } } private static JSONObject parseCommand(JSONObject command) { int result = 0; //Resource resource = new Resource(); JSONParser parser = new JSONParser(); JSONObject receive = new JSONObject(); JSONObject message = new JSONObject(); Resource resource = new Resource(); //String receivedsecret = ""; URI uri; if(command.containsKey("command")) { // PUBLISH------------------------------------------------------------------- if(command.get("command").equals("PUBLISH")) { boolean publisherror = false; /* try { resource = (JSONObject) parser.parse((String) command.get("resource")); } catch (org.json.simple.parser.ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } */ receive = (JSONObject) command.get("resource"); resource.name = (String) receive.get("name"); try { resource.uri = new URI((String)receive.get("uri")); } catch (URISyntaxException e) { // TODO Auto-generated catch block e.printStackTrace(); } resource.description = (String) receive.get("description"); resource.changeChannel((String) receive.get("channel")); resource.owner = (String) receive.get("owner"); resource.tags = new String[((JSONArray) receive.get("tags")).size()]; for(int i = 0, count = resource.tags.length; i< count; i++) { resource.tags[i] = (String) ((JSONArray) receive.get("tags")).get(i); } // Publishing a resource with the same channel and URI but different owner is not allowed. for (Resource r: resourcelist) { if(resource.getChannel().equals(r.getChannel())&&resource.uri.equals(r.uri) && resource.owner.equals(r.owner)) { publisherror = true; } } if (resource.uri == null) { message.put("response", "error"); message.put("errorMessage", "missing resource"); } else if (!resource.uri.isAbsolute() || resource.uri.getScheme().equals("file")) { //The URI must be present, must be absolute and cannot be a file scheme. message.put("response", "error"); message.put("errorMessage", "invalid resource"); } else if (resource.name.startsWith(" ") || resource.name.endsWith(" ") || resource.name.contains("\0")) { message.put("response", "error"); message.put("errorMessage", "invalid resource"); } else if (resource.description.startsWith(" ") || resource.description.endsWith(" ") || resource.description.contains("\0")) { message.put("response", "error"); message.put("errorMessage", "invalid resource"); } else if (resource.getChannel().startsWith(" ") || resource.getChannel().endsWith(" ") || resource.getChannel().contains("\0")) { message.put("response", "error"); message.put("errorMessage", "invalid resource"); } else if (resource.owner.startsWith(" ") || resource.owner.endsWith(" ") || resource.owner.contains("\0") || resource.owner.equals("*")) { message.put("response", "error"); message.put("errorMessage", "invalid resource"); } else if (publisherror == true) { message.put("response", "error"); message.put("errorMessage", "cannot publish resource"); } else { // check if the primary key is same with exists // if yes, overwrite for (Resource r: resourcelist) { if (r.owner.equals(resource.owner)&&r.getChannel().equals(resource.getChannel()) &&r.uri.equals(resource.uri)) { resourcelist.remove(r); } } resourcelist.add(resource); message.put("response", "success"); } } else if(command.get("command").equals("SHARE")) { // SHARE-------------------------------------------------------------------------- boolean shareerror = false; //receivedsecret = (String) command.get("secret"); System.out.println(secret); System.out.println(command.get("secret")); receive = (JSONObject) command.get("resource"); resource.name = (String) receive.get("name"); try { resource.uri = new URI((String)receive.get("uri")); } catch (URISyntaxException e) { // TODO Auto-generated catch block e.printStackTrace(); } resource.description = (String) receive.get("description"); resource.changeChannel((String) receive.get("channel")); resource.owner = (String) receive.get("owner"); resource.tags = new String[((JSONArray) receive.get("tags")).size()]; for(int i = 0, count = resource.tags.length; i< count; i++) { resource.tags[i] = (String) ((JSONArray) receive.get("tags")).get(i); } File file = new File(resource.uri.getPath()); // Publishing a resource with the same channel and URI but different owner is not allowed. for (Resource r: resourcelist) { if(resource.getChannel().equals(r.getChannel())&&resource.uri.equals(r.uri) && resource.owner.equals(r.owner)) { shareerror = true; } } if (resource.uri == null) { message.put("response", "error"); message.put("errorMessage", "missing resource and/or secret"); } else if (!resource.uri.isAbsolute() || !resource.uri.getScheme().equals("file") || !file.exists()) { //The URI must be present, must be absolute, non-authoritative and must be a file scheme. It must point //to a file on the local file system that the server can read as a file. message.put("response", "error"); message.put("errorMessage", "invalid resource"); } else if (command.get("secret") == null) { //If the resource or secret field was not given or not of the correct type message.put("response", "error"); message.put("errorMessage", "missing resource and/or secret"); } else if (!command.get("secret").getClass().equals(String.class)) { message.put("response", "error"); message.put("errorMessage", "missing resource and/or secret"); } else if (!command.get("secret").equals(secret)) { message.put("response", "error"); message.put("errorMessage", "incorrect secret"); } else if (resource.name.startsWith(" ") || resource.name.endsWith(" ") || resource.name.contains("\0")) { message.put("response", "error"); message.put("errorMessage", "invalid resource"); } else if (resource.description.startsWith(" ") || resource.description.endsWith(" ") || resource.description.contains("\0")) { message.put("response", "error"); message.put("errorMessage", "invalid resource"); } else if (resource.getChannel().startsWith(" ") || resource.getChannel().endsWith(" ") || resource.getChannel().contains("\0")) { message.put("response", "error"); message.put("errorMessage", "invalid resource"); } else if (resource.owner.startsWith(" ") || resource.owner.endsWith(" ") || resource.owner.contains("\0") || resource.owner.equals("*")) { message.put("response", "error"); message.put("errorMessage", "invalid resource"); } else if (shareerror == true) { message.put("response", "error"); message.put("errorMessage", "cannot share resource"); } else { // check if the primary key is same with exists // if yes, overwrite for (Resource r: resourcelist) { if (r.owner.equals(resource.owner)&&r.getChannel().equals(resource.getChannel()) &&r.uri.equals(resource.uri)) { resourcelist.remove(r); } } resourcelist.add(resource); message.put("response", "success"); } } else { // there are other commands rather than "publish", "remove", ... message.put("response", "error"); message.put("errorMessage", "invalid command"); } // there is no command } else { message.put("response", "error"); message.put("errorMessage", "missing or incorrect type for command"); } return message; } private static void serverClient(Socket client) { try(Socket clientSocket = client) { JSONParser parser = new JSONParser(); DataInputStream input = new DataInputStream(clientSocket.getInputStream()); DataOutputStream output = new DataOutputStream(clientSocket.getOutputStream()); System.out.println("Client: " + input.readUTF()); //output.writeUTF("Message received."); while(true) { if(input.available() > 0) { JSONObject command = (JSONObject)parser.parse(input.readUTF()); System.out.println(command); JSONObject message = parseCommand(command); JSONObject results = new JSONObject(); results.put("results", message); output.writeUTF(results.toJSONString()); } } } catch (IOException e) { e.printStackTrace(); } catch (org.json.simple.parser.ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
A new version with the SHARE command.

I have made some test and revision, the struction is better now, and you can just ignore the previous one, and just look at this as a reference.
It seems that ALL tests passed so far, and things all go well with the system.

Tell me if you find any problems or questions.

Be the first to comment

You can use [html][/html], [css][/css], [php][/php] and more to embed the code. Urls are automatically hyperlinked. Line breaks and paragraphs are automatically generated.