Advertisement
Guest User

Untitled

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