DS project_QUERY

The QUERY command is somewhat difficult and complicated. After finishing it, the Lines of Code come to 800! -------------------------------------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 = URI.create((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"); } // QUERY command if(cmd.hasOption("query")){ 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(","); } 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(cmd.hasOption("uri")) { resource.uri = new URI(cmd.getOptionValue("uri")); send.put("uri", resource.uri.toString()); } else { send.put("uri", "");// URI is not null!!!!!!!!!!!!! } // URI is not null!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! 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("ezserver", null); command.put("resourceTemplate", send); command.put("command", "QUERY"); command.put("relay", true); //relay field } 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()); JSONArray array = (JSONArray) result.get("results"); for (Object message: array) { System.out.println(message + "\n"); } } } } 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.Arrays; 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 JSONArray parseCommand(JSONObject command) { int result = 0; //Resource resource = new Resource(); JSONArray seq = new JSONArray(); 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"); resource.uri = URI.create(((String)receive.get("uri"))); 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"); } seq.add(message); } else if(command.get("command").equals("SHARE")) { // SHARE-------------------------------------------------------------------------- boolean shareerror = false; //receivedsecret = (String) command.get("secret"); receive = (JSONObject) command.get("resource"); resource.name = (String) receive.get("name"); resource.uri = URI.create(((String)receive.get("uri"))); 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()); // Sharing 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"); } seq.add(message); } else if(command.get("command").equals("QUERY")) { // QUERY-------------------------------------------------------------------------- //boolean shareerror = false; //receivedsecret = (String) command.get("secret"); boolean relay = (boolean) command.get("relay"); receive = (JSONObject) command.get("resourceTemplate"); resource.name = (String) receive.get("name"); resource.uri = URI.create(((String)receive.get("uri"))); 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); } if (!resource.uri.equals("")&&!resource.uri.isAbsolute()) { message.put("response", "error"); message.put("errorMessage", "invalid resourceTemplate"); } else if (resource.name.startsWith(" ") || resource.name.endsWith(" ") || resource.name.contains("\0")) { message.put("response", "error"); message.put("errorMessage", "invalid resourceTemplate"); } else if (resource.description.startsWith(" ") || resource.description.endsWith(" ") || resource.description.contains("\0")) { message.put("response", "error"); message.put("errorMessage", "invalid resourceTemplate"); } else if (resource.getChannel().startsWith(" ") || resource.getChannel().endsWith(" ") || resource.getChannel().contains("\0")) { message.put("response", "error"); message.put("errorMessage", "invalid resourceTemplate"); } else if (resource.owner.startsWith(" ") || resource.owner.endsWith(" ") || resource.owner.contains("\0") || resource.owner.equals("*")) { message.put("response", "error"); message.put("errorMessage", "invalid resourceTemplate"); } else if (command.get("relay") == null) { // if the relay field is not given message.put("response", "error"); message.put("errorMessage", "missing resourceTemplate"); } else { // check QUERY rules enforced by the server List<Resource> printlist = new ArrayList<Resource>(); boolean tagpresent = true; for (Resource c : resourcelist) { // The template channel equals (case sensitive) the // resource channel if (c.getChannel().equals(resource.getChannel())) { // Any tags present in the template also are present // in the candidate (case insensitive) if (resource.tags.length > 0 && Arrays.asList(c).containsAll(Arrays.asList(resource.tags))) { // If the template contains an owner that is not // "", then the candidate owner must equal it // (case sensitive) if (!resource.owner.equals("") && resource.owner.equals(c.owner)) { // If the template contains a URI then the // candidate URI matches (case sensitive) if (!resource.uri.toString().equals("") && resource.uri.equals(c.uri)) { if ((!resource.name.equals("") && c.name.contains(resource.name)) || (!resource.description.equals("") && c.name.contains(resource.name)) || (resource.description.equals("")) && (resource.name.equals(""))) { printlist.add(c); } } } } // if owner is "" if (resource.owner.equals("")) { // Any tags present in the template also are // present // in the candidate (case insensitive) if (resource.tags.length > 0 && Arrays.asList(c).containsAll(Arrays.asList(resource.tags))) { // If the template contains a URI then the // candidate URI matches (case sensitive) if (!resource.uri.toString().equals("") && resource.uri.equals(c.uri)) { if ((!resource.name.equals("") && c.name.contains(resource.name)) || (!resource.description.equals("") && c.name.contains(resource.name)) || (resource.description.equals("")) && (resource.name.equals(""))) { printlist.add(c); } } } } // if tags is [] if (resource.tags.length == 0) { // If the template contains an owner that is not // "", then the candidate owner must equal it // (case sensitive) if (!resource.owner.equals("") && resource.owner.equals(c.owner)) { // If the template contains a URI then the // candidate URI matches (case sensitive) if (!resource.uri.toString().equals("") && resource.uri.equals(c.uri)) { if ((!resource.name.equals("") && c.name.contains(resource.name)) || (!resource.description.equals("") && c.name.contains(resource.name)) || (resource.description.equals("")) && (resource.name.equals(""))) { printlist.add(c); } } } } // if URI is "" if (resource.uri.toString().equals("")) { if (resource.tags.length > 0 && Arrays.asList(c).containsAll(Arrays.asList(resource.tags))) { // If the template contains an owner that is // not // "", then the candidate owner must equal // it // (case sensitive) if (!resource.owner.equals("") && resource.owner.equals(c.owner)) { if ((!resource.name.equals("") && c.name.contains(resource.name)) || (!resource.description.equals("") && c.name.contains(resource.name)) || (resource.description.equals("")) && (resource.name.equals(""))) { printlist.add(c); } } } } // if owner is "" and tag is [] if (resource.owner.equals("") && resource.tags.length == 0) { // If the template contains a URI then the // candidate URI matches (case sensitive) if (!resource.uri.toString().equals("") && resource.uri.equals(c.uri)) { if ((!resource.name.equals("") && c.name.contains(resource.name)) || (!resource.description.equals("") && c.name.contains(resource.name)) || (resource.description.equals("")) && (resource.name.equals(""))) { printlist.add(c); } } } // if owner is "" and URI is "" if (resource.owner.equals("") && resource.uri.toString().equals("")) { // Any tags present in the template also are // present // in the candidate (case insensitive) if (resource.tags.length > 0 && Arrays.asList(c).containsAll(Arrays.asList(resource.tags))) { if ((!resource.name.equals("") && c.name.contains(resource.name)) || (!resource.description.equals("") && c.name.contains(resource.name)) || (resource.description.equals("")) && (resource.name.equals(""))) { printlist.add(c); } } } // if tag is [] and URI is "" if (resource.uri.toString().equals("") && resource.tags.length == 0) { // If the template contains an owner that is not // "", then the candidate owner must equal it // (case sensitive) if (!resource.owner.equals("") && resource.owner.equals(c.owner)) { if ((!resource.name.equals("") && c.name.contains(resource.name)) || (!resource.description.equals("") && c.name.contains(resource.name)) || (resource.description.equals("")) && (resource.name.equals(""))) { printlist.add(c); } } } // if owner is "" and tag is [] and URI is "" if (resource.owner.equals("") && resource.uri.toString().equals("") && resource.tags.length == 0) { if ((!resource.name.equals("") && c.name.contains(resource.name)) || (!resource.description.equals("") && c.name.contains(resource.name)) || (resource.description.equals("")) && (resource.name.equals(""))) { printlist.add(c); } } } } // resourcelist.add(resource); message.put("response", "success"); JSONObject size = new JSONObject(); for(Resource r: printlist) { JSONObject o = new JSONObject(); o.put("name", r.name); o.put("description", r.description); o.put("channel",r.getChannel()); o.put("uri", r.uri.toString()); if(!r.owner.equals("")) o.put("owner", "*");//The server will never reveal the owner of a resource in a response. If a resource has an owner then it will be //replaced with the "*" character else o.put("owner",""); o.put("ezserver", r.ezserver); JSONArray arr = new JSONArray(); for(String tag: r.tags) { arr.add(tag); } o.put("tags", arr); seq.add(o); } size.put("resultSize", printlist.size()); seq.add(size); } seq.add(message); } 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 seq; } 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); JSONArray 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(); } } }

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.