Advertisement
Guest User

Server

a guest
Jun 1st, 2016
66
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Scala 8.84 KB | None | 0 0
  1. import java.net._
  2. import java.io._
  3. import scala.io._
  4. import scala.util.control._
  5. import java.lang.String
  6. import collection.mutable.HashMap
  7.  
  8.  
  9. object ServerObject {
  10.   class Server(val _conn: Socket) extends Runnable {
  11.     val _connection = _conn
  12.     var root:String = System.getProperty("user.dir")
  13.     val in = new DataInputStream(_connection.getInputStream())
  14.     val out = new DataOutputStream(_connection.getOutputStream())
  15.     var currentClient = ""
  16.     var rootFolder = slashFix(root)
  17.     var currentDirectory = slashFix(pwd())
  18.  
  19.     def getListOfFiles(dir: String):List[File] = {
  20.       val d = new File(dir)
  21.       if (d.exists && d.isDirectory) {
  22.         d.listFiles.toList
  23.       } else {
  24.       List[File]()
  25.       }
  26.     }
  27.  
  28.  
  29.     def ls() : String = {
  30.         setDir(currentDirectory)
  31.         val Currdir = System.getProperty("user.dir")
  32.         val files = getListOfFiles(Currdir)
  33.         var dirs :String = "\n"
  34.         for ( i <- 0 to (files.length - 1)) {
  35.           dirs += '\t'+files(i).getName()
  36.         }
  37.         return dirs
  38.     }
  39.  
  40.     def cd() : Unit = {
  41.           out.writeUTF("Insert name of the directory that you want to navigate to: ")
  42.             out.flush()
  43.            var dir :String = in.readUTF()
  44.            setDir(currentDirectory)
  45.             println(dir)
  46.             val cd = new File(slashFix(root)+"/"+dir)
  47.             println(cd.exists)
  48.               if(cd.exists && cd.isDirectory)
  49.               {
  50.                 System.setProperty("user.dir", slashFix(root)+"/"+dir)
  51.                 println(System.getProperty("user.dir"))
  52.                 out.writeUTF("Current directory is: "+System.getProperty("user.dir"))
  53.                 out.flush()
  54.               }else{
  55.                 out.writeUTF("Directory does not exist")
  56.                 out.flush()
  57.               }
  58.     }
  59.  
  60.     def fileInputStream(fName:String,fLen:String):Unit={
  61.         val fos = new FileOutputStream(pwd+"/"+fName)
  62.         var bytes = new Array[Byte](1024)
  63.         var readBytes:Int = 0
  64.         var fSize:Int = Integer.parseInt(fLen)
  65.         println(fSize)
  66.         while(fSize > 0) {
  67.             if(fSize <= 1024){
  68.                 readBytes = in.read(bytes, 0, fSize)
  69.             } else{
  70.                 readBytes = in.read(bytes, 0, 1024)
  71.             }
  72.             fSize -= readBytes
  73.             fos.write(bytes, 0, readBytes)
  74.         }
  75.         fos.close()
  76.         out.writeUTF("Received successfully")
  77.         out.flush()
  78.     }
  79.     def put() : Unit = {
  80.     out.writeUTF("Input file path")
  81.     out.flush()
  82.     val fileName = in.readUTF()
  83.     val FileS = in.readUTF()
  84.     setDir(currentDirectory)
  85.     if(fileName != "File does not exist"){
  86.       fileInputStream(fileName,FileS)
  87.     }else {
  88.         out.writeUTF("File does not exist")
  89.         out.flush()
  90.     }
  91. }
  92.  
  93.     def mkdir() : Unit = {
  94.     out.writeUTF("Name of new directory: ")
  95.     out.flush()
  96.     val _dirName = in.readUTF()
  97.     setDir(currentDirectory)
  98.     val mkDir = new File(System.getProperty("user.dir") + "/" + _dirName)
  99.     val successful = mkDir.mkdir();
  100.     if(successful) {
  101.         out.writeUTF("Directory successfully created")
  102.     }else {
  103.         out.writeUTF("Unable to create directory")
  104.     }
  105.     out.flush()
  106.   }
  107.  
  108. def rm() : Unit = {
  109.     out.writeUTF("Name of file/directory to delete: ")
  110.     out.flush()
  111.     val delPath = in.readUTF()
  112.     setDir(currentDirectory)
  113.     val rm = new File(System.getProperty("user.dir") + "/" + delPath)
  114.     if(rm.exists) {
  115.         rm.delete()
  116.         out.writeUTF("Deleted successfully")
  117.     }else {
  118.         out.writeUTF("Unable to delete")
  119.     }
  120.     out.flush()
  121. }
  122.  
  123. def fileOutputStream(fLen:Int,requestedFile:String):Unit={
  124.         out.writeUTF(fLen.toString())
  125.         out.flush()
  126.         val fos = out
  127.         val reader = new FileInputStream(pwd()+"/"+requestedFile);
  128.         var bytes = new Array[Byte](1024);
  129.         var fSize:Int = fLen
  130.         var readBytes:Int = 0
  131.         while(fSize > 0) {
  132.             if(fSize <= 1024){
  133.                 readBytes = reader.read(bytes, 0, fSize)
  134.             } else{
  135.                 readBytes = reader.read(bytes, 0, 1024)
  136.             }
  137.             fSize -= readBytes
  138.             fos.write(bytes, 0, readBytes)
  139.         }
  140.         reader.close();
  141.         out.writeUTF("File sent successfully")
  142.         out.flush()
  143. }
  144.  
  145. def get() : Unit = {
  146.     out.writeUTF("File to download")
  147.     out.flush()
  148.     val request = in.readUTF()
  149.     val file = new File(pwd()+"/"+request)
  150.     if(file.exists){
  151.         fileOutputStream(file.length.intValue(),request)
  152.     }else{
  153.         out.writeUTF("File does not exists")
  154.         out.flush()
  155.     }
  156. }
  157.  
  158. def slashFix(root:String):String={
  159.   return root.replace('\\','/')
  160. }
  161. def pwd():String={
  162.   return System.getProperty("user.dir")
  163. }
  164. def setDir(path:String):Unit={
  165.   System.setProperty("user.dir", slashFix(path))
  166. }
  167. def userValidator(user: String, password: String) : Boolean = {
  168.     var usuarios = HashMap[String, String]()
  169.     val file = new File("users.txt")
  170.     var leido = ""
  171.     if (file.exists){
  172.         Source.fromFile("users.txt" ).foreach{case line =>
  173.             leido += line
  174.       }
  175.         var splitUsers: Array[java.lang.String] = leido.split(",").map(_.trim)
  176.         var isUser = 0;
  177.         var arrayTam = splitUsers.size
  178.         while(arrayTam > isUser){
  179.             usuarios(splitUsers(isUser)) = splitUsers(isUser+1)
  180.             isUser += 2
  181.         }
  182.     }
  183.    
  184.     if(usuarios contains user){
  185.         if(usuarios(user) == password){
  186.             println("successful login")
  187.             return true
  188.         }else{
  189.             println("Wrong Password")
  190.             return false
  191.         }
  192.     }else {
  193.       out.writeUTF("User not registered, create user? [Y/N]")
  194.       if(in.readUTF()=="Y"){
  195.         usuarios(user) = password
  196.         println("Successfully registered user, you are now logged in")
  197.         val mkDir = new File(System.getProperty("user.dir") + "/" + user)
  198.         mkDir.mkdir();
  199.         val writer = new PrintWriter(new File("users.txt" ))
  200.         var FileS = usuarios.size
  201.         var iteracion = 0;
  202.         usuarios.foreach{case(key, value) =>
  203.         writer.write(key)
  204.         writer.write(",")
  205.         writer.write(value)
  206.         if(iteracion != (FileS-1)){
  207.             writer.write(",")
  208.         }
  209.         iteracion += 1;
  210.     }
  211.     writer.close()
  212.         return true
  213.         }else{
  214.           return false
  215.         }
  216.     }
  217.     return false
  218. }
  219.  
  220. def printLogin():String={
  221.       var login:String = "\n"
  222.       login+="\t"+"*********************************"+"\n"
  223.       login+="\t"+"***-----------Login-----------***"+"\n"
  224.       login+="\t"+"*** Input you username:       ***"+"\n"
  225.       login+="\t"+"*********************************"
  226.       return login
  227. }
  228. def validateLogin():Unit={
  229.  
  230. }
  231.  
  232.     def logic() : Unit = {
  233.       var isActive:Boolean = true
  234.       while(isActive){
  235.       out.writeUTF(printLogin)
  236.       var userName:String= in.readUTF()
  237.       out.writeUTF("Input you password: ")
  238.       var password:String= in.readUTF()
  239.       if(userValidator(userName,password)){
  240.         out.writeUTF("Successful login")
  241.         System.setProperty("user.dir", slashFix(root)+"/"+userName)
  242.       while(true){
  243.          if(currentClient == ""){
  244.             currentClient = userName
  245.             if(currentClient != ""){
  246.                 rootFolder = pwd()
  247.                 currentDirectory = pwd()
  248.             }
  249.         }else{
  250.         val received = in.readUTF()
  251.         println("Message Received:" + received)
  252.         if(received == "pwd"){
  253.           setDir(currentDirectory)
  254.           out.writeUTF(pwd())
  255.           out.flush()
  256.         }else if (received == "ls"){
  257.           setDir(currentDirectory)
  258.           out.writeUTF(ls())
  259.           out.flush()
  260.         }else if(received == "cd"){
  261.           setDir(currentDirectory)
  262.           cd()
  263.         }else if(received == "get"){
  264.           setDir(currentDirectory)
  265.           get()
  266.           out.writeUTF("")
  267.         }else if(received == "put"){
  268.           setDir(currentDirectory)
  269.           put()
  270.         }else if(received == "rm"){
  271.           setDir(currentDirectory)
  272.             rm()
  273.         }else if(received == "mkdir"){
  274.           setDir(currentDirectory)
  275.             mkdir()
  276.         }else if(received == "exit"){
  277.           out.writeUTF(received)
  278.           out.flush
  279.           _connection.close()
  280.           isActive = false
  281.         }else{
  282.           out.writeUTF("Invalid command")
  283.           out.flush()
  284.         }
  285.       }
  286.       }
  287.       currentDirectory = pwd()
  288.       }else{
  289.         out.writeUTF("Invalid User/Password")
  290.         out.flush()
  291.       }
  292.     }
  293.     }
  294.     def run {
  295.       logic()
  296.     }
  297. }
  298.  
  299.   def main(args: Array[String]){
  300.     val socket = new ServerSocket(8000)
  301.     while (true) {
  302.         val sock = socket.accept()
  303.         println(sock.getRemoteSocketAddress())
  304.         new Thread(new Server(sock)).start
  305.     }
  306.   }
  307. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement