Advertisement
Guest User

Server

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