Advertisement
Guest User

Untitled

a guest
Mar 24th, 2018
95
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 27.59 KB | None | 0 0
  1. import java.io.BufferedReader;
  2. import java.io.BufferedWriter;
  3. import java.io.File;
  4. import java.io.FileNotFoundException;
  5. import java.io.FileReader;
  6. import java.io.FileWriter;
  7. import java.io.IOException;
  8. import java.io.ObjectInputStream;
  9. import java.io.ObjectOutputStream;
  10. import java.net.ServerSocket;
  11. import java.net.Socket;
  12. import java.text.DateFormat;
  13. import java.text.SimpleDateFormat;
  14. import java.util.ArrayList;
  15. import java.util.Date;
  16. import java.util.List;
  17. import java.util.Scanner;
  18. import java.util.concurrent.Semaphore;
  19.  
  20. public class PhotoShareServer {
  21.  
  22. private static final String PASTAPROG = System.getProperty("user.dir");
  23. private static final String SEPARADOR = File.separator;
  24. private static final String CREDFILE = PASTAPROG + SEPARADOR + "credenciais.txt";
  25. private static final String USERFOLDER = PASTAPROG + SEPARADOR + "users" + SEPARADOR;
  26. private static final String FOTOFOLDER = SEPARADOR + "fotos" + SEPARADOR;
  27. private static final String FICHEIRONOMEFOTOS = SEPARADOR + "fotos.txt";
  28. private static final String FICHEIROFOLLOWERS = SEPARADOR + "followers.txt";
  29. private static final String ERRO = "ERRO";
  30. private static List<String> onlineUsers = new ArrayList<>();
  31. private static Semaphore mutexUsers = new Semaphore(1, true);
  32.  
  33. /**
  34. * Servidor PhotoShare
  35. *
  36. * @author Grupo 37 Pedro Gaspar 46411, Ricardo Santos 47078, Ana Sofia Godinho
  37. * 48359
  38. *
  39. */
  40. public static void main(String[] args) {
  41. File file = new File(CREDFILE);
  42. File pasta = new File(USERFOLDER);
  43. // Verificar existencia do ficheiro de credenciais e pasta dos utilizadores
  44. // se nao existir cria.
  45. if (!file.exists()) {
  46. try {
  47. file.createNewFile();
  48. } catch (IOException e) {
  49. System.err.println("Nao conseguiu criar o ficheiro das credenciais");
  50. System.exit(-1);
  51. }
  52. }
  53. if (!pasta.exists()) {
  54. pasta.mkdirs();
  55. }
  56. System.out.println("servidor: main");
  57. PhotoShareServer server = new PhotoShareServer();
  58. server.startServer();
  59. }
  60.  
  61. /**
  62. * Ativa Servidor. Estabelece um socket no porto 23232 e fica em modo listen ah
  63. * espera de um cliente que se tente ligar a ele. Serve os pedidos do cliente,
  64. * tratando da comunicacao com o mesmo.
  65. *
  66. */
  67. private void startServer() {
  68. ServerSocket sSoc = null;
  69.  
  70. try {
  71. sSoc = new ServerSocket(23232);
  72. while (true) {
  73. Socket inSoc = sSoc.accept();
  74. ServerThread newServerThread = new ServerThread(inSoc);
  75. newServerThread.start();
  76. }
  77. } catch (IOException e) {
  78. System.err.println("O servidor nao se conseguiu ligar");
  79. }
  80. }
  81.  
  82. // Threads utilizadas para comunicacao com os clientes
  83. class ServerThread extends Thread {
  84.  
  85. private Socket socket = null;
  86.  
  87. ServerThread(Socket inSoc) {
  88. socket = inSoc;
  89. System.out.println("Entrou um cliente");
  90. }
  91.  
  92. /**
  93. * Autentica o utilizador
  94. *
  95. * @param username
  96. * @param password
  97. * @return 0 se a combinacao esta no ficheiro, 1 se criou um user novo , -1 se a
  98. * combinacao estiver incorreta, -4 em caso de erro de criacao de ficheiros/pastas
  99. * @throws IOException
  100. */
  101. private int autenticacao(String username, String password) throws IOException {
  102.  
  103. Scanner sc = null;
  104. String line;
  105. File file = new File(CREDFILE);
  106. int result = 0;
  107.  
  108. if (!userExists(username)) {
  109. if (!new File(USERFOLDER + username + SEPARADOR).mkdirs()
  110. || !new File(USERFOLDER + username + FICHEIROFOLLOWERS).createNewFile()
  111. || !new File(USERFOLDER + username + FICHEIRONOMEFOTOS).createNewFile()
  112. || !new File(USERFOLDER + username + FOTOFOLDER).mkdirs()) {
  113. return -4;
  114. }
  115. BufferedWriter bw = null;
  116. // cria utilizador no ficheiro das credenciais
  117. bw = new BufferedWriter(new FileWriter(file, true));
  118. bw.write(username + ":" + password);
  119. bw.newLine();
  120. bw.close();
  121. result = 1;
  122. } else {
  123. // procura creds no ficheiro
  124. sc = new Scanner(file);
  125. boolean found = false;
  126. while (sc.hasNextLine() && !found) {
  127. line = sc.nextLine();
  128. String lineSplit[] = line.split(":");
  129. if (lineSplit[0].equals(username)) {
  130. if (lineSplit[1].equals(password)) {
  131. // autenticado
  132. result = 0;
  133.  
  134. try {
  135. mutexUsers.acquire();
  136. } catch (InterruptedException e) {
  137. System.exit(-1);
  138. }
  139. if (onlineUsers.contains(username)) {
  140. result = 2;
  141. }
  142. mutexUsers.release();
  143. } else {
  144. result = -1;
  145. // password errada
  146. }
  147. found = true;
  148. }
  149. }
  150. }
  151. return result;
  152. }
  153.  
  154. public void run() {
  155. ObjectOutputStream outStream = null;
  156. ObjectInputStream inStream = null;
  157. try {
  158. outStream = new ObjectOutputStream(socket.getOutputStream());
  159. inStream = new ObjectInputStream(socket.getInputStream());
  160.  
  161. } catch (IOException e) {
  162. System.err.println("ERRO: Procura de streams do cliente");
  163. return;
  164. }
  165. int res = -1, tentativas = 3;
  166. String username;
  167. try {
  168. do {
  169. username = (String) inStream.readObject();
  170. String pass = (String) inStream.readObject();
  171. outStream.writeObject((res = autenticacao(username, pass)));
  172. tentativas--;
  173. } while ((res < 0) && (tentativas > 0));
  174.  
  175. if (tentativas == 0) {
  176. clientExit("ERRO: Utilizador esgotou as suas tentetivas de autenticacao", outStream);
  177. return;
  178. }
  179. try {
  180. mutexUsers.acquire();
  181. } catch (InterruptedException e) {
  182. System.exit(-1);
  183. }
  184. if (onlineUsers.contains(username)) {
  185. clientExit("ERRO(Autenticacao): Tentativa de autenticacao em duas maquinas: " + username,
  186. outStream);
  187. }
  188. mutexUsers.release();
  189. } catch (IOException | ClassNotFoundException e) {
  190. clientExit("ERRO(Autenticacao): Escrita/Leitura", outStream);
  191. return;
  192. }
  193. System.out.println("Cliente autenticado: " + username);
  194. try {
  195. mutexUsers.acquire();
  196. } catch (InterruptedException e) {
  197. System.exit(-1);
  198. }
  199. onlineUsers.add(username);
  200. mutexUsers.release();
  201. String comando;
  202.  
  203. try {
  204. while (!(comando = (String) inStream.readObject()).equals("-q")) {
  205. int valid = validCommand(comando, username);
  206. String[] split = comando.split(" ");
  207.  
  208. switch (split[0]) {
  209. // adiciona/copia estas fotos para o servidor. Caso este utilizador j� tenha
  210. // alguma foto com o mesmo nome no servidor, o cliente deve retornar um erro.
  211. case "-a":
  212. DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
  213. Date date = new Date();
  214. String dataEscrita = dateFormat.format(date);
  215.  
  216. List<Integer> repetidos = new ArrayList<>();
  217.  
  218. // Verifica as fotos repetidas
  219. for (int i = 1; i < split.length; i++) {
  220. File ficheiroTexto = new File(USERFOLDER + username + FOTOFOLDER + split[i] + ".txt");
  221. if (ficheiroTexto.exists()) {
  222. repetidos.add(i-1);
  223. }
  224. }
  225. outStream.writeObject(repetidos);
  226.  
  227. int i = 0;
  228. // Recebe os ficheiros nao repetidos
  229. while (++i < split.length) {
  230. if (!repetidos.contains(i + 1)) {
  231. String caminho = USERFOLDER + username + FOTOFOLDER + split[i];
  232. File ficheiroTexto = new File(USERFOLDER + username + FOTOFOLDER + split[i] + ".txt");
  233. ficheiroTexto.createNewFile();
  234. BufferedWriter fw = new BufferedWriter(new FileWriter(ficheiroTexto));
  235. fw.write("0 0 " + dataEscrita);
  236. fw.newLine();
  237. fw.close();
  238. File ficheiroFotosUser = new File(USERFOLDER + username + FICHEIRONOMEFOTOS);
  239. fw = new BufferedWriter(new FileWriter(ficheiroFotosUser, true));
  240. fw.write(split[i]);
  241. fw.newLine();
  242. fw.close();
  243. // mensagens de problemas de transmissao ja sao tratados do lado do cliente
  244. Ferramentas.receiveFile(inStream, outStream, caminho);
  245. }
  246. }
  247. break;
  248. case "-l":
  249. if (valid < 0) {
  250. outStream.writeObject(valid);
  251. } else {
  252. List<String> photos = listPhotosByUser(split[1]);
  253. if (photos == null) {
  254. outStream.writeObject(-4);
  255. } else {
  256. outStream.writeObject(valid);
  257. outStream.writeObject(photos);
  258. }
  259. }
  260. break;
  261. case "-i":
  262. if (valid < 0) {
  263. outStream.writeObject(valid);
  264. } else {
  265. List<String> descricao = photoDescription(split[1], split[2]);
  266. if (descricao == null) {
  267. outStream.writeObject(-4);
  268. } else {
  269. outStream.writeObject(valid);
  270. outStream.writeObject(descricao);
  271. }
  272. }
  273. break;
  274. case "-g":
  275. outStream.writeObject(valid);
  276. if (valid >= 0) {
  277. File[] fotos = (File[]) inStream.readObject();
  278. int valor = getPictures(split[1], fotos, inStream, outStream);
  279. if (valor == -100) {
  280. clientExit("ERRO: Envio de fotos ao utilizador " + username, outStream);
  281. try {
  282. mutexUsers.acquire();
  283. } catch (InterruptedException e) {
  284. System.exit(-1);
  285. }
  286. onlineUsers.remove(username);
  287. mutexUsers.release();
  288. return;
  289. }
  290. }
  291. break;
  292. case "-c":
  293. String comment = (String) inStream.readObject();
  294. if (valid < 0) {
  295. outStream.writeObject(valid);
  296. } else {
  297. outStream.writeObject(addComment(split[1], split[2], comment));
  298. }
  299. break;
  300. case "-L":
  301. if (valid < 0) {
  302. outStream.writeObject(valid);
  303. } else {
  304. outStream.writeObject(likePhoto(split[1], split[2], true));
  305. }
  306. break;
  307. case "-D":
  308. if (valid < 0) {
  309. outStream.writeObject(valid);
  310. } else {
  311. outStream.writeObject(likePhoto(split[1], split[2], false));
  312. }
  313. break;
  314. case "-f":
  315. outStream.writeObject(valid);
  316. if (valid >= 0) {
  317. ArrayList<String> nomes = new ArrayList<>();
  318. for (int f = 1; f < split.length; f++) {
  319. nomes.add(split[f]);
  320. }
  321. outStream.writeObject(followUser(nomes, username));
  322. }
  323. break;
  324. case "-r":
  325. outStream.writeObject(valid);
  326. if (valid >= 0) {
  327. List<String> erros = new ArrayList<>();
  328. for (i = 1; i < split.length; i++) {
  329. if (!userExists(split[i])) {
  330. erros.add("-1 " + split[i]);
  331. } else if (!verifyFollower(split[i], username)) {
  332. erros.add("-2 " + split[i]);
  333. } else if (removeFollower(username, split[i]) == -4) {
  334. erros.add("-4 " + split[i]);
  335. } else {
  336. erros.add("0 " + split[i]);
  337. }
  338. }
  339.  
  340. outStream.writeObject(erros);
  341. }
  342. break;
  343. default:
  344. System.out.println("Comando errado");
  345. }
  346. }
  347. } catch (ClassNotFoundException | IOException e) {
  348. clientExit("ERRO: Escrita/Leitura no cliente: " + username, outStream);
  349. try {
  350. mutexUsers.acquire();
  351. } catch (InterruptedException e1) {
  352. System.exit(-1);
  353. }
  354. onlineUsers.remove(username);
  355. mutexUsers.release();
  356. return;
  357. }
  358. System.out.println("Cliente Saiu: " + username);
  359. try {
  360. mutexUsers.acquire();
  361. } catch (InterruptedException e) {
  362. System.exit(-1);
  363. }
  364. onlineUsers.remove(username);
  365. mutexUsers.release();
  366. try {
  367. outStream.close();
  368. } catch (IOException e) {
  369. return;
  370. }
  371. }
  372.  
  373. /**
  374. * Metodo para ver se um dado utilizador tem fotos
  375. *
  376. * @param username
  377. * utilizador a verificar
  378. * @return true se o utilizador tiver fotos
  379. */
  380. private boolean hasPhotos(String username) {
  381. List<String> photos = listPhotosByUser(username);
  382. if (photos == null || photos.size() == 0)
  383. return false;
  384. return true;
  385. }
  386.  
  387. /**
  388. * Lista fotos por utilizador
  389. *
  390. * Metodo que concretiza a flag '-l'
  391. *
  392. * @param user
  393. * nome do utilizador de quem as fotos vao ser listadas
  394. * @return lista de strings contendo o nome e data de publicacao das fotos pertencentes a user
  395. */
  396. private List<String> listPhotosByUser(String user) {
  397.  
  398. BufferedReader br;
  399. ArrayList<String> resultado = null;
  400. BufferedReader readerFoto = null;
  401. try {
  402. br = new BufferedReader(new FileReader(USERFOLDER + user + FICHEIRONOMEFOTOS));
  403.  
  404. String fotoAtual = null;
  405. resultado = new ArrayList<>();
  406. // Para cada foto
  407. while ((fotoAtual = br.readLine()) != null) {
  408. // busca a data
  409. try {
  410. readerFoto = new BufferedReader(
  411. new FileReader(USERFOLDER + user + FOTOFOLDER + fotoAtual + ".txt"));
  412. } catch (FileNotFoundException e) {
  413. System.err.println("Ficheiro de dados da foto: " + fotoAtual + " do utilizador " + user
  414. + " nao encontrado");
  415. continue;
  416. }
  417. String dataFoto;
  418.  
  419. dataFoto = readerFoto.readLine().split(" ")[2];
  420.  
  421. resultado.add(fotoAtual + " " + dataFoto);
  422. readerFoto.close();
  423. }
  424.  
  425. br.close();
  426. } catch (IOException e) {
  427. return null;
  428. }
  429.  
  430. return resultado;
  431.  
  432. }
  433.  
  434. /**
  435. * Gosta de foto
  436. *
  437. * Metodo que concretiza as flag '-L' || '-D'
  438. *
  439. * @param user
  440. * nome do utilizador de quem as fotos vao ser alvo de reacao
  441. * @param photo
  442. * foto alvo dos likes ou dislikes
  443. * @param likeordislike
  444. * true - acrescenta um like || false - acrescenta um dislike
  445. * @return 0 - se a tudo foi bem sucedido || -3 - ERRO: a foto nao existe || -4
  446. * - ERRO: erro de input/output
  447. */
  448. private int likePhoto(String user, String photo, boolean likeordislike) {
  449. try {
  450. if (photoExists(user, photo)) {
  451. BufferedReader br = new BufferedReader(
  452. new FileReader(USERFOLDER + user + FOTOFOLDER + photo + ".txt"));
  453. String line = br.readLine();
  454. br.close();
  455. String[] split = line.split(" ");
  456. if (likeordislike) {
  457. int actualLikes = Integer.parseInt(split[0]);
  458. actualLikes++;
  459. split[0] = actualLikes + "";
  460. } else {
  461. int actualLikes = Integer.parseInt(split[1]);
  462. actualLikes++;
  463. split[1] = actualLikes + "";
  464. }
  465. String res = split[0] + " " + split[1] + " " + split[2];
  466. return reEscreveInfo(res, USERFOLDER + user + FOTOFOLDER + photo + ".txt");
  467. } else
  468. return -3;
  469. } catch (IOException e) {
  470. return -4;
  471. }
  472. }
  473.  
  474. /**
  475. * Reescreve os dados da foto
  476. *
  477. * Altera dados do ficheiro da foto
  478. *
  479. * @param res
  480. * primeira linha do ficheiro da foto
  481. * @param caminho
  482. * localizacao no sistema de ficheiros do ficheiro da foto
  483. * @return -100 - ficheiro nao encontrado || -4 - erro de input/output || 0 -
  484. * bem sucedido
  485. */
  486. private int reEscreveInfo(String res, String caminho) {
  487. File fich = new File(caminho);
  488. List<String> tempList = new ArrayList<>();
  489. BufferedWriter writer = null;
  490. BufferedReader reader;
  491. try {
  492. reader = new BufferedReader(new FileReader(fich));
  493.  
  494. String currentLine;
  495. // Primeira linha nao interessa (dados que vao ser alterados)
  496. try {
  497. reader.readLine();
  498. tempList.add(res);
  499. while ((currentLine = reader.readLine()) != null) {
  500. tempList.add(currentLine.trim());
  501. }
  502. reader.close();
  503. writer = new BufferedWriter(new FileWriter(fich));
  504. for (String line : tempList) {
  505. writer.write(line);
  506. writer.newLine();
  507. }
  508. } catch (FileNotFoundException e) {
  509. System.err.println("O sistema nao conseguiu encontrar o ficheiro para reescrever.");
  510. return -100;
  511. }
  512.  
  513. writer.close();
  514. } catch (IOException e) {
  515. return -4;
  516. }
  517. return 0;
  518. }
  519.  
  520. /**
  521. * Adiciona os utilizadores followUserIds como seguidores do utilizador local.
  522. *
  523. * @param users
  524. * nomes dos utilizadores a serem adicionados
  525. * @param localUser
  526. * nome do utilizador autenticado
  527. * @return lista de listas com utilizadores adicionados como seguidores, com
  528. * utilizadores inexistentes e com utilizadores que jah estao a seguir o
  529. * localUser
  530. */
  531.  
  532. private ArrayList<ArrayList<String>> followUser(ArrayList<String> users, String localUser) {
  533. ArrayList<ArrayList<String>> lis_res;
  534. try {
  535. lis_res = new ArrayList<>();
  536. ArrayList<String> errosF = new ArrayList<>(); // indice 1
  537. ArrayList<String> errosE = new ArrayList<>(); // indice 2
  538. ArrayList<String> addUsers = new ArrayList<>(); // indice 0
  539. BufferedWriter bw = new BufferedWriter(
  540. new FileWriter(USERFOLDER + localUser + FICHEIROFOLLOWERS, true));
  541. for (int i = 0; i < users.size(); i++) {
  542. if (userExists(users.get(i))) {
  543. if (!verifyFollower(users.get(i), localUser)) {
  544. bw.write(users.get(i));
  545. bw.newLine();
  546. addUsers.add(users.get(i));
  547. } else {
  548. errosF.add(users.get(i));
  549. }
  550. } else {
  551. errosE.add(users.get(i));
  552. }
  553. }
  554. lis_res.add(addUsers);
  555. lis_res.add(errosF);
  556. lis_res.add(errosE);
  557. bw.close();
  558. } catch (IOException e) {
  559. return null;
  560. }
  561. return lis_res;
  562. }
  563.  
  564. /**
  565. * Verifica se o utilizador dado existe
  566. *
  567. * @param user
  568. * nome do utilizador a ser verificado
  569. * @return true se o user existe no sistema.
  570. */
  571. private boolean userExists(String user) {
  572. return new File(USERFOLDER + user).exists();
  573. }
  574.  
  575. /**
  576. * Verifica se dada foto existe
  577. *
  578. * @param user
  579. * nome do utilizador a quem a foto pertence
  580. * @param photo
  581. * nome da foto a ser verificada
  582. * @return true - se foto existe || false - c.c.
  583. */
  584. private boolean photoExists(String user, String photo) {
  585. return new File(USERFOLDER + user + FOTOFOLDER + photo).exists();
  586. }
  587.  
  588. /**
  589. * Verifica se um dado utilizador segue outro utilizador
  590. *
  591. * @param userFollower
  592. * nome do utilizador que segue
  593. * @param userFollowed
  594. * nome do utilizador que eh seguido
  595. * @return true - se userFollower segue userFollowed || false - c.c.
  596. */
  597. private boolean verifyFollower(String userFollower, String userFollowed) throws IOException {
  598. boolean found = false;
  599. if (userFollower.equals(userFollowed))
  600. return true;
  601. File fichFollow = new File(USERFOLDER + userFollowed + FICHEIROFOLLOWERS);
  602. BufferedReader br = new BufferedReader(new FileReader(fichFollow));
  603. String currLine = null;
  604. while ((currLine = br.readLine()) != null && !found) {
  605. found = currLine.equals(userFollower);
  606. }
  607. br.close();
  608. return found;
  609. }
  610.  
  611. /**
  612. * Metodo que concretiza flag '-g'
  613. *
  614. * @param username
  615. * nome do utilizador cujas fotos vao ser descarregadas
  616. * @param fotos
  617. * fotos do utilizador que vao ser descarregadas
  618. * @param in
  619. * fluxo de comunicacao para rececao de informacao do cliente
  620. * @param out
  621. * fluxo de comunicacao para transmissao de informacao ao cliente
  622. * @return -4 - ficheiro de fotos nao encontrado || 0 - acao bem sucedida
  623. */
  624. private int getPictures(String username, File[] fotos, ObjectInputStream in, ObjectOutputStream out) {
  625. File pathUsername = new File(USERFOLDER + username + FOTOFOLDER);
  626. List<String> fotosAtuais = listPhotosByUser(username);
  627.  
  628. if (fotosAtuais == null) {
  629. return -100;
  630. }
  631. try {
  632. // fotos ja existentes
  633. if (fotos != null) {
  634. for (File f : fotos) {
  635. String nomeF = f.getName();
  636. fotosAtuais.remove(nomeF);
  637. List<String> comments;
  638. comments = getComments(username, nomeF);
  639. if (comments.size() != 0 && comments.get(0).equals(ERRO)) {
  640. return -100;
  641. }
  642. out.writeObject(comments);
  643.  
  644. }
  645. }
  646. // fotos nao existentes
  647.  
  648. out.writeObject(fotosAtuais);
  649. for (String ficheiro : fotosAtuais) {
  650. ficheiro = ficheiro.split(" ")[0];
  651. String txt = ficheiro + ".txt";
  652. String pathUserfoto = pathUsername.getAbsolutePath() + SEPARADOR + ficheiro;
  653. Ferramentas.sendFile(out, in, pathUserfoto);
  654. List<String> comments = getComments(username, txt);
  655. out.writeObject(comments);
  656. }
  657. } catch (IOException e) {
  658. return -100;
  659. }
  660. return 0;
  661. }
  662.  
  663. /**
  664. * Metodo que concretiza a flag '-r'
  665. *
  666. * @param username
  667. * nome do utilizador de quem vao ser removidos seguidores
  668. * @param follower
  669. * nome do seguidor a ser removido
  670. * @return -4 - erro de Input/Output || -1 - ficheiro de seguidores nao encontrado || 0 - acao bem
  671. * sucedida
  672. */
  673. private int removeFollower(String username, String follower) {
  674. File caminhoFollowers = new File(USERFOLDER + username + FICHEIROFOLLOWERS);
  675. List<String> temp = new ArrayList<>();
  676.  
  677. BufferedReader reader = null;
  678. BufferedWriter writer = null;
  679. try {
  680. reader = new BufferedReader(new FileReader(caminhoFollowers));
  681. } catch (FileNotFoundException e) {
  682. System.err.println("Ficheiro de seguidores nao encontrado");
  683. return -100;
  684. }
  685. String currentLine;
  686.  
  687. try {
  688. while ((currentLine = reader.readLine()) != null) {
  689. String trimmedLine = currentLine.trim();
  690. if (!trimmedLine.equals(follower)) {
  691. temp.add(currentLine);
  692. }
  693. }
  694.  
  695. reader.close();
  696. writer = new BufferedWriter(new FileWriter(caminhoFollowers));
  697. for (String line : temp) {
  698. writer.write(line);
  699. writer.newLine();
  700. }
  701. writer.close();
  702. } catch (IOException e) {
  703. return -4;
  704. }
  705.  
  706. return 0;
  707. }
  708.  
  709. /**
  710. * Metodo que concretiza a flag '-i'
  711. *
  712. * @param username
  713. * nome do utilizador a quem a foto pertence
  714. * @param foto
  715. * foto da qual a descricao vai ser dada
  716. * @return lista com a caracteristicas de foto pertencente a username
  717. */
  718.  
  719. private List<String> photoDescription(String username, String foto) {
  720. List<String> result = new ArrayList<String>();
  721. File pathFoto = new File(USERFOLDER + username + FOTOFOLDER + foto + ".txt");
  722. BufferedReader br = null;
  723. try {
  724. br = new BufferedReader(new FileReader(pathFoto));
  725. // likes, dislikes, data
  726. String[] dados;
  727.  
  728. dados = br.readLine().split(" ");
  729.  
  730. result.add("Likes: " + dados[0]);
  731. result.add("Dislikes: " + dados[1]);
  732. result.add("Data de publicacao: " + dados[2]);
  733. String linha;
  734. int i = 1;
  735.  
  736. while ((linha = br.readLine()) != null) {
  737. result.add("[" + i++ + "]: " + linha);
  738. }
  739. br.close();
  740. } catch (IOException e) {
  741. return null;
  742. }
  743. return result;
  744. }
  745.  
  746. /**
  747. * Imprime uma mensagem de erro, denota a saida de um cliente e fecha a socket de comunicacao
  748. * @param msgErr - mensagem de erro
  749. * @param out - canal de comunicacao
  750. */
  751. private void clientExit(String msgErr, ObjectOutputStream out) {
  752. System.err.println(msgErr);
  753. System.out.println("Saiu um cliente");
  754.  
  755. try {
  756. out.close();
  757. } catch (IOException e) {
  758. return;
  759. }
  760. }
  761.  
  762. /**
  763. * Metodo que concretiza a flag '-c'
  764. *
  765. * @param username
  766. * nome do utilizador cuja foto vai ser comentada
  767. * @param foto
  768. * foto a ser comentada
  769. * @param comentario
  770. * comentario a acrescentar a foto
  771. * @return -4 - foto nao encontrada || 0 - acao bem sucedida
  772. */
  773. private int addComment(String username, String foto, String comentario) {
  774. File pathFoto = new File(USERFOLDER + username + FOTOFOLDER + foto + ".txt");
  775. BufferedWriter bw;
  776. try {
  777. bw = new BufferedWriter(new FileWriter(pathFoto, true));
  778. bw.write(comentario);
  779. bw.newLine();
  780. bw.close();
  781. } catch (IOException e) {
  782. return -4;
  783. }
  784. return 0;
  785. }
  786.  
  787. /**
  788. * Devolve comentarios de uma dada foto
  789. *
  790. * @param username
  791. * nome do utilizador a quem a foto pertence
  792. * @param nomeFoto
  793. * nome da foto cujos comentarios vao ser devolvidos
  794. * @return lista de comentarios da foto dada pertencente a username
  795. */
  796. private List<String> getComments(String username, String nomeFoto) {
  797. List<String> result = new ArrayList<>();
  798. File ficheiroPath = new File(USERFOLDER + username + FOTOFOLDER + nomeFoto);
  799. BufferedReader br = null;
  800. try {
  801. br = new BufferedReader(new FileReader(ficheiroPath));
  802. } catch (FileNotFoundException e) {
  803. System.err.println("Ficheiro de fotos nao encontrado");
  804. result.add(ERRO);
  805. return result;
  806. }
  807. try {
  808. br.readLine();
  809.  
  810. String linha;
  811. while ((linha = br.readLine()) != null) {
  812. result.add(linha);
  813. }
  814. br.close();
  815. } catch (IOException e) {
  816. return null;
  817. }
  818. return result;
  819. }
  820.  
  821. /**
  822. * Metodo que valida o numero de argumentos introduzidos para cada comando e
  823. * verifica todas as possibilidades de erro antes da execucao do comando
  824. *
  825. * @param command
  826. * comando que vai ser executado
  827. * @param username
  828. * nome do utilizador sobre o qual vai ser executado o comando
  829. * @return inteiro equivalente ao codigo de erro, 0 se nao tem nenhum erro
  830. */
  831. private int validCommand(String command, String username) {
  832. int result = 0;
  833. if (command == null) {
  834. return result;
  835. } else {
  836. try {
  837. String[] split = command.split(" ");
  838. switch (split[0]) {
  839. case "-q":
  840. if (split.length != 1) {
  841. result = -7;
  842. }
  843. break;
  844. case "-a":
  845. if (split.length < 2) {
  846. result = -7;
  847. }
  848. break;
  849. case "-l":
  850. if (split.length != 2) {
  851. result = -7;
  852. } else if (!userExists(split[1])) {
  853. result = -1;
  854. } else if (!verifyFollower(username, split[1])) {
  855. result = -2;
  856. } else if (!hasPhotos(split[1])) {
  857. result = -6;
  858. }
  859. break;
  860. case "-i":
  861. if (split.length != 3) {
  862. result = -7;
  863. } else if (!userExists(split[1])) {
  864. result = -1;
  865. } else if (!verifyFollower(username, split[1])) {
  866. result = -2;
  867. } else if (!hasPhotos(split[1])) {
  868. result = -6;
  869. } else if (!photoExists(split[1], split[2])) {
  870. result = -3;
  871. }
  872. break;
  873. case "-g":
  874. if (split.length != 2) {
  875. result = -7;
  876. }
  877. if (!userExists(split[1])) {
  878. result = -1;
  879. } else if (!verifyFollower(username, split[1])) {
  880. result = -2;
  881. } else if (!hasPhotos(split[1])) {
  882. result = -6;
  883. }
  884. break;
  885. case "-c":
  886. if (split.length != 3) {
  887. result = -7;
  888. }
  889. if (!userExists(split[1])) {
  890. result = -1;
  891. } else if (!verifyFollower(username, split[1])) {
  892. result = -2;
  893. } else if (!hasPhotos(split[1])) {
  894. result = -6;
  895. } else if (!photoExists(split[1], split[2])) {
  896. result = -3;
  897. }
  898. break;
  899. case "-L":
  900. if (split.length != 3) {
  901. result = -7;
  902. }
  903. if (!userExists(split[1])) {
  904. result = -1;
  905. } else if (!verifyFollower(username, split[1])) {
  906. result = -2;
  907. } else if (!hasPhotos(split[1])) {
  908. result = -6;
  909. } else if (!photoExists(split[1], split[2])) {
  910. result = -3;
  911. }
  912. break;
  913. case "-D":
  914. if (split.length != 3) {
  915. result = -7;
  916. }
  917. if (!userExists(split[1])) {
  918. result = -1;
  919. } else if (!verifyFollower(username, split[1])) {
  920. result = -2;
  921. } else if (!hasPhotos(split[1])) {
  922. result = -6;
  923. } else if (!photoExists(split[1], split[2])) {
  924. result = -3;
  925. }
  926. break;
  927. case "-f":
  928. if (split.length < 2) {
  929. result = -7;
  930. }
  931. break;
  932. case "-r":
  933. if (split.length < 2) {
  934. result = -7;
  935. }
  936. break;
  937. default:
  938. System.err.println("ERRO: Comando introduzido invalido!");
  939. result = -7;
  940. }
  941. } catch (IOException e) {
  942. result = -4;
  943. }
  944. return result;
  945. }
  946. }
  947. }
  948. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement