Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.io.BufferedWriter;
- import java.io.File;
- import java.io.FileWriter;
- import java.io.FilenameFilter;
- import java.io.IOException;
- import java.io.ObjectInputStream;
- import java.io.ObjectOutputStream;
- import java.net.Socket;
- import java.net.UnknownHostException;
- import java.util.ArrayList;
- import java.util.LinkedHashSet;
- import java.util.List;
- import java.util.Scanner;
- import java.util.Set;
- /**
- * Cliente PhotoShare
- *
- * @author Grupo 37 Pedro Gaspar 46411, Ricardo Santos 47078, Ana Sofia Godinho
- * 48359
- *
- */
- public class PhotoShare {
- private static final String SEPARADOR = File.separator;
- private static final String PASTAPROG = System.getProperty("user.dir");
- private static final String PASTALOCAL = PASTAPROG + SEPARADOR + "local" + SEPARADOR;
- public static void main(String[] args) throws ClassNotFoundException, IOException {
- System.out.println("Bem-vindo ao PhotoShare!");
- PhotoShare psClient = new PhotoShare();
- psClient.startClient();
- }
- /**
- * Verifica validade das credenciais de acordo com as restricoes do programa
- *
- * @param sc
- * Scanner usado para ler valores do teclado
- * @return vetor de Strings contendo username, password e ip:porto, nas posicoes
- * 0, 1 e 2, respetivamente
- */
- private String[] validCreds(Scanner sc) {
- String[] result = new String[3];
- boolean validated = false;
- while (!validated) {
- System.out.println("Insira as credenciais: ");
- String input = sc.nextLine();
- String[] split_command = input.split(" ");
- // Verificar tamanhos validos e primeiro argumento
- if ((split_command.length == 3 || split_command.length == 4) && split_command[0].equals("PhotoShare")) {
- result[0] = split_command[1];
- if (split_command.length == 3) {// apenas user e server
- result[2] = split_command[2];
- System.out.print("Insira a password: ");
- result[1] = sc.nextLine();
- } else {// Todos os dados
- result[2] = split_command[3];
- result[1] = split_command[2];
- }
- validated = (result[1].split(" ").length == 1);
- if (!validated) {
- System.out.println("Login falhado. Tente outra vez!");
- }
- } else {
- System.err.println(
- "Argumentos Errados -> PhotoShare <localUserID> <password> <ip:porto> OU PhotoShare <localUserID> <ip:porto>\n");
- }
- }
- return result;
- }
- /**
- * /** Remove duplicados
- *
- * @param inicial
- * String inicial ah qual vao ser removidos os valores duplicados
- * @return String sem os valores duplicados
- */
- private String removeDups(String inicial) {
- String[] verReps = inicial.split(" ");
- StringBuilder res = new StringBuilder();
- List<String> al = new ArrayList<>();
- Set<String> s = new LinkedHashSet<>(al);
- for (String str : verReps) {
- al.add(str);
- }
- s.addAll(al);
- al.clear();
- al.addAll(s);
- for (String strFim : al) {
- res.append(strFim + " ");
- }
- res.deleteCharAt(res.length() - 1);
- return res.toString();
- }
- /**
- * Metodo para imprimir uma lista de Strings
- *
- * @param list
- * Lista a ser impressa
- */
- private void printList(List<String> list) {
- for (String s : list)
- System.out.println(s);
- }
- /**
- * Impressao do resultado de uma lista de Strings
- * @param list - Lista a ser impressa
- */
- private void listErr(List<String> list) {
- if (list != null) {
- for (String s : list) {
- String[] linhaSeparada = s.split(" ");
- switch (linhaSeparada[0]) {
- case "0":
- System.out.println("Operacao realizada com sucesso para o utilizador: " + linhaSeparada[1]);
- break;
- case "-1":
- System.err.println("ERRO: Utilizador nao existe: " + linhaSeparada[1]);
- break;
- case "-2":
- System.err.println("ERRO: Utilizador nao e seu seguidor: " + linhaSeparada[1]);
- break;
- case "-3":
- System.err.println("ERRO: Utilizador ja o segue: " + linhaSeparada[1]);
- break;
- case "-4":
- System.err.println("ERRO: Operacao no utilizador " + linhaSeparada[1] + " tente novamente");
- break;
- default:
- System.err.println("ERRO: Utilizador: " + linhaSeparada[1]);
- }
- }
- }
- }
- /**
- * Metodo que trata dos varios tipos de erros relacionados com a execucao do
- * programa
- *
- * @param erro
- * codigo de erro gerado para ser tratado
- */
- private void trataErros(int erro) {
- if (erro == -1) {
- System.err.println("ERRO: O utilizador nao existe");
- } else if (erro == -2) {
- System.err.println("ERRO: Nao segue este utilizador");
- } else if (erro == -3) {
- System.err.println("ERRO: A foto escolhida nao existe");
- } else if (erro == -4) {
- System.err.println("ERRO: Erro do lado do servidor. Tente novamente!");
- } else if (erro == -5) {
- System.err.println("ERRO: Numero de argumentos incorreto");
- } else if (erro == -6) {
- System.err.println("ERRO: Utilizador nao tem fotos");
- } else if (erro == -7) {
- System.err.println("ERRO: Comando nao e valido");
- } else if (erro == -8) {
- System.err.println("ERRO: Nao pode fazer esta operacao sobre si mesmo");
- } else if (erro == -9) {
- System.err.println("ERRO: Tipo de ficheiro nao e valido.");
- } else {
- System.err.println("ERRO NAO DEFINIDO");
- }
- }
- /**
- * Ativa cliente Estabelece ligacao ao servidor e trata da comunicacao com o
- * mesmo Realiza as funcoes de cliente
- */
- private void startClient() {
- Socket cSoc = null;
- Scanner sc = new Scanner(System.in);
- ObjectInputStream in = null;
- ObjectOutputStream out = null;
- boolean authenticated = false;
- int erro = 3;
- String username = null;
- // permite tentar fazer login 3 vezes antes do cliente ir abaixo
- while (!authenticated && erro != 0) {
- try {
- String[] input = validCreds(sc);
- String[] connection = input[2].split(":");
- username = input[0];
- if (connection.length != 2) {
- System.err.println("ERRO: Introduza um ip e porto validos");
- continue;
- }
- int fromServer = 0;
- if (cSoc == null) {
- try {
- cSoc = new Socket(connection[0] + "", Integer.parseInt(connection[1]));
- } catch (UnknownHostException e) {
- System.err.println("Erro a estabelecer a ligacao com o servidor. Tente novamente");
- continue;
- }
- out = new ObjectOutputStream(cSoc.getOutputStream());
- in = new ObjectInputStream(cSoc.getInputStream());
- }
- out.writeObject(input[0]);
- out.writeObject(input[1]);
- fromServer = (Integer) in.readObject();
- if (fromServer == 0) {
- System.out.println("Login feito!");
- authenticated = true;
- } else if (fromServer == 1) {
- System.out.println("Conta criada. Login feito!");
- authenticated = true;
- } else if (fromServer == -1) {
- System.err.println("ERRO: Credenciais Incorretas.");
- erro--;
- } else if (fromServer == 2) {
- System.err.println("ERRO: Utilizador ja esta no sistema");
- System.exit(0);
- } else {
- System.err.println("Ocorreu um erro na ligacao com o servidor. Tente novamente");
- }
- } catch (IOException | ClassNotFoundException e) {
- System.err.println("ERRO: Comunicacao com o servidor. Tente novamente.");
- }
- }
- if (erro == 0) {
- System.err.println("Numero de tentativas permitidas ultrapassadas. Utilizador nao autenticado.");
- try {
- out.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- sc.close();
- System.exit(-1);
- }
- String[] linhaSeparada = null;
- boolean quit = false;
- while (!quit) {
- try {
- System.out.println("Insira um comando: ");
- String linha = sc.nextLine();
- linhaSeparada = linha.split(" ");
- if (!linhaSeparada[0].equals("PhotoShare"))
- System.out.println("Argumentos Errados -> PhotoShare <flag> <conteudo>\n");
- else {
- String comando = linhaSeparada[1];
- switch (comando) {
- // QUIT
- case "-q":
- out.writeObject(comando);
- quit = true;
- break;
- // Transferir fotos para o servidor
- case "-a":
- if (linhaSeparada.length < 3) {
- trataErros(-5);
- } else {
- linha = removeDups(linha);
- linhaSeparada = linha.split(" ");
- List<String> validos = new ArrayList<String>();
- StringBuilder sb = new StringBuilder();
- sb.append(comando);
- // Adiciona um ficheiro se ele existir, removendo o caminho
- for (int i = 2; i < linhaSeparada.length; i++) {
- String [] split = linhaSeparada[i].split("\\.(?=[^\\.]+$)");
- if (split.length != 2) {
- trataErros(-9);
- } else {
- String extensao = split[1];
- boolean verifica = false;
- Imagens[] tipos = Imagens.values();
- int j = 0;
- while (tipos.length > j && !verifica) {
- verifica = tipos[j].toString().equals(extensao);
- j++;
- }
- if (!verifica) {
- trataErros(-9);
- } else if (!new File(linhaSeparada[i]).exists()) {
- System.err.println("Ficheiro nao existente: " + linhaSeparada[i]);
- } else {
- String tiraBarras = linhaSeparada[i];
- String t = tiraBarras.substring(tiraBarras.lastIndexOf(SEPARADOR) + 1);
- sb.append(" " + t);
- validos.add(linhaSeparada[i]);
- }
- }
- }
- String nomesImagens = sb.toString();
- String[] splitNomeImagens = nomesImagens.split(" ");
- if (splitNomeImagens.length == 1) {
- System.err.println("Todas as imagens sao invalidas");
- } else {
- out.writeObject(nomesImagens);
- // receber a resposta do servidor com os ficheiros que criam conflito
- List<Integer> conflitos = (List<Integer>) in.readObject();
- // Envia ficheiros sem conflito
- int i = 0;
- while (i < validos.size()) {
- if (!conflitos.contains(i)) {
- if (Ferramentas.sendFile(out, in, validos.get(i))) {
- System.out.println("Adicionou a imagem: " + splitNomeImagens[i+1]);
- } else {
- System.err
- .println("Erro a transferir a imagem: " + splitNomeImagens[i+1]);
- }
- } else {
- System.err.println(
- "ERRO: Ja contem uma imagem com nome: " + splitNomeImagens[i+1]);
- }
- i++;
- }
- }
- }
- break;
- // listagem de fotos de um utilizador
- case "-l":
- if (linhaSeparada.length != 3) {
- trataErros(-5);
- } else {
- out.writeObject(linhaSeparada[1] + " " + linhaSeparada[2]);
- int code = (int) in.readObject();
- if (code < 0) {
- trataErros(code);
- } else {
- List<String> lista = (List<String>) in.readObject();
- if (lista.isEmpty())
- System.err.println("ERRO: Este utilizador nao tem fotos");
- else
- printList(lista);
- }
- }
- break;
- case "-i":
- if (linhaSeparada.length != 4) {
- trataErros(-5);
- } else {
- out.writeObject(linhaSeparada[1] + " " + linhaSeparada[2] + " " + linhaSeparada[3]);
- int code = (int) in.readObject();
- if (code < 0) {
- trataErros(code);
- } else {
- List<String> lista = (List<String>) in.readObject();
- printList(lista);
- }
- }
- break;
- case "-g":
- if (linhaSeparada.length != 3) {
- trataErros(-5);
- } else {
- out.writeObject(linhaSeparada[1] + " " + linhaSeparada[2]);
- int code = (Integer) in.readObject();
- if (code < 0) {
- trataErros(code);
- } else {
- // Cria a pasta se nao existir
- File caminhoLocal = new File(PASTALOCAL);
- File pastaLocalUser = new File(PASTALOCAL + linhaSeparada[2]);
- if (!caminhoLocal.exists()) {
- caminhoLocal.mkdirs();
- }
- // Procura as fotos ja existentes do utilizador
- File[] nomeFotos = null;
- if (pastaLocalUser.exists()) {
- nomeFotos = pastaLocalUser.listFiles(new FilenameFilter() {
- public boolean accept(File dir, String name) {
- return name.toLowerCase().endsWith(".txt");
- }
- });
- } else {
- pastaLocalUser.mkdirs();
- }
- out.writeObject(nomeFotos);
- // reescrever comentarios de fotos ja existentes
- List<String> comments = null;
- if (nomeFotos != null) {
- for (File file : nomeFotos) {
- comments = (List<String>) in.readObject();
- if (comments == null) {
- trataErros(-4);
- break;
- }
- BufferedWriter bw = new BufferedWriter(new FileWriter(file));
- for (String comment : comments) {
- bw.write(comment);
- bw.newLine();
- }
- bw.close();
- }
- }
- if (comments == null && nomeFotos != null) {
- break;
- }
- // transferir fotos e criar ficheiros de comentarios de fotos nao existentes
- List<String> nomesFotos = (List<String>) in.readObject();
- for (String nome : nomesFotos) {
- nome = nome.split(" ")[0];
- String caminho = pastaLocalUser + SEPARADOR + nome;
- if (!Ferramentas.receiveFile(in, out, caminho)) {
- System.err.println("ERRO: Transferencia do ficheiro " + nome);
- } else {
- File novoTxt = new File(pastaLocalUser + SEPARADOR + nome + ".txt");
- comments = (List<String>) in.readObject();
- BufferedWriter bw = new BufferedWriter(new FileWriter(novoTxt));
- for (String comment : comments) {
- bw.write(comment);
- bw.newLine();
- }
- bw.close();
- }
- }
- System.out.println("Pasta copiada com sucesso!");
- }
- }
- break;
- case "-c":
- if (linhaSeparada.length < 5) {
- trataErros(-5);
- } else {
- StringBuilder strb = new StringBuilder();
- for (int j = 2; j < linhaSeparada.length - 2; j++) {
- strb.append(linhaSeparada[j] + " ");
- }
- strb.deleteCharAt(strb.length() - 1);
- out.writeObject(linhaSeparada[1] + " " + linhaSeparada[linhaSeparada.length - 2] + " "
- + linhaSeparada[linhaSeparada.length - 1]);
- out.writeObject(strb.toString());
- int code = (int) in.readObject();
- if (code < 0) {
- trataErros(code);
- } else {
- System.out.println("Comentario adicionado com sucesso!");
- }
- }
- break;
- case "-L":
- if (linhaSeparada.length != 4) {
- trataErros(-5);
- } else {
- out.writeObject(linhaSeparada[1] + " " + linhaSeparada[2] + " " + linhaSeparada[3]);
- int code = (int) in.readObject();
- if (code < 0) {
- trataErros(code);
- } else {
- System.out.println(
- "Deu like a foto " + linhaSeparada[3] + " do utilizador " + linhaSeparada[2]);
- }
- }
- break;
- case "-D":
- if (linhaSeparada.length != 4) {
- trataErros(-5);
- } else {
- out.writeObject(linhaSeparada[1] + " " + linhaSeparada[2] + " " + linhaSeparada[3]);
- int code = (int) in.readObject();
- if (code < 0) {
- trataErros(code);
- } else {
- System.out.println("Deu dislike a foto " + linhaSeparada[3] + " do utilizador "
- + linhaSeparada[2]);
- }
- }
- break;
- case "-f":
- if (linhaSeparada.length < 3) {
- trataErros(-5);
- } else {
- StringBuilder nomes = new StringBuilder();
- for (int j = 2; j < linhaSeparada.length; j++) {
- if (!linhaSeparada[j].equals(username)) {
- nomes.append((linhaSeparada[j] + " "));
- } else {
- trataErros(-8);
- }
- }
- if (nomes.length() == 0) {
- System.err.println("ERRO: Nao introduziu utilizadores validos");
- } else {
- out.writeObject(linhaSeparada[1] + " " + removeDups(nomes.toString()));
- int code = (Integer) in.readObject();
- if (code >= 0) {
- ArrayList<ArrayList<String>> respostaF = (ArrayList<ArrayList<String>>) in
- .readObject();
- if (respostaF.get(0).isEmpty()) {
- System.err.println("ERRO: Nao foi adicionado nenhum utilizador");
- if (!respostaF.get(1).isEmpty()) {
- System.err.println("ERRO: Os seguintes utilizadores ja o seguem:");
- for (String s : respostaF.get(1))
- System.err.println(s);
- }
- if (!respostaF.get(2).isEmpty()) {
- System.err.println("ERRO: Os seguintes utilizadores nao existem:");
- for (String s : respostaF.get(2))
- System.err.println(s);
- }
- } else {
- for (String s : respostaF.get(0))
- System.out.println(s + " esta agora a segui-lo");
- if (!respostaF.get(1).isEmpty()) {
- System.err.println("ERRO: Os seguintes utilizadores ja o seguem:");
- for (String s : respostaF.get(1))
- System.err.println(s);
- }
- if (!respostaF.get(2).isEmpty()) {
- System.err.println("ERRO: Os seguintes utilizadores nao existem:");
- for (String s : respostaF.get(2))
- System.err.println(s);
- }
- }
- } else {
- trataErros(code);
- }
- }
- }
- break;
- case "-r":
- if (linhaSeparada.length < 3) {
- trataErros(-5);
- } else {
- StringBuilder strb = new StringBuilder();
- for (int j = 2; j < linhaSeparada.length; j++) {
- if (!linhaSeparada[j].equals(username)) {
- strb.append(linhaSeparada[j] + " ");
- } else {
- trataErros(-8);
- }
- }
- if (strb.length() == 0) {
- System.err.println("ERRO: Nao introduziu utilizadores validos");
- } else {
- strb.deleteCharAt(strb.length() - 1);
- out.writeObject(linhaSeparada[1] + " " + removeDups(strb.toString()));
- int code = (Integer) in.readObject();
- if (code >= 0) {
- List<String> retorno = (ArrayList<String>) in.readObject();
- listErr(retorno);
- } else {
- trataErros(code);
- }
- }
- }
- break;
- default:
- System.err.println("ERRO: Comando invalido");
- }
- }
- } catch (ClassNotFoundException | IOException e) {
- System.err.println("Erro: comunicacao com o servidor. Tente novamente.");
- }
- }
- try {
- out.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- sc.close();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement