Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.io.BufferedReader;
- import java.io.BufferedWriter;
- import java.io.File;
- import java.io.FileNotFoundException;
- import java.io.FileReader;
- import java.io.FileWriter;
- import java.io.IOException;
- import java.io.ObjectInputStream;
- import java.io.ObjectOutputStream;
- import java.net.ServerSocket;
- import java.net.Socket;
- import java.text.DateFormat;
- import java.text.SimpleDateFormat;
- import java.util.ArrayList;
- import java.util.Date;
- import java.util.List;
- import java.util.Scanner;
- import java.util.concurrent.Semaphore;
- public class PhotoShareServer {
- private static final String PASTAPROG = System.getProperty("user.dir");
- private static final String SEPARADOR = File.separator;
- private static final String CREDFILE = PASTAPROG + SEPARADOR + "credenciais.txt";
- private static final String USERFOLDER = PASTAPROG + SEPARADOR + "users" + SEPARADOR;
- private static final String FOTOFOLDER = SEPARADOR + "fotos" + SEPARADOR;
- private static final String FICHEIRONOMEFOTOS = SEPARADOR + "fotos.txt";
- private static final String FICHEIROFOLLOWERS = SEPARADOR + "followers.txt";
- private static final String ERRO = "ERRO";
- private static List<String> onlineUsers = new ArrayList<>();
- private static Semaphore mutexUsers = new Semaphore(1, true);
- /**
- * Servidor PhotoShare
- *
- * @author Grupo 37 Pedro Gaspar 46411, Ricardo Santos 47078, Ana Sofia Godinho
- * 48359
- *
- */
- public static void main(String[] args) {
- File file = new File(CREDFILE);
- File pasta = new File(USERFOLDER);
- // Verificar existencia do ficheiro de credenciais e pasta dos utilizadores
- // se nao existir cria.
- if (!file.exists()) {
- try {
- file.createNewFile();
- } catch (IOException e) {
- System.err.println("Nao conseguiu criar o ficheiro das credenciais");
- System.exit(-1);
- }
- }
- if (!pasta.exists()) {
- pasta.mkdirs();
- }
- System.out.println("servidor: main");
- PhotoShareServer server = new PhotoShareServer();
- server.startServer();
- }
- /**
- * Ativa Servidor. Estabelece um socket no porto 23232 e fica em modo listen ah
- * espera de um cliente que se tente ligar a ele. Serve os pedidos do cliente,
- * tratando da comunicacao com o mesmo.
- *
- */
- private void startServer() {
- ServerSocket sSoc = null;
- try {
- sSoc = new ServerSocket(23232);
- while (true) {
- Socket inSoc = sSoc.accept();
- ServerThread newServerThread = new ServerThread(inSoc);
- newServerThread.start();
- }
- } catch (IOException e) {
- System.err.println("O servidor nao se conseguiu ligar");
- }
- }
- // Threads utilizadas para comunicacao com os clientes
- class ServerThread extends Thread {
- private Socket socket = null;
- ServerThread(Socket inSoc) {
- socket = inSoc;
- System.out.println("Entrou um cliente");
- }
- /**
- * Autentica o utilizador
- *
- * @param username
- * @param password
- * @return 0 se a combinacao esta no ficheiro, 1 se criou um user novo , -1 se a
- * combinacao estiver incorreta, -4 em caso de erro de criacao de ficheiros/pastas
- * @throws IOException
- */
- private int autenticacao(String username, String password) throws IOException {
- Scanner sc = null;
- String line;
- File file = new File(CREDFILE);
- int result = 0;
- if (!userExists(username)) {
- if (!new File(USERFOLDER + username + SEPARADOR).mkdirs()
- || !new File(USERFOLDER + username + FICHEIROFOLLOWERS).createNewFile()
- || !new File(USERFOLDER + username + FICHEIRONOMEFOTOS).createNewFile()
- || !new File(USERFOLDER + username + FOTOFOLDER).mkdirs()) {
- return -4;
- }
- BufferedWriter bw = null;
- // cria utilizador no ficheiro das credenciais
- bw = new BufferedWriter(new FileWriter(file, true));
- bw.write(username + ":" + password);
- bw.newLine();
- bw.close();
- result = 1;
- } else {
- // procura creds no ficheiro
- sc = new Scanner(file);
- boolean found = false;
- while (sc.hasNextLine() && !found) {
- line = sc.nextLine();
- String lineSplit[] = line.split(":");
- if (lineSplit[0].equals(username)) {
- if (lineSplit[1].equals(password)) {
- // autenticado
- result = 0;
- try {
- mutexUsers.acquire();
- } catch (InterruptedException e) {
- System.exit(-1);
- }
- if (onlineUsers.contains(username)) {
- result = 2;
- }
- mutexUsers.release();
- } else {
- result = -1;
- // password errada
- }
- found = true;
- }
- }
- }
- return result;
- }
- public void run() {
- ObjectOutputStream outStream = null;
- ObjectInputStream inStream = null;
- try {
- outStream = new ObjectOutputStream(socket.getOutputStream());
- inStream = new ObjectInputStream(socket.getInputStream());
- } catch (IOException e) {
- System.err.println("ERRO: Procura de streams do cliente");
- return;
- }
- int res = -1, tentativas = 3;
- String username;
- try {
- do {
- username = (String) inStream.readObject();
- String pass = (String) inStream.readObject();
- outStream.writeObject((res = autenticacao(username, pass)));
- tentativas--;
- } while ((res < 0) && (tentativas > 0));
- if (tentativas == 0) {
- clientExit("ERRO: Utilizador esgotou as suas tentetivas de autenticacao", outStream);
- return;
- }
- try {
- mutexUsers.acquire();
- } catch (InterruptedException e) {
- System.exit(-1);
- }
- if (onlineUsers.contains(username)) {
- clientExit("ERRO(Autenticacao): Tentativa de autenticacao em duas maquinas: " + username,
- outStream);
- }
- mutexUsers.release();
- } catch (IOException | ClassNotFoundException e) {
- clientExit("ERRO(Autenticacao): Escrita/Leitura", outStream);
- return;
- }
- System.out.println("Cliente autenticado: " + username);
- try {
- mutexUsers.acquire();
- } catch (InterruptedException e) {
- System.exit(-1);
- }
- onlineUsers.add(username);
- mutexUsers.release();
- String comando;
- try {
- while (!(comando = (String) inStream.readObject()).equals("-q")) {
- int valid = validCommand(comando, username);
- String[] split = comando.split(" ");
- switch (split[0]) {
- // adiciona/copia estas fotos para o servidor. Caso este utilizador j� tenha
- // alguma foto com o mesmo nome no servidor, o cliente deve retornar um erro.
- case "-a":
- DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
- Date date = new Date();
- String dataEscrita = dateFormat.format(date);
- List<Integer> repetidos = new ArrayList<>();
- // Verifica as fotos repetidas
- for (int i = 1; i < split.length; i++) {
- File ficheiroTexto = new File(USERFOLDER + username + FOTOFOLDER + split[i] + ".txt");
- if (ficheiroTexto.exists()) {
- repetidos.add(i-1);
- }
- }
- outStream.writeObject(repetidos);
- int i = 0;
- // Recebe os ficheiros nao repetidos
- while (++i < split.length) {
- if (!repetidos.contains(i + 1)) {
- String caminho = USERFOLDER + username + FOTOFOLDER + split[i];
- File ficheiroTexto = new File(USERFOLDER + username + FOTOFOLDER + split[i] + ".txt");
- ficheiroTexto.createNewFile();
- BufferedWriter fw = new BufferedWriter(new FileWriter(ficheiroTexto));
- fw.write("0 0 " + dataEscrita);
- fw.newLine();
- fw.close();
- File ficheiroFotosUser = new File(USERFOLDER + username + FICHEIRONOMEFOTOS);
- fw = new BufferedWriter(new FileWriter(ficheiroFotosUser, true));
- fw.write(split[i]);
- fw.newLine();
- fw.close();
- // mensagens de problemas de transmissao ja sao tratados do lado do cliente
- Ferramentas.receiveFile(inStream, outStream, caminho);
- }
- }
- break;
- case "-l":
- if (valid < 0) {
- outStream.writeObject(valid);
- } else {
- List<String> photos = listPhotosByUser(split[1]);
- if (photos == null) {
- outStream.writeObject(-4);
- } else {
- outStream.writeObject(valid);
- outStream.writeObject(photos);
- }
- }
- break;
- case "-i":
- if (valid < 0) {
- outStream.writeObject(valid);
- } else {
- List<String> descricao = photoDescription(split[1], split[2]);
- if (descricao == null) {
- outStream.writeObject(-4);
- } else {
- outStream.writeObject(valid);
- outStream.writeObject(descricao);
- }
- }
- break;
- case "-g":
- outStream.writeObject(valid);
- if (valid >= 0) {
- File[] fotos = (File[]) inStream.readObject();
- int valor = getPictures(split[1], fotos, inStream, outStream);
- if (valor == -100) {
- clientExit("ERRO: Envio de fotos ao utilizador " + username, outStream);
- try {
- mutexUsers.acquire();
- } catch (InterruptedException e) {
- System.exit(-1);
- }
- onlineUsers.remove(username);
- mutexUsers.release();
- return;
- }
- }
- break;
- case "-c":
- String comment = (String) inStream.readObject();
- if (valid < 0) {
- outStream.writeObject(valid);
- } else {
- outStream.writeObject(addComment(split[1], split[2], comment));
- }
- break;
- case "-L":
- if (valid < 0) {
- outStream.writeObject(valid);
- } else {
- outStream.writeObject(likePhoto(split[1], split[2], true));
- }
- break;
- case "-D":
- if (valid < 0) {
- outStream.writeObject(valid);
- } else {
- outStream.writeObject(likePhoto(split[1], split[2], false));
- }
- break;
- case "-f":
- outStream.writeObject(valid);
- if (valid >= 0) {
- ArrayList<String> nomes = new ArrayList<>();
- for (int f = 1; f < split.length; f++) {
- nomes.add(split[f]);
- }
- outStream.writeObject(followUser(nomes, username));
- }
- break;
- case "-r":
- outStream.writeObject(valid);
- if (valid >= 0) {
- List<String> erros = new ArrayList<>();
- for (i = 1; i < split.length; i++) {
- if (!userExists(split[i])) {
- erros.add("-1 " + split[i]);
- } else if (!verifyFollower(split[i], username)) {
- erros.add("-2 " + split[i]);
- } else if (removeFollower(username, split[i]) == -4) {
- erros.add("-4 " + split[i]);
- } else {
- erros.add("0 " + split[i]);
- }
- }
- outStream.writeObject(erros);
- }
- break;
- default:
- System.out.println("Comando errado");
- }
- }
- } catch (ClassNotFoundException | IOException e) {
- clientExit("ERRO: Escrita/Leitura no cliente: " + username, outStream);
- try {
- mutexUsers.acquire();
- } catch (InterruptedException e1) {
- System.exit(-1);
- }
- onlineUsers.remove(username);
- mutexUsers.release();
- return;
- }
- System.out.println("Cliente Saiu: " + username);
- try {
- mutexUsers.acquire();
- } catch (InterruptedException e) {
- System.exit(-1);
- }
- onlineUsers.remove(username);
- mutexUsers.release();
- try {
- outStream.close();
- } catch (IOException e) {
- return;
- }
- }
- /**
- * Metodo para ver se um dado utilizador tem fotos
- *
- * @param username
- * utilizador a verificar
- * @return true se o utilizador tiver fotos
- */
- private boolean hasPhotos(String username) {
- List<String> photos = listPhotosByUser(username);
- if (photos == null || photos.size() == 0)
- return false;
- return true;
- }
- /**
- * Lista fotos por utilizador
- *
- * Metodo que concretiza a flag '-l'
- *
- * @param user
- * nome do utilizador de quem as fotos vao ser listadas
- * @return lista de strings contendo o nome e data de publicacao das fotos pertencentes a user
- */
- private List<String> listPhotosByUser(String user) {
- BufferedReader br;
- ArrayList<String> resultado = null;
- BufferedReader readerFoto = null;
- try {
- br = new BufferedReader(new FileReader(USERFOLDER + user + FICHEIRONOMEFOTOS));
- String fotoAtual = null;
- resultado = new ArrayList<>();
- // Para cada foto
- while ((fotoAtual = br.readLine()) != null) {
- // busca a data
- try {
- readerFoto = new BufferedReader(
- new FileReader(USERFOLDER + user + FOTOFOLDER + fotoAtual + ".txt"));
- } catch (FileNotFoundException e) {
- System.err.println("Ficheiro de dados da foto: " + fotoAtual + " do utilizador " + user
- + " nao encontrado");
- continue;
- }
- String dataFoto;
- dataFoto = readerFoto.readLine().split(" ")[2];
- resultado.add(fotoAtual + " " + dataFoto);
- readerFoto.close();
- }
- br.close();
- } catch (IOException e) {
- return null;
- }
- return resultado;
- }
- /**
- * Gosta de foto
- *
- * Metodo que concretiza as flag '-L' || '-D'
- *
- * @param user
- * nome do utilizador de quem as fotos vao ser alvo de reacao
- * @param photo
- * foto alvo dos likes ou dislikes
- * @param likeordislike
- * true - acrescenta um like || false - acrescenta um dislike
- * @return 0 - se a tudo foi bem sucedido || -3 - ERRO: a foto nao existe || -4
- * - ERRO: erro de input/output
- */
- private int likePhoto(String user, String photo, boolean likeordislike) {
- try {
- if (photoExists(user, photo)) {
- BufferedReader br = new BufferedReader(
- new FileReader(USERFOLDER + user + FOTOFOLDER + photo + ".txt"));
- String line = br.readLine();
- br.close();
- String[] split = line.split(" ");
- if (likeordislike) {
- int actualLikes = Integer.parseInt(split[0]);
- actualLikes++;
- split[0] = actualLikes + "";
- } else {
- int actualLikes = Integer.parseInt(split[1]);
- actualLikes++;
- split[1] = actualLikes + "";
- }
- String res = split[0] + " " + split[1] + " " + split[2];
- return reEscreveInfo(res, USERFOLDER + user + FOTOFOLDER + photo + ".txt");
- } else
- return -3;
- } catch (IOException e) {
- return -4;
- }
- }
- /**
- * Reescreve os dados da foto
- *
- * Altera dados do ficheiro da foto
- *
- * @param res
- * primeira linha do ficheiro da foto
- * @param caminho
- * localizacao no sistema de ficheiros do ficheiro da foto
- * @return -100 - ficheiro nao encontrado || -4 - erro de input/output || 0 -
- * bem sucedido
- */
- private int reEscreveInfo(String res, String caminho) {
- File fich = new File(caminho);
- List<String> tempList = new ArrayList<>();
- BufferedWriter writer = null;
- BufferedReader reader;
- try {
- reader = new BufferedReader(new FileReader(fich));
- String currentLine;
- // Primeira linha nao interessa (dados que vao ser alterados)
- try {
- reader.readLine();
- tempList.add(res);
- while ((currentLine = reader.readLine()) != null) {
- tempList.add(currentLine.trim());
- }
- reader.close();
- writer = new BufferedWriter(new FileWriter(fich));
- for (String line : tempList) {
- writer.write(line);
- writer.newLine();
- }
- } catch (FileNotFoundException e) {
- System.err.println("O sistema nao conseguiu encontrar o ficheiro para reescrever.");
- return -100;
- }
- writer.close();
- } catch (IOException e) {
- return -4;
- }
- return 0;
- }
- /**
- * Adiciona os utilizadores followUserIds como seguidores do utilizador local.
- *
- * @param users
- * nomes dos utilizadores a serem adicionados
- * @param localUser
- * nome do utilizador autenticado
- * @return lista de listas com utilizadores adicionados como seguidores, com
- * utilizadores inexistentes e com utilizadores que jah estao a seguir o
- * localUser
- */
- private ArrayList<ArrayList<String>> followUser(ArrayList<String> users, String localUser) {
- ArrayList<ArrayList<String>> lis_res;
- try {
- lis_res = new ArrayList<>();
- ArrayList<String> errosF = new ArrayList<>(); // indice 1
- ArrayList<String> errosE = new ArrayList<>(); // indice 2
- ArrayList<String> addUsers = new ArrayList<>(); // indice 0
- BufferedWriter bw = new BufferedWriter(
- new FileWriter(USERFOLDER + localUser + FICHEIROFOLLOWERS, true));
- for (int i = 0; i < users.size(); i++) {
- if (userExists(users.get(i))) {
- if (!verifyFollower(users.get(i), localUser)) {
- bw.write(users.get(i));
- bw.newLine();
- addUsers.add(users.get(i));
- } else {
- errosF.add(users.get(i));
- }
- } else {
- errosE.add(users.get(i));
- }
- }
- lis_res.add(addUsers);
- lis_res.add(errosF);
- lis_res.add(errosE);
- bw.close();
- } catch (IOException e) {
- return null;
- }
- return lis_res;
- }
- /**
- * Verifica se o utilizador dado existe
- *
- * @param user
- * nome do utilizador a ser verificado
- * @return true se o user existe no sistema.
- */
- private boolean userExists(String user) {
- return new File(USERFOLDER + user).exists();
- }
- /**
- * Verifica se dada foto existe
- *
- * @param user
- * nome do utilizador a quem a foto pertence
- * @param photo
- * nome da foto a ser verificada
- * @return true - se foto existe || false - c.c.
- */
- private boolean photoExists(String user, String photo) {
- return new File(USERFOLDER + user + FOTOFOLDER + photo).exists();
- }
- /**
- * Verifica se um dado utilizador segue outro utilizador
- *
- * @param userFollower
- * nome do utilizador que segue
- * @param userFollowed
- * nome do utilizador que eh seguido
- * @return true - se userFollower segue userFollowed || false - c.c.
- */
- private boolean verifyFollower(String userFollower, String userFollowed) throws IOException {
- boolean found = false;
- if (userFollower.equals(userFollowed))
- return true;
- File fichFollow = new File(USERFOLDER + userFollowed + FICHEIROFOLLOWERS);
- BufferedReader br = new BufferedReader(new FileReader(fichFollow));
- String currLine = null;
- while ((currLine = br.readLine()) != null && !found) {
- found = currLine.equals(userFollower);
- }
- br.close();
- return found;
- }
- /**
- * Metodo que concretiza flag '-g'
- *
- * @param username
- * nome do utilizador cujas fotos vao ser descarregadas
- * @param fotos
- * fotos do utilizador que vao ser descarregadas
- * @param in
- * fluxo de comunicacao para rececao de informacao do cliente
- * @param out
- * fluxo de comunicacao para transmissao de informacao ao cliente
- * @return -4 - ficheiro de fotos nao encontrado || 0 - acao bem sucedida
- */
- private int getPictures(String username, File[] fotos, ObjectInputStream in, ObjectOutputStream out) {
- File pathUsername = new File(USERFOLDER + username + FOTOFOLDER);
- List<String> fotosAtuais = listPhotosByUser(username);
- if (fotosAtuais == null) {
- return -100;
- }
- try {
- // fotos ja existentes
- if (fotos != null) {
- for (File f : fotos) {
- String nomeF = f.getName();
- fotosAtuais.remove(nomeF);
- List<String> comments;
- comments = getComments(username, nomeF);
- if (comments.size() != 0 && comments.get(0).equals(ERRO)) {
- return -100;
- }
- out.writeObject(comments);
- }
- }
- // fotos nao existentes
- out.writeObject(fotosAtuais);
- for (String ficheiro : fotosAtuais) {
- ficheiro = ficheiro.split(" ")[0];
- String txt = ficheiro + ".txt";
- String pathUserfoto = pathUsername.getAbsolutePath() + SEPARADOR + ficheiro;
- Ferramentas.sendFile(out, in, pathUserfoto);
- List<String> comments = getComments(username, txt);
- out.writeObject(comments);
- }
- } catch (IOException e) {
- return -100;
- }
- return 0;
- }
- /**
- * Metodo que concretiza a flag '-r'
- *
- * @param username
- * nome do utilizador de quem vao ser removidos seguidores
- * @param follower
- * nome do seguidor a ser removido
- * @return -4 - erro de Input/Output || -1 - ficheiro de seguidores nao encontrado || 0 - acao bem
- * sucedida
- */
- private int removeFollower(String username, String follower) {
- File caminhoFollowers = new File(USERFOLDER + username + FICHEIROFOLLOWERS);
- List<String> temp = new ArrayList<>();
- BufferedReader reader = null;
- BufferedWriter writer = null;
- try {
- reader = new BufferedReader(new FileReader(caminhoFollowers));
- } catch (FileNotFoundException e) {
- System.err.println("Ficheiro de seguidores nao encontrado");
- return -100;
- }
- String currentLine;
- try {
- while ((currentLine = reader.readLine()) != null) {
- String trimmedLine = currentLine.trim();
- if (!trimmedLine.equals(follower)) {
- temp.add(currentLine);
- }
- }
- reader.close();
- writer = new BufferedWriter(new FileWriter(caminhoFollowers));
- for (String line : temp) {
- writer.write(line);
- writer.newLine();
- }
- writer.close();
- } catch (IOException e) {
- return -4;
- }
- return 0;
- }
- /**
- * Metodo que concretiza a flag '-i'
- *
- * @param username
- * nome do utilizador a quem a foto pertence
- * @param foto
- * foto da qual a descricao vai ser dada
- * @return lista com a caracteristicas de foto pertencente a username
- */
- private List<String> photoDescription(String username, String foto) {
- List<String> result = new ArrayList<String>();
- File pathFoto = new File(USERFOLDER + username + FOTOFOLDER + foto + ".txt");
- BufferedReader br = null;
- try {
- br = new BufferedReader(new FileReader(pathFoto));
- // likes, dislikes, data
- String[] dados;
- dados = br.readLine().split(" ");
- result.add("Likes: " + dados[0]);
- result.add("Dislikes: " + dados[1]);
- result.add("Data de publicacao: " + dados[2]);
- String linha;
- int i = 1;
- while ((linha = br.readLine()) != null) {
- result.add("[" + i++ + "]: " + linha);
- }
- br.close();
- } catch (IOException e) {
- return null;
- }
- return result;
- }
- /**
- * Imprime uma mensagem de erro, denota a saida de um cliente e fecha a socket de comunicacao
- * @param msgErr - mensagem de erro
- * @param out - canal de comunicacao
- */
- private void clientExit(String msgErr, ObjectOutputStream out) {
- System.err.println(msgErr);
- System.out.println("Saiu um cliente");
- try {
- out.close();
- } catch (IOException e) {
- return;
- }
- }
- /**
- * Metodo que concretiza a flag '-c'
- *
- * @param username
- * nome do utilizador cuja foto vai ser comentada
- * @param foto
- * foto a ser comentada
- * @param comentario
- * comentario a acrescentar a foto
- * @return -4 - foto nao encontrada || 0 - acao bem sucedida
- */
- private int addComment(String username, String foto, String comentario) {
- File pathFoto = new File(USERFOLDER + username + FOTOFOLDER + foto + ".txt");
- BufferedWriter bw;
- try {
- bw = new BufferedWriter(new FileWriter(pathFoto, true));
- bw.write(comentario);
- bw.newLine();
- bw.close();
- } catch (IOException e) {
- return -4;
- }
- return 0;
- }
- /**
- * Devolve comentarios de uma dada foto
- *
- * @param username
- * nome do utilizador a quem a foto pertence
- * @param nomeFoto
- * nome da foto cujos comentarios vao ser devolvidos
- * @return lista de comentarios da foto dada pertencente a username
- */
- private List<String> getComments(String username, String nomeFoto) {
- List<String> result = new ArrayList<>();
- File ficheiroPath = new File(USERFOLDER + username + FOTOFOLDER + nomeFoto);
- BufferedReader br = null;
- try {
- br = new BufferedReader(new FileReader(ficheiroPath));
- } catch (FileNotFoundException e) {
- System.err.println("Ficheiro de fotos nao encontrado");
- result.add(ERRO);
- return result;
- }
- try {
- br.readLine();
- String linha;
- while ((linha = br.readLine()) != null) {
- result.add(linha);
- }
- br.close();
- } catch (IOException e) {
- return null;
- }
- return result;
- }
- /**
- * Metodo que valida o numero de argumentos introduzidos para cada comando e
- * verifica todas as possibilidades de erro antes da execucao do comando
- *
- * @param command
- * comando que vai ser executado
- * @param username
- * nome do utilizador sobre o qual vai ser executado o comando
- * @return inteiro equivalente ao codigo de erro, 0 se nao tem nenhum erro
- */
- private int validCommand(String command, String username) {
- int result = 0;
- if (command == null) {
- return result;
- } else {
- try {
- String[] split = command.split(" ");
- switch (split[0]) {
- case "-q":
- if (split.length != 1) {
- result = -7;
- }
- break;
- case "-a":
- if (split.length < 2) {
- result = -7;
- }
- break;
- case "-l":
- if (split.length != 2) {
- result = -7;
- } else if (!userExists(split[1])) {
- result = -1;
- } else if (!verifyFollower(username, split[1])) {
- result = -2;
- } else if (!hasPhotos(split[1])) {
- result = -6;
- }
- break;
- case "-i":
- if (split.length != 3) {
- result = -7;
- } else if (!userExists(split[1])) {
- result = -1;
- } else if (!verifyFollower(username, split[1])) {
- result = -2;
- } else if (!hasPhotos(split[1])) {
- result = -6;
- } else if (!photoExists(split[1], split[2])) {
- result = -3;
- }
- break;
- case "-g":
- if (split.length != 2) {
- result = -7;
- }
- if (!userExists(split[1])) {
- result = -1;
- } else if (!verifyFollower(username, split[1])) {
- result = -2;
- } else if (!hasPhotos(split[1])) {
- result = -6;
- }
- break;
- case "-c":
- if (split.length != 3) {
- result = -7;
- }
- if (!userExists(split[1])) {
- result = -1;
- } else if (!verifyFollower(username, split[1])) {
- result = -2;
- } else if (!hasPhotos(split[1])) {
- result = -6;
- } else if (!photoExists(split[1], split[2])) {
- result = -3;
- }
- break;
- case "-L":
- if (split.length != 3) {
- result = -7;
- }
- if (!userExists(split[1])) {
- result = -1;
- } else if (!verifyFollower(username, split[1])) {
- result = -2;
- } else if (!hasPhotos(split[1])) {
- result = -6;
- } else if (!photoExists(split[1], split[2])) {
- result = -3;
- }
- break;
- case "-D":
- if (split.length != 3) {
- result = -7;
- }
- if (!userExists(split[1])) {
- result = -1;
- } else if (!verifyFollower(username, split[1])) {
- result = -2;
- } else if (!hasPhotos(split[1])) {
- result = -6;
- } else if (!photoExists(split[1], split[2])) {
- result = -3;
- }
- break;
- case "-f":
- if (split.length < 2) {
- result = -7;
- }
- break;
- case "-r":
- if (split.length < 2) {
- result = -7;
- }
- break;
- default:
- System.err.println("ERRO: Comando introduzido invalido!");
- result = -7;
- }
- } catch (IOException e) {
- result = -4;
- }
- return result;
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement