Advertisement
Guest User

Untitled

a guest
Mar 24th, 2018
106
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 18.39 KB | None | 0 0
  1. import java.io.BufferedWriter;
  2. import java.io.File;
  3. import java.io.FileWriter;
  4. import java.io.FilenameFilter;
  5. import java.io.IOException;
  6. import java.io.ObjectInputStream;
  7. import java.io.ObjectOutputStream;
  8. import java.net.Socket;
  9. import java.net.UnknownHostException;
  10. import java.util.ArrayList;
  11. import java.util.LinkedHashSet;
  12. import java.util.List;
  13. import java.util.Scanner;
  14. import java.util.Set;
  15.  
  16. /**
  17. * Cliente PhotoShare
  18. *
  19. * @author Grupo 37 Pedro Gaspar 46411, Ricardo Santos 47078, Ana Sofia Godinho
  20. * 48359
  21. *
  22. */
  23. public class PhotoShare {
  24.  
  25. private static final String SEPARADOR = File.separator;
  26. private static final String PASTAPROG = System.getProperty("user.dir");
  27. private static final String PASTALOCAL = PASTAPROG + SEPARADOR + "local" + SEPARADOR;
  28.  
  29. public static void main(String[] args) throws ClassNotFoundException, IOException {
  30. System.out.println("Bem-vindo ao PhotoShare!");
  31. PhotoShare psClient = new PhotoShare();
  32. psClient.startClient();
  33. }
  34.  
  35. /**
  36. * Verifica validade das credenciais de acordo com as restricoes do programa
  37. *
  38. * @param sc
  39. * Scanner usado para ler valores do teclado
  40. * @return vetor de Strings contendo username, password e ip:porto, nas posicoes
  41. * 0, 1 e 2, respetivamente
  42. */
  43. private String[] validCreds(Scanner sc) {
  44.  
  45. String[] result = new String[3];
  46. boolean validated = false;
  47.  
  48. while (!validated) {
  49. System.out.println("Insira as credenciais: ");
  50. String input = sc.nextLine();
  51. String[] split_command = input.split(" ");
  52.  
  53. // Verificar tamanhos validos e primeiro argumento
  54. if ((split_command.length == 3 || split_command.length == 4) && split_command[0].equals("PhotoShare")) {
  55. result[0] = split_command[1];
  56. if (split_command.length == 3) {// apenas user e server
  57. result[2] = split_command[2];
  58. System.out.print("Insira a password: ");
  59. result[1] = sc.nextLine();
  60. } else {// Todos os dados
  61. result[2] = split_command[3];
  62. result[1] = split_command[2];
  63. }
  64. validated = (result[1].split(" ").length == 1);
  65. if (!validated) {
  66. System.out.println("Login falhado. Tente outra vez!");
  67. }
  68. } else {
  69. System.err.println(
  70. "Argumentos Errados -> PhotoShare <localUserID> <password> <ip:porto> OU PhotoShare <localUserID> <ip:porto>\n");
  71. }
  72. }
  73. return result;
  74. }
  75.  
  76. /**
  77. * /** Remove duplicados
  78. *
  79. * @param inicial
  80. * String inicial ah qual vao ser removidos os valores duplicados
  81. * @return String sem os valores duplicados
  82. */
  83. private String removeDups(String inicial) {
  84. String[] verReps = inicial.split(" ");
  85. StringBuilder res = new StringBuilder();
  86. List<String> al = new ArrayList<>();
  87. Set<String> s = new LinkedHashSet<>(al);
  88. for (String str : verReps) {
  89. al.add(str);
  90. }
  91. s.addAll(al);
  92. al.clear();
  93. al.addAll(s);
  94.  
  95. for (String strFim : al) {
  96. res.append(strFim + " ");
  97. }
  98. res.deleteCharAt(res.length() - 1);
  99. return res.toString();
  100. }
  101.  
  102. /**
  103. * Metodo para imprimir uma lista de Strings
  104. *
  105. * @param list
  106. * Lista a ser impressa
  107. */
  108. private void printList(List<String> list) {
  109. for (String s : list)
  110. System.out.println(s);
  111. }
  112.  
  113. /**
  114. * Impressao do resultado de uma lista de Strings
  115. * @param list - Lista a ser impressa
  116. */
  117. private void listErr(List<String> list) {
  118. if (list != null) {
  119. for (String s : list) {
  120. String[] linhaSeparada = s.split(" ");
  121. switch (linhaSeparada[0]) {
  122. case "0":
  123. System.out.println("Operacao realizada com sucesso para o utilizador: " + linhaSeparada[1]);
  124. break;
  125. case "-1":
  126. System.err.println("ERRO: Utilizador nao existe: " + linhaSeparada[1]);
  127. break;
  128. case "-2":
  129. System.err.println("ERRO: Utilizador nao e seu seguidor: " + linhaSeparada[1]);
  130. break;
  131. case "-3":
  132. System.err.println("ERRO: Utilizador ja o segue: " + linhaSeparada[1]);
  133. break;
  134. case "-4":
  135. System.err.println("ERRO: Operacao no utilizador " + linhaSeparada[1] + " tente novamente");
  136. break;
  137. default:
  138. System.err.println("ERRO: Utilizador: " + linhaSeparada[1]);
  139. }
  140. }
  141. }
  142. }
  143.  
  144. /**
  145. * Metodo que trata dos varios tipos de erros relacionados com a execucao do
  146. * programa
  147. *
  148. * @param erro
  149. * codigo de erro gerado para ser tratado
  150. */
  151. private void trataErros(int erro) {
  152. if (erro == -1) {
  153. System.err.println("ERRO: O utilizador nao existe");
  154. } else if (erro == -2) {
  155. System.err.println("ERRO: Nao segue este utilizador");
  156. } else if (erro == -3) {
  157. System.err.println("ERRO: A foto escolhida nao existe");
  158. } else if (erro == -4) {
  159. System.err.println("ERRO: Erro do lado do servidor. Tente novamente!");
  160. } else if (erro == -5) {
  161. System.err.println("ERRO: Numero de argumentos incorreto");
  162. } else if (erro == -6) {
  163. System.err.println("ERRO: Utilizador nao tem fotos");
  164. } else if (erro == -7) {
  165. System.err.println("ERRO: Comando nao e valido");
  166. } else if (erro == -8) {
  167. System.err.println("ERRO: Nao pode fazer esta operacao sobre si mesmo");
  168. } else if (erro == -9) {
  169. System.err.println("ERRO: Tipo de ficheiro nao e valido.");
  170. } else {
  171. System.err.println("ERRO NAO DEFINIDO");
  172. }
  173. }
  174.  
  175. /**
  176. * Ativa cliente Estabelece ligacao ao servidor e trata da comunicacao com o
  177. * mesmo Realiza as funcoes de cliente
  178. */
  179. private void startClient() {
  180. Socket cSoc = null;
  181. Scanner sc = new Scanner(System.in);
  182.  
  183. ObjectInputStream in = null;
  184. ObjectOutputStream out = null;
  185. boolean authenticated = false;
  186. int erro = 3;
  187. String username = null;
  188. // permite tentar fazer login 3 vezes antes do cliente ir abaixo
  189. while (!authenticated && erro != 0) {
  190. try {
  191. String[] input = validCreds(sc);
  192. String[] connection = input[2].split(":");
  193. username = input[0];
  194. if (connection.length != 2) {
  195. System.err.println("ERRO: Introduza um ip e porto validos");
  196. continue;
  197. }
  198. int fromServer = 0;
  199. if (cSoc == null) {
  200. try {
  201. cSoc = new Socket(connection[0] + "", Integer.parseInt(connection[1]));
  202. } catch (UnknownHostException e) {
  203. System.err.println("Erro a estabelecer a ligacao com o servidor. Tente novamente");
  204. continue;
  205. }
  206. out = new ObjectOutputStream(cSoc.getOutputStream());
  207. in = new ObjectInputStream(cSoc.getInputStream());
  208.  
  209. }
  210.  
  211. out.writeObject(input[0]);
  212. out.writeObject(input[1]);
  213.  
  214. fromServer = (Integer) in.readObject();
  215.  
  216. if (fromServer == 0) {
  217. System.out.println("Login feito!");
  218. authenticated = true;
  219. } else if (fromServer == 1) {
  220. System.out.println("Conta criada. Login feito!");
  221. authenticated = true;
  222. } else if (fromServer == -1) {
  223. System.err.println("ERRO: Credenciais Incorretas.");
  224. erro--;
  225. } else if (fromServer == 2) {
  226. System.err.println("ERRO: Utilizador ja esta no sistema");
  227. System.exit(0);
  228. } else {
  229. System.err.println("Ocorreu um erro na ligacao com o servidor. Tente novamente");
  230. }
  231. } catch (IOException | ClassNotFoundException e) {
  232. System.err.println("ERRO: Comunicacao com o servidor. Tente novamente.");
  233. }
  234. }
  235.  
  236. if (erro == 0) {
  237. System.err.println("Numero de tentativas permitidas ultrapassadas. Utilizador nao autenticado.");
  238.  
  239. try {
  240. out.close();
  241. } catch (IOException e) {
  242. e.printStackTrace();
  243. }
  244. sc.close();
  245. System.exit(-1);
  246. }
  247.  
  248. String[] linhaSeparada = null;
  249. boolean quit = false;
  250.  
  251. while (!quit) {
  252. try {
  253. System.out.println("Insira um comando: ");
  254. String linha = sc.nextLine();
  255. linhaSeparada = linha.split(" ");
  256. if (!linhaSeparada[0].equals("PhotoShare"))
  257. System.out.println("Argumentos Errados -> PhotoShare <flag> <conteudo>\n");
  258. else {
  259. String comando = linhaSeparada[1];
  260. switch (comando) {
  261. // QUIT
  262. case "-q":
  263. out.writeObject(comando);
  264. quit = true;
  265. break;
  266. // Transferir fotos para o servidor
  267. case "-a":
  268. if (linhaSeparada.length < 3) {
  269. trataErros(-5);
  270. } else {
  271. linha = removeDups(linha);
  272. linhaSeparada = linha.split(" ");
  273. List<String> validos = new ArrayList<String>();
  274.  
  275. StringBuilder sb = new StringBuilder();
  276. sb.append(comando);
  277.  
  278. // Adiciona um ficheiro se ele existir, removendo o caminho
  279. for (int i = 2; i < linhaSeparada.length; i++) {
  280. String [] split = linhaSeparada[i].split("\\.(?=[^\\.]+$)");
  281. if (split.length != 2) {
  282. trataErros(-9);
  283. } else {
  284. String extensao = split[1];
  285. boolean verifica = false;
  286. Imagens[] tipos = Imagens.values();
  287. int j = 0;
  288. while (tipos.length > j && !verifica) {
  289. verifica = tipos[j].toString().equals(extensao);
  290. j++;
  291. }
  292.  
  293. if (!verifica) {
  294. trataErros(-9);
  295. } else if (!new File(linhaSeparada[i]).exists()) {
  296. System.err.println("Ficheiro nao existente: " + linhaSeparada[i]);
  297. } else {
  298. String tiraBarras = linhaSeparada[i];
  299. String t = tiraBarras.substring(tiraBarras.lastIndexOf(SEPARADOR) + 1);
  300. sb.append(" " + t);
  301. validos.add(linhaSeparada[i]);
  302. }
  303. }
  304. }
  305.  
  306. String nomesImagens = sb.toString();
  307. String[] splitNomeImagens = nomesImagens.split(" ");
  308. if (splitNomeImagens.length == 1) {
  309. System.err.println("Todas as imagens sao invalidas");
  310. } else {
  311.  
  312. out.writeObject(nomesImagens);
  313.  
  314.  
  315.  
  316.  
  317. // receber a resposta do servidor com os ficheiros que criam conflito
  318.  
  319. List<Integer> conflitos = (List<Integer>) in.readObject();
  320.  
  321. // Envia ficheiros sem conflito
  322. int i = 0;
  323. while (i < validos.size()) {
  324. if (!conflitos.contains(i)) {
  325. if (Ferramentas.sendFile(out, in, validos.get(i))) {
  326. System.out.println("Adicionou a imagem: " + splitNomeImagens[i+1]);
  327. } else {
  328. System.err
  329. .println("Erro a transferir a imagem: " + splitNomeImagens[i+1]);
  330. }
  331. } else {
  332. System.err.println(
  333. "ERRO: Ja contem uma imagem com nome: " + splitNomeImagens[i+1]);
  334. }
  335. i++;
  336. }
  337. }
  338. }
  339. break;
  340. // listagem de fotos de um utilizador
  341. case "-l":
  342. if (linhaSeparada.length != 3) {
  343. trataErros(-5);
  344. } else {
  345. out.writeObject(linhaSeparada[1] + " " + linhaSeparada[2]);
  346. int code = (int) in.readObject();
  347. if (code < 0) {
  348. trataErros(code);
  349. } else {
  350. List<String> lista = (List<String>) in.readObject();
  351. if (lista.isEmpty())
  352. System.err.println("ERRO: Este utilizador nao tem fotos");
  353. else
  354. printList(lista);
  355. }
  356. }
  357. break;
  358. case "-i":
  359. if (linhaSeparada.length != 4) {
  360. trataErros(-5);
  361. } else {
  362. out.writeObject(linhaSeparada[1] + " " + linhaSeparada[2] + " " + linhaSeparada[3]);
  363. int code = (int) in.readObject();
  364. if (code < 0) {
  365. trataErros(code);
  366. } else {
  367. List<String> lista = (List<String>) in.readObject();
  368. printList(lista);
  369. }
  370. }
  371. break;
  372. case "-g":
  373. if (linhaSeparada.length != 3) {
  374. trataErros(-5);
  375. } else {
  376. out.writeObject(linhaSeparada[1] + " " + linhaSeparada[2]);
  377. int code = (Integer) in.readObject();
  378. if (code < 0) {
  379. trataErros(code);
  380. } else {
  381.  
  382. // Cria a pasta se nao existir
  383. File caminhoLocal = new File(PASTALOCAL);
  384. File pastaLocalUser = new File(PASTALOCAL + linhaSeparada[2]);
  385. if (!caminhoLocal.exists()) {
  386. caminhoLocal.mkdirs();
  387. }
  388.  
  389. // Procura as fotos ja existentes do utilizador
  390. File[] nomeFotos = null;
  391. if (pastaLocalUser.exists()) {
  392. nomeFotos = pastaLocalUser.listFiles(new FilenameFilter() {
  393. public boolean accept(File dir, String name) {
  394. return name.toLowerCase().endsWith(".txt");
  395. }
  396. });
  397. } else {
  398. pastaLocalUser.mkdirs();
  399. }
  400. out.writeObject(nomeFotos);
  401. // reescrever comentarios de fotos ja existentes
  402. List<String> comments = null;
  403. if (nomeFotos != null) {
  404. for (File file : nomeFotos) {
  405. comments = (List<String>) in.readObject();
  406. if (comments == null) {
  407. trataErros(-4);
  408. break;
  409. }
  410. BufferedWriter bw = new BufferedWriter(new FileWriter(file));
  411. for (String comment : comments) {
  412. bw.write(comment);
  413. bw.newLine();
  414. }
  415. bw.close();
  416. }
  417. }
  418. if (comments == null && nomeFotos != null) {
  419. break;
  420. }
  421. // transferir fotos e criar ficheiros de comentarios de fotos nao existentes
  422. List<String> nomesFotos = (List<String>) in.readObject();
  423. for (String nome : nomesFotos) {
  424. nome = nome.split(" ")[0];
  425. String caminho = pastaLocalUser + SEPARADOR + nome;
  426. if (!Ferramentas.receiveFile(in, out, caminho)) {
  427. System.err.println("ERRO: Transferencia do ficheiro " + nome);
  428. } else {
  429. File novoTxt = new File(pastaLocalUser + SEPARADOR + nome + ".txt");
  430. comments = (List<String>) in.readObject();
  431. BufferedWriter bw = new BufferedWriter(new FileWriter(novoTxt));
  432. for (String comment : comments) {
  433. bw.write(comment);
  434. bw.newLine();
  435. }
  436. bw.close();
  437. }
  438.  
  439. }
  440. System.out.println("Pasta copiada com sucesso!");
  441. }
  442. }
  443. break;
  444. case "-c":
  445. if (linhaSeparada.length < 5) {
  446. trataErros(-5);
  447. } else {
  448. StringBuilder strb = new StringBuilder();
  449. for (int j = 2; j < linhaSeparada.length - 2; j++) {
  450. strb.append(linhaSeparada[j] + " ");
  451. }
  452. strb.deleteCharAt(strb.length() - 1);
  453. out.writeObject(linhaSeparada[1] + " " + linhaSeparada[linhaSeparada.length - 2] + " "
  454. + linhaSeparada[linhaSeparada.length - 1]);
  455. out.writeObject(strb.toString());
  456. int code = (int) in.readObject();
  457. if (code < 0) {
  458. trataErros(code);
  459. } else {
  460. System.out.println("Comentario adicionado com sucesso!");
  461. }
  462. }
  463. break;
  464. case "-L":
  465. if (linhaSeparada.length != 4) {
  466. trataErros(-5);
  467. } else {
  468. out.writeObject(linhaSeparada[1] + " " + linhaSeparada[2] + " " + linhaSeparada[3]);
  469. int code = (int) in.readObject();
  470. if (code < 0) {
  471. trataErros(code);
  472. } else {
  473. System.out.println(
  474. "Deu like a foto " + linhaSeparada[3] + " do utilizador " + linhaSeparada[2]);
  475. }
  476. }
  477. break;
  478. case "-D":
  479. if (linhaSeparada.length != 4) {
  480. trataErros(-5);
  481. } else {
  482. out.writeObject(linhaSeparada[1] + " " + linhaSeparada[2] + " " + linhaSeparada[3]);
  483. int code = (int) in.readObject();
  484. if (code < 0) {
  485. trataErros(code);
  486. } else {
  487. System.out.println("Deu dislike a foto " + linhaSeparada[3] + " do utilizador "
  488. + linhaSeparada[2]);
  489. }
  490. }
  491.  
  492. break;
  493. case "-f":
  494. if (linhaSeparada.length < 3) {
  495. trataErros(-5);
  496. } else {
  497. StringBuilder nomes = new StringBuilder();
  498. for (int j = 2; j < linhaSeparada.length; j++) {
  499. if (!linhaSeparada[j].equals(username)) {
  500. nomes.append((linhaSeparada[j] + " "));
  501. } else {
  502. trataErros(-8);
  503. }
  504. }
  505. if (nomes.length() == 0) {
  506. System.err.println("ERRO: Nao introduziu utilizadores validos");
  507. } else {
  508. out.writeObject(linhaSeparada[1] + " " + removeDups(nomes.toString()));
  509. int code = (Integer) in.readObject();
  510. if (code >= 0) {
  511. ArrayList<ArrayList<String>> respostaF = (ArrayList<ArrayList<String>>) in
  512. .readObject();
  513.  
  514. if (respostaF.get(0).isEmpty()) {
  515. System.err.println("ERRO: Nao foi adicionado nenhum utilizador");
  516. if (!respostaF.get(1).isEmpty()) {
  517. System.err.println("ERRO: Os seguintes utilizadores ja o seguem:");
  518. for (String s : respostaF.get(1))
  519. System.err.println(s);
  520. }
  521. if (!respostaF.get(2).isEmpty()) {
  522. System.err.println("ERRO: Os seguintes utilizadores nao existem:");
  523. for (String s : respostaF.get(2))
  524. System.err.println(s);
  525. }
  526. } else {
  527. for (String s : respostaF.get(0))
  528. System.out.println(s + " esta agora a segui-lo");
  529. if (!respostaF.get(1).isEmpty()) {
  530. System.err.println("ERRO: Os seguintes utilizadores ja o seguem:");
  531. for (String s : respostaF.get(1))
  532. System.err.println(s);
  533. }
  534. if (!respostaF.get(2).isEmpty()) {
  535. System.err.println("ERRO: Os seguintes utilizadores nao existem:");
  536. for (String s : respostaF.get(2))
  537. System.err.println(s);
  538. }
  539. }
  540. } else {
  541. trataErros(code);
  542. }
  543. }
  544. }
  545. break;
  546. case "-r":
  547. if (linhaSeparada.length < 3) {
  548. trataErros(-5);
  549. } else {
  550. StringBuilder strb = new StringBuilder();
  551. for (int j = 2; j < linhaSeparada.length; j++) {
  552. if (!linhaSeparada[j].equals(username)) {
  553. strb.append(linhaSeparada[j] + " ");
  554. } else {
  555. trataErros(-8);
  556. }
  557. }
  558. if (strb.length() == 0) {
  559. System.err.println("ERRO: Nao introduziu utilizadores validos");
  560. } else {
  561. strb.deleteCharAt(strb.length() - 1);
  562. out.writeObject(linhaSeparada[1] + " " + removeDups(strb.toString()));
  563. int code = (Integer) in.readObject();
  564. if (code >= 0) {
  565. List<String> retorno = (ArrayList<String>) in.readObject();
  566. listErr(retorno);
  567. } else {
  568. trataErros(code);
  569. }
  570. }
  571. }
  572. break;
  573. default:
  574. System.err.println("ERRO: Comando invalido");
  575. }
  576. }
  577. } catch (ClassNotFoundException | IOException e) {
  578. System.err.println("Erro: comunicacao com o servidor. Tente novamente.");
  579. }
  580.  
  581. }
  582. try {
  583. out.close();
  584. } catch (IOException e) {
  585. e.printStackTrace();
  586. }
  587. sc.close();
  588. }
  589. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement