Lauda

java web

Apr 25th, 2014
163
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 7.71 KB | None | 0 0
  1. import java.io.BufferedReader;
  2. import java.io.BufferedWriter;
  3. import java.io.IOException;
  4. import java.io.InputStreamReader;
  5. import java.io.OutputStreamWriter;
  6. import java.io.PrintWriter;
  7. import java.net.InetAddress;
  8. import java.net.Socket;
  9. import java.net.UnknownHostException;
  10. import java.util.Scanner;
  11.  
  12. public class UserClient {
  13.     public static final int TCP_PORT = 80; // Le port
  14.  
  15.     public static void main(String[] args) {
  16.         // We get shit from command line...
  17.         if (args.length == 0) {
  18.             System.out.println("User Client v1.0");
  19.             System.out.println("Usage: UserClient <username> [<hostname>]");
  20.             System.out.println("Params:");
  21.             System.out.println("\t<username> Username to use for login.");
  22.             System.out.println("\t<hostname> Server name; default is localhost\n\n");
  23.             System.exit(0);
  24.         }
  25.         Scanner sc = new Scanner(System.in);
  26.        
  27.         String hostname = (args.length > 1) ? args[1] : "localhost";
  28.         try {
  29.             InetAddress addr = InetAddress.getByName(hostname);
  30.            
  31.             // Open le socket
  32.             Socket sock = new Socket(addr, TCP_PORT);
  33.            
  34.             // Initialize stuff
  35.             BufferedReader in = new BufferedReader(new InputStreamReader(sock.getInputStream()));
  36.            
  37.             PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(sock.getOutputStream())), true);
  38.            
  39.             // Send request
  40.             System.out.println("Logging in...");
  41.            
  42.             boolean temp = true;
  43.             do {
  44.                 String request = sc.nextLine(); // args[0];
  45.                 out.println(request);
  46.                 out.flush();
  47.                
  48.                 // Read response
  49.                 String response;
  50.                 String list = "";
  51.                
  52.                 while (!(response = in.readLine()).equals("END")) {
  53.                     list += response + "\n";
  54.                 }
  55.                
  56.             //  if (request.equals("LIST"))
  57.                     System.out.println("\nCurrent users:\n");
  58.                 System.out.println(list);
  59.                
  60.                 // Close connection
  61.                 if (list.contains("Closed")) {
  62.                     in.close();
  63.                     out.close();
  64.                     sock.close();
  65.                     temp = false;
  66.                 }
  67.             } while(temp);
  68.         } catch (UnknownHostException uhe) {
  69.             uhe.printStackTrace();
  70.         } catch (IOException ioe) {
  71.             ioe.printStackTrace();
  72.         }
  73.         }
  74.     }
  75.  
  76.  
  77. import java.net.ServerSocket;
  78. import java.net.Socket;
  79. import java.util.Vector;
  80.  
  81.  
  82. public class UserServer {
  83.  
  84.     public static final int TCP_PORT = 9000;
  85.    
  86.    
  87.     public static void main(String[] args) {
  88.         Vector users = new Vector();
  89.        
  90.         try {
  91.             ServerSocket ss = new ServerSocket(TCP_PORT);
  92.            
  93.             System.out.println("Server running...");
  94.            
  95.             while (true) {
  96.                 Socket sock = ss.accept();
  97.                 UserServerThread ust = new UserServerThread(sock, users);      
  98.             }
  99.         } catch (Exception ex) {
  100.             ex.printStackTrace();
  101.         }
  102.  
  103.     }
  104.  
  105. }
  106.  
  107.  
  108.  
  109. import java.io.BufferedReader;
  110. import java.io.BufferedWriter;
  111. import java.io.FileReader;
  112. import java.io.FileWriter;
  113. import java.io.IOException;
  114. import java.io.InputStreamReader;
  115. import java.io.OutputStreamWriter;
  116. import java.io.PrintWriter;
  117. import java.net.Socket;
  118. import java.util.StringTokenizer;
  119. import java.util.Vector;
  120.  
  121.  
  122. public class UserServerThread extends Thread {
  123.     private Socket sock;
  124.     private BufferedReader in;
  125.     private PrintWriter out;
  126.     private Vector records;
  127.     private BufferedReader br;
  128.     private BufferedWriter bw;
  129.    
  130.     public UserServerThread(Socket sock, Vector records) {
  131.         this.sock = sock;
  132.         this.records = records;
  133.        
  134.        
  135.         try {
  136.             // Initialize input stream
  137.             in = new BufferedReader(new InputStreamReader(sock.getInputStream()));
  138.            
  139.             // Initialize outout stream
  140.             out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(sock.getOutputStream())), true);
  141.            
  142.             // Start thread
  143.             start();
  144.         } catch (Exception ex) {
  145.             ex.printStackTrace();
  146.         }
  147.     }
  148.    
  149.     public void run() {
  150.         String response = "";
  151.        
  152.         try {
  153.         //  while (true) {
  154.                 // Read request
  155.                 String request = in.readLine();
  156.                 // System.out.println(request);
  157.                
  158.  
  159.                
  160.                 // Add to the list
  161.                   if (request.startsWith("GET")) {
  162.                       response = browserResponse();
  163.                     } else {
  164.                       // dodaj u listu
  165.                       response = clientResponse(request);
  166.                     }
  167.                
  168.                 // Send answer
  169.                 out.println(response);
  170.     //      }
  171.            
  172.             // Close connection
  173.             in.close();
  174.             out.close();
  175.             sock.close();
  176.            
  177.         } catch (Exception ex) {
  178.             ex.printStackTrace();
  179.         }
  180.     }
  181.    
  182.     private String clientResponse(String request) throws IOException {
  183.         br = new BufferedReader(new FileReader("knjige.txt"));
  184.        
  185.         if (request.startsWith("iznad_proseka")) {
  186.             int lineCount = 0;
  187.             int sum = 0;
  188.             int intPriceFromFile = 0;
  189.             Vector<Integer> price_records = new Vector<Integer>(10);
  190.             Vector<String> rec = new Vector<String>(10);
  191.             String s = "";
  192.             double avg = 0;
  193.            
  194.             while ((s = br.readLine()) != null) {
  195.                 lineCount++;
  196.                
  197.                 StringTokenizer fileLine = new StringTokenizer(s, "|");
  198.                 String id = fileLine.nextToken(); // ID
  199.                 String name = fileLine.nextToken(); // Name
  200.                 String auth = fileLine.nextToken(); // Auth
  201.                 String stringPriceFromFile = fileLine.nextToken(); // Price
  202.                
  203.                 intPriceFromFile = Integer.parseInt(stringPriceFromFile);
  204.                 String recForVector = id + "|" + name + "|" + auth + "|" + stringPriceFromFile;
  205.                 rec.add(recForVector);
  206.                 price_records.add(intPriceFromFile);
  207.                
  208.                 sum += intPriceFromFile;
  209.             }
  210.            
  211.             avg = (double)sum/lineCount;
  212.            
  213.             for (String k: rec) {
  214.                 StringTokenizer st = new StringTokenizer(k, "|");
  215.                 String id = st.nextToken(); // ID
  216.                 String name = st.nextToken(); // Name
  217.                 String auth = st.nextToken(); // Auth
  218.                 String stringPriceFromFile = st.nextToken(); // Price
  219.                
  220.                 int price = Integer.parseInt(stringPriceFromFile);
  221.                
  222.                 if (price > avg) {
  223.                     System.out.println(name);
  224.                 }
  225.             }
  226.                
  227.         }
  228.        
  229.         else if (request.startsWith("update")) {
  230.             String retVal = "";
  231.             StringTokenizer st = new StringTokenizer(request);
  232.             String command = st.nextToken(); // Command
  233.             String newReq = st.nextToken(); // The rest...
  234.             StringTokenizer newSt = new StringTokenizer(newReq, "|");
  235.            
  236.             String s = "";
  237.             String id = newSt.nextToken();
  238.             String name = newSt.nextToken();
  239.             String author = newSt.nextToken();
  240.             String price = newSt.nextToken();
  241.            
  242.             String updateRecord = id + "|" + name + "|" + author + "|" + price;
  243.             boolean idNotExist = true;
  244.            
  245.             records.clear();
  246.            
  247.             while ((s = br.readLine()) != null) {
  248.                 System.out.println(s + "\n");
  249.                
  250.                 StringTokenizer fileLine = new StringTokenizer(s, "|");
  251.                 String idFromFile = fileLine.nextToken();
  252.                
  253.                 if (id.equals(idFromFile)) {
  254.                     records.add(updateRecord);
  255.                     idNotExist = false;
  256.                 }
  257.                 else
  258.                     records.add(s);
  259.             }
  260.            
  261.             if (idNotExist) {
  262.                 return "ID does not exists! \nEND";
  263.             }
  264.             else
  265.                 return saveDat(records) ? "Successful updated!\nEND" : "Not successful updated\nEND";
  266.         }
  267.    
  268.     return "";
  269.     }
  270.    
  271.     private boolean saveDat(Vector records) {
  272.         try {
  273.             bw = new BufferedWriter(new FileWriter("knjige.txt"));
  274.            
  275.             for (int i = 0; i < records.size(); i++) {
  276.                 String us = (String)records.elementAt(i);
  277.                 System.out.println(records.size());
  278.                
  279.                 bw.write(us);
  280.                 bw.newLine();
  281.             }
  282.            
  283.             bw.close();
  284.             return true;
  285.         } catch (IOException ioe) {
  286.             ioe.printStackTrace();
  287.         }
  288.        
  289.         return false;
  290.     }
  291.    
  292.       /**
  293.        * Generisanje odgovora za web browser
  294.        */
  295.       private String browserResponse() {
  296.         String retVal = "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n";
  297.         retVal += "<html><head><title>Prijavljeni korisnici</title></head>\n";
  298.         retVal += "<body><h1>Prijavljeni korisnici</h1><ol>\n";
  299.         for (int i = 0; i < records.size(); i++) {
  300.           String user = (String)records.elementAt(i);
  301.           retVal += "<li>" + user + "</li>\n";
  302.         }
  303.         retVal += "</ol></body></html>\n";
  304.         return retVal;
  305.       }
  306.    
  307.    
  308. }
Advertisement
Add Comment
Please, Sign In to add comment