From 151b1ea36fb7dd972937c45298cd7fc879ac1d01 Mon Sep 17 00:00:00 2001 From: PiterOfc Date: Wed, 28 May 2025 12:30:21 -0300 Subject: [PATCH 01/33] Feat: implement user management in the file system and mkdir --- Main.java | 30 ++++++--- filesys/FileSystem.java | 6 ++ filesys/FileSystemImpl.java | 122 +++++++++++++++++++++++++++++++++++- filesys/IFileSystem.java | 2 +- filesys/Usuario.java | 30 +++++++++ run.bat | 2 + 6 files changed, 181 insertions(+), 11 deletions(-) create mode 100644 filesys/Usuario.java create mode 100644 run.bat diff --git a/Main.java b/Main.java index 3b8673a..f65a5d6 100644 --- a/Main.java +++ b/Main.java @@ -1,5 +1,8 @@ import filesys.IFileSystem; +import filesys.Usuario; +import java.util.ArrayList; +import java.util.List; import java.util.Scanner; import java.io.FileNotFoundException; @@ -29,6 +32,9 @@ public class Main { // Usuário que está executando o programa private static String user; + // Lista de usuários + private static List usuarios = new ArrayList<>(); + // O sistema de arquivos é inteiramente virtual, ou seja, será reiniciado a cada execução do programa. // Logo, não é necessário salvar os arquivos em disco. O sistema será uma simulação em memória. public static void main(String[] args) { @@ -68,7 +74,8 @@ public static void main(String[] args) { */ System.out.println(userListed + " " + dir + " " + dirPermission); // Somente imprime o usuário, diretório e permissão - + // Adicionar usuário à lista + usuarios.add(new Usuario(userListed, dir, dirPermission)); } else { System.out.println("Formato ruim no arquivo de usuários. Linha: " + line); } @@ -80,19 +87,24 @@ public static void main(String[] args) { return; } - + + System.out.println("Usuários carregados:"); + for (Usuario user : usuarios) { + System.out.println(user); + } + // Finalmente cria o Sistema de Arquivos // Lista de usuários é imutável durante a execução do programa // Obs: Como passar a lista de usuários para o FileSystem? - fileSystem = new FileSystem(/*usuários?*/); + fileSystem = new FileSystem(usuarios, user); // // DESCOMENTE O BLOCO ABAIXO PARA CRIAR O DIRETÓRIO RAIZ ANTES DE RODAR O MENU - // // Cria o diretório raiz do sistema. Root sempre tem permissão total "rwx" - // try { - // fileSystem.mkdir(ROOT_DIR, ROOT_USER); - // } catch (CaminhoJaExistenteException | PermissaoException e) { - // System.out.println(e.getMessage()); - // } + // Cria o diretório raiz do sistema. Root sempre tem permissão total "rwx" + try { + fileSystem.mkdir(ROOT_DIR, ROOT_USER); + } catch (CaminhoJaExistenteException | PermissaoException e) { + System.out.println(e.getMessage()); + } // Menu interativo. menu(); diff --git a/filesys/FileSystem.java b/filesys/FileSystem.java index 8d7a83b..45637ca 100644 --- a/filesys/FileSystem.java +++ b/filesys/FileSystem.java @@ -1,5 +1,7 @@ package filesys; +import java.util.List; + import exception.CaminhoJaExistenteException; import exception.CaminhoNaoEncontradoException; import exception.PermissaoException; @@ -13,6 +15,10 @@ public FileSystem() { fileSystemImpl = new FileSystemImpl(); } + public FileSystem(List usuarios, String user) { + fileSystemImpl = new FileSystemImpl(usuarios, user); + } + @Override public void chmod(String caminho, String usuario, String usuarioAlvo, String permissao) throws CaminhoNaoEncontradoException, PermissaoException { diff --git a/filesys/FileSystemImpl.java b/filesys/FileSystemImpl.java index 45fa05d..6c84a3c 100644 --- a/filesys/FileSystemImpl.java +++ b/filesys/FileSystemImpl.java @@ -1,9 +1,17 @@ package filesys; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + import exception.CaminhoJaExistenteException; import exception.CaminhoNaoEncontradoException; import exception.PermissaoException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; + // Implemente nesta classe o seu código do FileSystem. // A classe pode ser alterada. // O construtor, argumentos do construtor podem ser modificados @@ -11,11 +19,123 @@ public final class FileSystemImpl implements IFileSystem { private static final String ROOT_USER = "root"; // pode ser necessário + private List usuarios; + private String user; + private Map> permissoesPorCaminho = new HashMap<>(); + public FileSystemImpl() {} + public FileSystemImpl(List usuarios, String user) { + if (usuarios == null) { + throw new IllegalArgumentException("Lista de usuários não pode ser nula"); + } + this.usuarios = usuarios; + + if (user == null) { + throw new IllegalArgumentException("Usuário atual não recebido"); + } + this.user = user; + } + @Override public void mkdir(String caminho, String nome) throws CaminhoJaExistenteException, PermissaoException { - throw new UnsupportedOperationException("Método não implementado 'mkdir'"); + // throw new UnsupportedOperationException("Método não implementado 'mkdir'"); + if (caminho == null || nome == null) { + throw new IllegalArgumentException("Caminho e nome não podem ser nulos"); + } + if (caminho.isEmpty() || nome.isEmpty()) { + throw new IllegalArgumentException("Caminho e nome não podem ser vazios"); + } + + // Aqui você deve implementar a lógica para criar um diretório + // Verifique se o caminho existe e se o usuário tem permissão para criar o diretório + // Se o diretório já existir, lance CaminhoJaExistenteException + // Se o caminho não existir, lance CaminhoNaoEncontradoException + // Se o usuário não tiver permissão, lance PermissaoException + + // OBS: o contrato para esta interface exige que caminhos intermediários sejam criados por padrão durante a chamada à mkdir. É como se a flag '-p' fosse passada por padrão na nossa interface: + /* + -p Create intermediate directories as required. If this option is not specified, + the full path prefix of each operand must already exist. On the other hand, + with this option specified, no error will be reported if a directory given as + an operand already exists. Intermediate directories are created with + permission bits of “rwxrwxrwx” (0777) as modified by the current umask, plus + write and search permission for the owner. + */ + + // Verifique se o diretório já existe + if (diretorioExiste(caminho + nome)) { + throw new CaminhoJaExistenteException("Diretório já existe: " + caminho + nome); + } + + // Verificar se o usuário tem permissão para criar o diretório + if (!usuarioPodeCriarDiretorio(caminho, nome)) { + throw new PermissaoException("Usuário não tem permissão para criar diretório na raiz: " + nome); + } + + if (caminho.equals("/")) { + // Criar diretório na raiz + criarDiretorioNaRaiz(nome); + } else { + // Verifique se o caminho existe + if (!caminhoExiste(caminho)) { + throw new IllegalStateException("Caminho não encontrado: " + caminho); + } + // Criar diretório no caminho especificado + criarDiretorioNoCaminho(caminho, nome); + } + + } + + private boolean caminhoExiste(String caminho) { + Path path = Paths.get(caminho); + return Files.exists(path); + } + + private boolean diretorioExiste(String caminho) { + Path path = Paths.get(caminho); + return Files.isDirectory(path); + } + + private void criarDiretorioNaRaiz(String nome) { + Path path = Paths.get("/" + nome); + try { + Files.createDirectory(path); + } catch (Exception e) { + throw new RuntimeException("Erro ao criar diretório na raiz: " + e.getMessage(), e); + } + } + + private void criarDiretorioNoCaminho(String caminho, String nome) { + Path path = Paths.get(caminho, nome); + try { + Files.createDirectories(path); // Cria o diretório e quaisquer diretórios intermediários necessários + } catch (Exception e) { + throw new RuntimeException("Erro ao criar diretório no caminho: " + e.getMessage(), e); + } + } + + public boolean usuarioPodeCriarDiretorio(String caminho, String nome) { + // Verifica se o usuário atual tem permissão para criar no diretório + Usuario usuarioAtual = getUsuarioAtual(); // Método fictício para obter o usuário atual + // Pega as permissões do usuário atual + String permissoes = usuarioAtual.getPermissoes(); + + // Verifica se o usuário é root ou se tem permissão de escrita + if (ROOT_USER.equals(usuarioAtual.getNome()) || permissoes.contains("w")) { + return true; // Usuário root ou tem permissão de escrita + } + + return false; // Usuário não tem permissão + } + + private Usuario getUsuarioAtual() { + for (Usuario usuario : usuarios) { + if (usuario.getNome().equals(user)) { + return usuario; + } + } + throw new IllegalArgumentException("Usuário não encontrado: " + user); } @Override diff --git a/filesys/IFileSystem.java b/filesys/IFileSystem.java index a0f0ce0..06e1738 100644 --- a/filesys/IFileSystem.java +++ b/filesys/IFileSystem.java @@ -5,7 +5,7 @@ import exception.PermissaoException; // Apenas modifique essa interface caso seja EXTREMAMENTE necessário. -// Documente & Justifique TODAS asalterações feitas. +// Documente & Justifique TODAS as alterações feitas. public interface IFileSystem { // Altera as permissões de um arquivo ou diretório. // Configura a permissao do caminho para o usuarioAlvo. diff --git a/filesys/Usuario.java b/filesys/Usuario.java new file mode 100644 index 0000000..6d8deb5 --- /dev/null +++ b/filesys/Usuario.java @@ -0,0 +1,30 @@ +package filesys; + +public class Usuario { + private String nome; + private String diretorio; + private String permissoes; + + public Usuario(String nome, String diretorio, String permissoes) { + this.nome = nome; + this.diretorio = diretorio; + this.permissoes = permissoes; + } + + public String getNome() { + return nome; + } + + public String getDiretorio() { + return diretorio; + } + + public String getPermissoes() { + return permissoes; + } + + @Override + public String toString() { + return nome + " " + diretorio + " " + permissoes; + } +} \ No newline at end of file diff --git a/run.bat b/run.bat new file mode 100644 index 0000000..06f7fdd --- /dev/null +++ b/run.bat @@ -0,0 +1,2 @@ +java .\Main.java -u "root" +Pause \ No newline at end of file From 607424732370a6e7c2b492c427c25dd4873913f1 Mon Sep 17 00:00:00 2001 From: PiterOfc Date: Sun, 1 Jun 2025 16:49:18 -0300 Subject: [PATCH 02/33] Feat: refatorar sistema de arquivos e adicionar classe de bloco de dados --- Main.java | 5 +- filesys/BlocoDeDados.java | 29 ++++++ filesys/Dir.java | 191 ++++++++++++++++++++++++++++++++++++ filesys/File.java | 119 ++++++++++++++++++++++ filesys/FileSystem.java | 4 +- filesys/FileSystemImpl.java | 45 +++++---- 6 files changed, 370 insertions(+), 23 deletions(-) create mode 100644 filesys/BlocoDeDados.java create mode 100644 filesys/Dir.java create mode 100644 filesys/File.java diff --git a/Main.java b/Main.java index f65a5d6..dc4a268 100644 --- a/Main.java +++ b/Main.java @@ -88,15 +88,17 @@ public static void main(String[] args) { return; } + /* REMOVER ISSO PQ NÃO PRECISA System.out.println("Usuários carregados:"); for (Usuario user : usuarios) { System.out.println(user); } + */ // Finalmente cria o Sistema de Arquivos // Lista de usuários é imutável durante a execução do programa // Obs: Como passar a lista de usuários para o FileSystem? - fileSystem = new FileSystem(usuarios, user); + fileSystem = new FileSystem(usuarios); // // DESCOMENTE O BLOCO ABAIXO PARA CRIAR O DIRETÓRIO RAIZ ANTES DE RODAR O MENU // Cria o diretório raiz do sistema. Root sempre tem permissão total "rwx" @@ -222,6 +224,7 @@ public static void write() throws CaminhoNaoEncontradoException, PermissaoExcept fileSystem.write(caminho, user, anexar, buffer); } + // Read foi modificado public static void read() throws CaminhoNaoEncontradoException, PermissaoException { System.out.println("Insira o caminho do arquivo a ser lido:"); String caminho = scanner.nextLine(); diff --git a/filesys/BlocoDeDados.java b/filesys/BlocoDeDados.java new file mode 100644 index 0000000..88205c3 --- /dev/null +++ b/filesys/BlocoDeDados.java @@ -0,0 +1,29 @@ +package filesys; + +public class BlocoDeDados { + private byte[] dados; // Dados do bloco + + // Construtores + public BlocoDeDados() { + this.dados = new byte[File.TAMANHO_BYTES_BLOCO]; // Inicializa o bloco com o tamanho especificado + } + + public BlocoDeDados(byte[] dados) { + setDados(dados); + } + + + // Dados + public byte[] getDados() { + return dados; + } + + public void setDados(byte[] dados) { + if (dados.length <= File.TAMANHO_BYTES_BLOCO) { + this.dados = new byte[dados.length]; + System.arraycopy(dados, 0, this.dados, 0, dados.length); // Copia os novos dados para o bloco + } else { + throw new IllegalArgumentException("Dados excedem o tamanho do bloco."); + } + } +} diff --git a/filesys/Dir.java b/filesys/Dir.java new file mode 100644 index 0000000..cfadeef --- /dev/null +++ b/filesys/Dir.java @@ -0,0 +1,191 @@ +package filesys; + +import java.util.HashMap; +import java.util.Map; + +public class Dir { + // Atributos + private String nome; + private String dono; + private String permissoes; + + // Relacionamentos + protected Dir pai; + protected Map filhos; + private Map permissoesUsuarios; + + // Construtor + public Dir(String nome, String dono, String permissoes) { + this.nome = nome; + this.dono = dono; + this.permissoes = permissoes; + + this.pai = null; // Inicialmente, o diretório não tem pai + this.filhos = new HashMap<>(); + this.permissoesUsuarios = new HashMap<>(); + + // Define as permissões iniciais para o dono do diretório + this.permissoesUsuarios.put(dono, "rwx"); // O dono tem permissão total + } + + // Nome + public String getNome() { + return nome; + } + + public void setNome(String nome) { + this.nome = nome; + } + + + // Dono + public String getDono() { + return dono; + } + + public void setDono(String dono) { + this.dono = dono; + } + + + // Permissões + public String getPermissoes() { + return permissoes; + } + + public void setPermissoes(String permissoes) { + this.permissoes = permissoes; + } + + + // Pai + public Dir getPai() { + return pai; + } + + public void setPai(Dir pai) { + this.pai = pai; + } + + + // Filhos + public Map getFilhos() { + return filhos; + } + + public Dir getFilho(String nome) { + return filhos.get(nome); + } + + public void setFilhos(Map filhos) { + this.filhos = filhos; + for (Dir filho : filhos.values()) { + filho.setPai(this); // Define o pai de cada filho + } + } + + public void addFilho(Dir filho) { + filhos.put(filho.getNome(), filho); + filho.setPai(this); // Define o pai do filho + } + + public void removeFilho(String nome) { + filhos.remove(nome); + } + + + // Permissões dos usuários + public Map getPermissoesUsuarios() { + return permissoesUsuarios; + } + + public String getPermissoesUsuario(String usuario) { + if ("root".equals(usuario)) return "rwx"; // O usuário root sempre tem permissão total + + // Verifica se o usuário é nulo ou vazio + if (usuario == null || usuario.isEmpty()) { + throw new IllegalArgumentException("Usuário não pode ser nulo ou vazio"); + } + + // Verifica se o usuário tem permissões definidas + if (!permissoesUsuarios.containsKey(usuario)) { + throw new IllegalArgumentException("Usuário não encontrado: " + usuario); + } + + if (dono.equals(usuario)) return permissoes; // O dono do diretório tem as permissões do diretório + + return permissoesUsuarios.getOrDefault(usuario, "---"); // Retorna as permissões do usuário ou um padrão se não tiver + } + + public void setPermissoesUsuario(String usuario, String permissoes) { + if (permissoes == null || permissoes.length() != 3) { + throw new IllegalArgumentException("As permissões precisam ter 3 caracteres"); + } + + this.permissoesUsuarios.put(usuario, permissoes); + } + + + // Verifica se o usuário tem permissão para acessar o diretório + public boolean temPerm(String usuario, String permissao) { + // Verifica se o usuário é nulo ou vazio + if (usuario == null || usuario.isEmpty()) { + throw new IllegalArgumentException("Usuário não pode ser nulo ou vazio"); + } + + if ("root".equals(usuario)) { + return true; // O dono do diretório sempre tem permissão total + } + + if (usuario.equals(dono)) { + return true; // O dono do diretório sempre tem permissão total + } + + // Verifica se a permissão é nula ou vazia + if (permissao == null || permissao.isEmpty()) { + throw new IllegalArgumentException("Permissão não pode ser nula ou vazia"); + } + + // Verifica se o usuário tem permissões definidas + if (!permissoesUsuarios.containsKey(usuario)) { + throw new IllegalArgumentException("Usuário não encontrado nas permissões: " + usuario); + } + + String permissoesUsuario = getPermissoesUsuario(usuario); + + // Verifica se o usuário tem a permissão solicitada + if (permissoesUsuario.contains(permissao)) { + return true; // O usuário tem a permissão solicitada + } + + // Se não tiver a permissão solicitada, verifica permissões do diretório pai + if (pai != null) { + return pai.temPerm(usuario, permissao); // Verifica no diretório pai + } + + // Se não, o usuário não tem permissão + return false; + } + + + // É um arquivo? + public boolean isArquivo() { + return false; // Esta classe representa um diretório, não um arquivo + } + + + // Transformando em string + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + + sb.append("Diretório: ").append(nome) + .append(", Dono: ").append(dono) + .append(", Permissões: ").append(permissoes) + .append(", Pai: ").append(pai != null ? pai.getNome() : "Nenhum") + .append(", Filhos: ").append(getFilhos().keySet()) + .append(", Permissões dos usuários: ").append(permissoesUsuarios); + + return sb.toString(); + } +} diff --git a/filesys/File.java b/filesys/File.java new file mode 100644 index 0000000..1bc7da3 --- /dev/null +++ b/filesys/File.java @@ -0,0 +1,119 @@ +package filesys; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +public class File extends Dir { + public static final int TAMANHO_BYTES_BLOCO = 1024; // Tamanho do arquivo em bytes + + // Atributos específicos de um arquivo + private List blocos; // Lista de blocos de dados que compõem o arquivo + private long tamanho; // Tamanho atual do arquivo em bytes + + // Construtor + public File(String nome, String dono, String permissoes) { + super(nome, dono, permissoes); + + this.blocos = new ArrayList<>(); + this.tamanho = 0; + + this.pai = null; + this.filhos = null; // Um arquivo não pode ter filhos, então setamos como null + } + + // Blocos + public List getBlocos() { + return blocos; + } + + public void setBlocos(List blocos) { + this.blocos = blocos; + this.tamanho = blocos.stream().mapToLong(bloco -> bloco.getDados().length).sum(); // Atualiza o tamanho do arquivo + } + + public void addBloco(BlocoDeDados bloco) { + this.blocos.add(bloco); + this.tamanho += bloco.getDados().length; // Atualiza o tamanho do arquivo + } + + public void removeBloco(BlocoDeDados bloco) { + if (this.blocos.remove(bloco)) { + this.tamanho -= bloco.getDados().length; // Atualiza o tamanho do arquivo + } + } + + public void clearBlocos() { + this.blocos.clear(); + this.tamanho = 0; // Reseta o tamanho do arquivo + } + + + // Tamanho + public long getTamanho() { + return tamanho; + } + + public void setTamanho(long tamanho) { + this.tamanho = tamanho; + } + + public void addTamanho(long tamanho) { + this.tamanho += tamanho; + } + + public void removeTamanho(long tamanho) { + this.tamanho -= tamanho; + if (this.tamanho < 0) { + this.tamanho = 0; // Garante que o tamanho não fique negativo + } + } + + + // É um arquivo? + @Override + public boolean isArquivo() { + return true; // Essa classe representa um diretório do tipo arquivo + } + + + // Filhos + @Override + public Dir getFilho(String nome) { + throw new UnsupportedOperationException("Um arquivo não tem filhos."); + } + + @Override + public Map getFilhos() { + throw new UnsupportedOperationException("Um arquivo não tem filhos."); + } + + @Override + public void setFilhos(Map filhos) { + throw new UnsupportedOperationException("Um arquivo não pode ter filhos."); + } + + @Override + public void addFilho(Dir filho) { + throw new UnsupportedOperationException("Um arquivo não pode ter filhos."); + } + + @Override + public void removeFilho(String nome) { + throw new UnsupportedOperationException("Um arquivo não tem filhos."); + } + + + // Transformando em string + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + + sb.append("Arquivo: ").append(getNome()) + .append(", Dono: ").append(getDono()) + .append(", Permissões: ").append(getPermissoes()) + .append(", Tamanho: ").append(tamanho).append(" bytes") + .append(", Blocos: ").append(blocos.size()); + return sb.toString(); + } +} diff --git a/filesys/FileSystem.java b/filesys/FileSystem.java index 45637ca..5abc4e5 100644 --- a/filesys/FileSystem.java +++ b/filesys/FileSystem.java @@ -15,8 +15,8 @@ public FileSystem() { fileSystemImpl = new FileSystemImpl(); } - public FileSystem(List usuarios, String user) { - fileSystemImpl = new FileSystemImpl(usuarios, user); + public FileSystem(List usuarios) { + fileSystemImpl = new FileSystemImpl(usuarios); } @Override diff --git a/filesys/FileSystemImpl.java b/filesys/FileSystemImpl.java index 6c84a3c..90bcff9 100644 --- a/filesys/FileSystemImpl.java +++ b/filesys/FileSystemImpl.java @@ -1,5 +1,6 @@ package filesys; +import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; @@ -17,26 +18,25 @@ // O construtor, argumentos do construtor podem ser modificados // e atributos & métodos privados podem ser adicionados public final class FileSystemImpl implements IFileSystem { - private static final String ROOT_USER = "root"; // pode ser necessário + private static final String ROOT_USER = "root"; - private List usuarios; - private String user; - private Map> permissoesPorCaminho = new HashMap<>(); + private List usuarios = new ArrayList<>(); + private Dir raiz; // Diretório raiz - public FileSystemImpl() {} + public FileSystemImpl() { + this.raiz = new Dir("/", ROOT_USER, "rwx"); + usuarios.add(new Usuario(ROOT_USER, "/", "rwx")); // Adiciona o usuário root com permissões totais + } - public FileSystemImpl(List usuarios, String user) { - if (usuarios == null) { + public FileSystemImpl(List usuarios) { + if (usuarios.isEmpty()) { throw new IllegalArgumentException("Lista de usuários não pode ser nula"); } - this.usuarios = usuarios; - if (user == null) { - throw new IllegalArgumentException("Usuário atual não recebido"); - } - this.user = user; + this.usuarios = usuarios; } + /* @Override public void mkdir(String caminho, String nome) throws CaminhoJaExistenteException, PermissaoException { // throw new UnsupportedOperationException("Método não implementado 'mkdir'"); @@ -54,14 +54,12 @@ public void mkdir(String caminho, String nome) throws CaminhoJaExistenteExceptio // Se o usuário não tiver permissão, lance PermissaoException // OBS: o contrato para esta interface exige que caminhos intermediários sejam criados por padrão durante a chamada à mkdir. É como se a flag '-p' fosse passada por padrão na nossa interface: - /* - -p Create intermediate directories as required. If this option is not specified, - the full path prefix of each operand must already exist. On the other hand, - with this option specified, no error will be reported if a directory given as - an operand already exists. Intermediate directories are created with - permission bits of “rwxrwxrwx” (0777) as modified by the current umask, plus - write and search permission for the owner. - */ + // -p Create intermediate directories as required. If this option is not specified, + // the full path prefix of each operand must already exist. On the other hand, + // with this option specified, no error will be reported if a directory given as + // an operand already exists. Intermediate directories are created with + // permission bits of “rwxrwxrwx” (0777) as modified by the current umask, plus + // write and search permission for the owner. // Verifique se o diretório já existe if (diretorioExiste(caminho + nome)) { @@ -137,6 +135,13 @@ private Usuario getUsuarioAtual() { } throw new IllegalArgumentException("Usuário não encontrado: " + user); } + */ + + @Override + public void mkdir(String caminho, String usuario) + throws CaminhoJaExistenteException, PermissaoException { + throw new UnsupportedOperationException("Método não implementado 'chmod'"); + } @Override public void chmod(String caminho, String usuario, String usuarioAlvo, String permissao) From 555030354597f9de8d949472948ca716754f8a9e Mon Sep 17 00:00:00 2001 From: PiterOfc Date: Mon, 9 Jun 2025 19:19:45 -0300 Subject: [PATCH 03/33] Implementando mkdir --- filesys/FileSystemImpl.java | 48 ++++++++++++++++++++++++++++++++++--- 1 file changed, 45 insertions(+), 3 deletions(-) diff --git a/filesys/FileSystemImpl.java b/filesys/FileSystemImpl.java index 90bcff9..5a3c4ea 100644 --- a/filesys/FileSystemImpl.java +++ b/filesys/FileSystemImpl.java @@ -138,9 +138,51 @@ private Usuario getUsuarioAtual() { */ @Override - public void mkdir(String caminho, String usuario) - throws CaminhoJaExistenteException, PermissaoException { - throw new UnsupportedOperationException("Método não implementado 'chmod'"); + public void mkdir(String caminho, String usuario) throws CaminhoJaExistenteException, PermissaoException { + if (caminho.equals("/")) { + throw new UnsupportedOperationException("Não é possível criar diretório raiz pois ele já existe."); + } + if (caminho == null || usuario == null) { + throw new IllegalArgumentException("Caminho e usuário não podem ser nulos"); + } + + // Separar caminho em partes + String[] partes = caminho.split("/"); + Dir diretorioAtual = raiz; // Começa no diretório raiz + StringBuilder caminhoAtual = new StringBuilder("/"); + + for (String parte : partes) { + if (parte.isEmpty()) { + continue; // Ignora partes vazias (por exemplo, quando o caminho começa com '/') + } + caminhoAtual.append(parte).append("/"); + + // Verifica se o diretório já existe + if (diretorioAtual.getFilhos().containsKey(parte)) { + if (diretorioAtual.getFilhos().get(parte).isArquivo()) { + throw new CaminhoJaExistenteException("Caminho já existe como arquivo: " + caminhoAtual); + } + + diretorioAtual = diretorioAtual.getFilhos().get(parte); // Ir para o diretório existente + throw new CaminhoJaExistenteException("Diretório já existe: " + caminhoAtual); + } + + // Verifica se o usuário existe + usuarios.stream() + .filter(u -> u.getNome().equals(usuario)) + .findFirst() + .orElseThrow(() -> new IllegalArgumentException("Usuário não encontrado: " + usuario)); + + // Verifica se o usuário tem permissão para criar o diretório + if (!diretorioAtual.getPermissoesUsuario(usuario).contains("w")) { + throw new PermissaoException("Usuário não tem permissão para criar diretório: " + caminhoAtual); + } + + // Cria o novo diretório + Dir novoDiretorio = new Dir(parte, usuario, "rwx"); + diretorioAtual.addFilho(novoDiretorio); + diretorioAtual = novoDiretorio; // Move para o novo diretório criado + } } @Override From 57d1f1a4c94517f0cb6303d91bc616192703b7bf Mon Sep 17 00:00:00 2001 From: PiterOfc Date: Mon, 9 Jun 2025 20:01:03 -0300 Subject: [PATCH 04/33] =?UTF-8?q?Fix:=20script=20r=C3=A1pido=20para=20inic?= =?UTF-8?q?iar=20programa?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- run.bat | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/run.bat b/run.bat index 06f7fdd..1861aea 100644 --- a/run.bat +++ b/run.bat @@ -1,2 +1,12 @@ -java .\Main.java -u "root" -Pause \ No newline at end of file +@echo off +echo. + +echo Compilando programa... +javac Main.java + +echo Rodando programa... +timeout 3 +cls + +java Main -u "root" +pause \ No newline at end of file From 406b78ab94feda06071819f9140ffa44cbcd9950 Mon Sep 17 00:00:00 2001 From: PiterOfc Date: Mon, 9 Jun 2025 20:07:32 -0300 Subject: [PATCH 05/33] =?UTF-8?q?Fix:=20mandando=20arquivos=20de=20compila?= =?UTF-8?q?=C3=A7=C3=A3o=20pra=20pasta=20bin?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- run.bat | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/run.bat b/run.bat index 1861aea..1c840f2 100644 --- a/run.bat +++ b/run.bat @@ -1,12 +1,15 @@ @echo off echo. +echo Criando pasta bin... +mkdir bin 2>nul + echo Compilando programa... -javac Main.java +javac -d bin Main.java echo Rodando programa... -timeout 3 +timeout /t 3 cls -java Main -u "root" -pause \ No newline at end of file +java -cp bin Main -u "root" +pause From 1576f7c952b23bd031703286352ebd3b240e1408 Mon Sep 17 00:00:00 2001 From: PiterOfc Date: Mon, 9 Jun 2025 21:48:27 -0300 Subject: [PATCH 06/33] =?UTF-8?q?Feat:=20finalizando=20implementa=C3=A7?= =?UTF-8?q?=C3=A3o=20do=20mkdir?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Main.java | 2 + filesys/FileSystemImpl.java | 142 ++++++++++-------------------------- 2 files changed, 39 insertions(+), 105 deletions(-) diff --git a/Main.java b/Main.java index dc4a268..faa3332 100644 --- a/Main.java +++ b/Main.java @@ -102,11 +102,13 @@ public static void main(String[] args) { // // DESCOMENTE O BLOCO ABAIXO PARA CRIAR O DIRETÓRIO RAIZ ANTES DE RODAR O MENU // Cria o diretório raiz do sistema. Root sempre tem permissão total "rwx" + /* try { fileSystem.mkdir(ROOT_DIR, ROOT_USER); } catch (CaminhoJaExistenteException | PermissaoException e) { System.out.println(e.getMessage()); } + */ // Menu interativo. menu(); diff --git a/filesys/FileSystemImpl.java b/filesys/FileSystemImpl.java index 5a3c4ea..41ab562 100644 --- a/filesys/FileSystemImpl.java +++ b/filesys/FileSystemImpl.java @@ -24,8 +24,8 @@ public final class FileSystemImpl implements IFileSystem { private Dir raiz; // Diretório raiz public FileSystemImpl() { - this.raiz = new Dir("/", ROOT_USER, "rwx"); usuarios.add(new Usuario(ROOT_USER, "/", "rwx")); // Adiciona o usuário root com permissões totais + this.raiz = new Dir("/", ROOT_USER, "rwx"); } public FileSystemImpl(List usuarios) { @@ -34,116 +34,30 @@ public FileSystemImpl(List usuarios) { } this.usuarios = usuarios; + this.raiz = new Dir("/", ROOT_USER, "rwx"); } - /* @Override - public void mkdir(String caminho, String nome) throws CaminhoJaExistenteException, PermissaoException { - // throw new UnsupportedOperationException("Método não implementado 'mkdir'"); - if (caminho == null || nome == null) { - throw new IllegalArgumentException("Caminho e nome não podem ser nulos"); - } - if (caminho.isEmpty() || nome.isEmpty()) { - throw new IllegalArgumentException("Caminho e nome não podem ser vazios"); - } - - // Aqui você deve implementar a lógica para criar um diretório - // Verifique se o caminho existe e se o usuário tem permissão para criar o diretório - // Se o diretório já existir, lance CaminhoJaExistenteException - // Se o caminho não existir, lance CaminhoNaoEncontradoException - // Se o usuário não tiver permissão, lance PermissaoException - - // OBS: o contrato para esta interface exige que caminhos intermediários sejam criados por padrão durante a chamada à mkdir. É como se a flag '-p' fosse passada por padrão na nossa interface: - // -p Create intermediate directories as required. If this option is not specified, - // the full path prefix of each operand must already exist. On the other hand, - // with this option specified, no error will be reported if a directory given as - // an operand already exists. Intermediate directories are created with - // permission bits of “rwxrwxrwx” (0777) as modified by the current umask, plus - // write and search permission for the owner. - - // Verifique se o diretório já existe - if (diretorioExiste(caminho + nome)) { - throw new CaminhoJaExistenteException("Diretório já existe: " + caminho + nome); - } - - // Verificar se o usuário tem permissão para criar o diretório - if (!usuarioPodeCriarDiretorio(caminho, nome)) { - throw new PermissaoException("Usuário não tem permissão para criar diretório na raiz: " + nome); - } - - if (caminho.equals("/")) { - // Criar diretório na raiz - criarDiretorioNaRaiz(nome); - } else { - // Verifique se o caminho existe - if (!caminhoExiste(caminho)) { - throw new IllegalStateException("Caminho não encontrado: " + caminho); - } - // Criar diretório no caminho especificado - criarDiretorioNoCaminho(caminho, nome); - } - - } - - private boolean caminhoExiste(String caminho) { - Path path = Paths.get(caminho); - return Files.exists(path); - } - - private boolean diretorioExiste(String caminho) { - Path path = Paths.get(caminho); - return Files.isDirectory(path); - } - - private void criarDiretorioNaRaiz(String nome) { - Path path = Paths.get("/" + nome); - try { - Files.createDirectory(path); - } catch (Exception e) { - throw new RuntimeException("Erro ao criar diretório na raiz: " + e.getMessage(), e); - } - } - - private void criarDiretorioNoCaminho(String caminho, String nome) { - Path path = Paths.get(caminho, nome); - try { - Files.createDirectories(path); // Cria o diretório e quaisquer diretórios intermediários necessários - } catch (Exception e) { - throw new RuntimeException("Erro ao criar diretório no caminho: " + e.getMessage(), e); - } - } - - public boolean usuarioPodeCriarDiretorio(String caminho, String nome) { - // Verifica se o usuário atual tem permissão para criar no diretório - Usuario usuarioAtual = getUsuarioAtual(); // Método fictício para obter o usuário atual - // Pega as permissões do usuário atual - String permissoes = usuarioAtual.getPermissoes(); - - // Verifica se o usuário é root ou se tem permissão de escrita - if (ROOT_USER.equals(usuarioAtual.getNome()) || permissoes.contains("w")) { - return true; // Usuário root ou tem permissão de escrita + public void mkdir(String caminho, String usuario) throws CaminhoJaExistenteException, PermissaoException { + if (caminho == null || usuario == null) { + throw new IllegalArgumentException("Caminho e usuário não podem ser nulos"); } - return false; // Usuário não tem permissão - } + // Normaliza o caminho para formato UNIX + caminho = caminho.replace("\\", "/"); // Converte barras invertidas para barras normais - private Usuario getUsuarioAtual() { - for (Usuario usuario : usuarios) { - if (usuario.getNome().equals(user)) { - return usuario; - } + // Remove barras finais + if (caminho.length() > 1 && caminho.endsWith("/")) { + caminho = caminho.substring(0, caminho.length() - 1); } - throw new IllegalArgumentException("Usuário não encontrado: " + user); - } - */ - @Override - public void mkdir(String caminho, String usuario) throws CaminhoJaExistenteException, PermissaoException { if (caminho.equals("/")) { throw new UnsupportedOperationException("Não é possível criar diretório raiz pois ele já existe."); } - if (caminho == null || usuario == null) { - throw new IllegalArgumentException("Caminho e usuário não podem ser nulos"); + + if (raiz == null) { + System.err.println("Diretório raiz: " + raiz); + throw new IllegalStateException("Diretório raiz não foi inicializado."); } // Separar caminho em partes @@ -151,12 +65,23 @@ public void mkdir(String caminho, String usuario) throws CaminhoJaExistenteExcep Dir diretorioAtual = raiz; // Começa no diretório raiz StringBuilder caminhoAtual = new StringBuilder("/"); - for (String parte : partes) { - if (parte.isEmpty()) { - continue; // Ignora partes vazias (por exemplo, quando o caminho começa com '/') + for (int i = 0; i < partes.length; i++) { + String parte = partes[i]; + + if (parte == null || parte.isEmpty()) { + continue; // Ignora partes vazias } + + // Impede nomes inválidos de diretório + if (parte.contains("/") || parte.contains("\\")) { + throw new IllegalArgumentException("Nome de diretório inválido: " + parte); + } + caminhoAtual.append(parte).append("/"); + // Verifica se é o último diretório a ser criado + boolean isUltimoDiretorio = (i == partes.length - 1); + // Verifica se o diretório já existe if (diretorioAtual.getFilhos().containsKey(parte)) { if (diretorioAtual.getFilhos().get(parte).isArquivo()) { @@ -164,7 +89,12 @@ public void mkdir(String caminho, String usuario) throws CaminhoJaExistenteExcep } diretorioAtual = diretorioAtual.getFilhos().get(parte); // Ir para o diretório existente - throw new CaminhoJaExistenteException("Diretório já existe: " + caminhoAtual); + + if (isUltimoDiretorio) { + throw new CaminhoJaExistenteException("Diretório já existe: " + caminhoAtual); + } + + continue; // Se já existe, não cria novamente } // Verifica se o usuário existe @@ -174,7 +104,7 @@ public void mkdir(String caminho, String usuario) throws CaminhoJaExistenteExcep .orElseThrow(() -> new IllegalArgumentException("Usuário não encontrado: " + usuario)); // Verifica se o usuário tem permissão para criar o diretório - if (!diretorioAtual.getPermissoesUsuario(usuario).contains("w")) { + if (!diretorioAtual.temPerm(usuario, "w")) { throw new PermissaoException("Usuário não tem permissão para criar diretório: " + caminhoAtual); } @@ -182,6 +112,8 @@ public void mkdir(String caminho, String usuario) throws CaminhoJaExistenteExcep Dir novoDiretorio = new Dir(parte, usuario, "rwx"); diretorioAtual.addFilho(novoDiretorio); diretorioAtual = novoDiretorio; // Move para o novo diretório criado + + System.out.println("Diretório criado: " + caminhoAtual); } } From af838dd7d8138e120edf37e69fc3f31849d8e4eb Mon Sep 17 00:00:00 2001 From: PiterOfc Date: Mon, 9 Jun 2025 21:52:09 -0300 Subject: [PATCH 07/33] Feat: melhorando visual de pastas e arquivos --- filesys/Dir.java | 13 ++++++------- filesys/File.java | 10 +++++----- 2 files changed, 11 insertions(+), 12 deletions(-) diff --git a/filesys/Dir.java b/filesys/Dir.java index cfadeef..7334750 100644 --- a/filesys/Dir.java +++ b/filesys/Dir.java @@ -179,13 +179,12 @@ public boolean isArquivo() { public String toString() { StringBuilder sb = new StringBuilder(); - sb.append("Diretório: ").append(nome) - .append(", Dono: ").append(dono) - .append(", Permissões: ").append(permissoes) - .append(", Pai: ").append(pai != null ? pai.getNome() : "Nenhum") - .append(", Filhos: ").append(getFilhos().keySet()) - .append(", Permissões dos usuários: ").append(permissoesUsuarios); - + sb.append(" Diretório: ").append(nome).append("\n") + .append(" - Dono: ").append(dono).append("\n") + .append(" - Permissões: ").append(permissoes).append("\n") + .append(" - Pai: ").append(pai != null ? pai.getNome() : "Nenhum").append("\n") + .append(" - Filhos: ").append(getFilhos().isEmpty() ? "Nenhum" : getFilhos().keySet()).append("\n") + .append(" - Permissões dos usuários: ").append(permissoesUsuarios).append("\n"); return sb.toString(); } } diff --git a/filesys/File.java b/filesys/File.java index 1bc7da3..fb63bcc 100644 --- a/filesys/File.java +++ b/filesys/File.java @@ -109,11 +109,11 @@ public void removeFilho(String nome) { public String toString() { StringBuilder sb = new StringBuilder(); - sb.append("Arquivo: ").append(getNome()) - .append(", Dono: ").append(getDono()) - .append(", Permissões: ").append(getPermissoes()) - .append(", Tamanho: ").append(tamanho).append(" bytes") - .append(", Blocos: ").append(blocos.size()); + sb.append("Arquivo: ").append(getNome()).append("\n") + .append(" - Dono: ").append(getDono()).append("\n") + .append(" - Permissões: ").append(getPermissoes()).append("\n") + .append(" - Tamanho: ").append(tamanho).append(" bytes\n") + .append(" - Blocos: ").append(blocos.size()).append("\n"); return sb.toString(); } } From 3de05ecda09a871d59157d546a0836773549b710 Mon Sep 17 00:00:00 2001 From: PiterOfc Date: Mon, 9 Jun 2025 21:54:37 -0300 Subject: [PATCH 08/33] Feat: implementando listagem --- Main.java | 4 +-- filesys/FileSystemImpl.java | 61 +++++++++++++++++++++++++++++++++++-- 2 files changed, 61 insertions(+), 4 deletions(-) diff --git a/Main.java b/Main.java index faa3332..c4bfbbb 100644 --- a/Main.java +++ b/Main.java @@ -245,9 +245,9 @@ public static void mv() throws CaminhoNaoEncontradoException, PermissaoException } public static void ls() throws CaminhoNaoEncontradoException, PermissaoException { - System.out.println("Insira o caminho do diretório a ser listado:"); + System.out.print("Insira o caminho do diretório a ser listado: "); String caminho = scanner.nextLine(); - System.out.println("Listar recursivamente? (true/false):"); + System.out.print("Listar recursivamente? (true/false): "); boolean recursivo = Boolean.parseBoolean(scanner.nextLine()); fileSystem.ls(caminho, user, recursivo); diff --git a/filesys/FileSystemImpl.java b/filesys/FileSystemImpl.java index 41ab562..6d61769 100644 --- a/filesys/FileSystemImpl.java +++ b/filesys/FileSystemImpl.java @@ -37,6 +37,55 @@ public FileSystemImpl(List usuarios) { this.raiz = new Dir("/", ROOT_USER, "rwx"); } + // Método auxiliar para navegar até o diretório especificado pelo caminho + private Dir irPara(String caminho) throws CaminhoNaoEncontradoException { + if (caminho.equals("/") || caminho.isEmpty()) { + return raiz; + } + + Dir diretorioAtual = raiz; + + String[] partes = caminho.split("/"); + + for (String parte : partes) { + if (parte == null || parte.isEmpty()) continue; + if (!diretorioAtual.getFilhos().containsKey(parte)) { + throw new CaminhoNaoEncontradoException("Caminho não encontrado: " + caminho); + } + diretorioAtual = diretorioAtual.getFilhos().get(parte); + } + + return diretorioAtual; + } + + // Lista o conteúdo de um diretório e, se recursivo=true, lista também os subdiretórios + private String lsRecursivo(Dir diretorio, String caminho, boolean recursivo, String usuario) { + StringBuilder saida = new StringBuilder(); + String nomeCaminho = (caminho == null || caminho.isEmpty() || !caminho.startsWith("/")) ? "/" + caminho : caminho; + saida.append(nomeCaminho).append(":\n"); + + // Lista todos os filhos (arquivos e diretórios) do diretório atual + if (diretorio.getFilhos().isEmpty()) { + saida.append(" - Vazio\n"); + } else { + for (Dir filho : diretorio.getFilhos().values()) { + saida.append(filho.toString()).append("\n"); + } + } + + // Se for para listar recursivamente, faz o mesmo para cada subdiretório + if (recursivo) { + for (Dir filho : diretorio.getFilhos().values()) { + if (!filho.isArquivo()) { // Só entra em diretórios + String novoCaminho = caminho.equals("/") ? "/" + filho.getNome() : caminho + "/" + filho.getNome(); + saida.append(lsRecursivo(filho, novoCaminho, true, usuario)); + } + } + } + + return saida.toString(); + } + @Override public void mkdir(String caminho, String usuario) throws CaminhoJaExistenteException, PermissaoException { if (caminho == null || usuario == null) { @@ -153,8 +202,16 @@ public void mv(String caminhoAntigo, String caminhoNovo, String usuario) } @Override - public void ls(String caminho, String usuario, boolean recursivo) throws CaminhoNaoEncontradoException, PermissaoException { - throw new UnsupportedOperationException("Método não implementado 'ls'"); + public void ls(String caminho, String usuario, boolean recursivo) + throws CaminhoNaoEncontradoException, PermissaoException { + Dir diretorio = irPara(caminho); + + if (!diretorio.temPerm(usuario, "r")) { + throw new PermissaoException("Você não tem permissão para listar este diretório!"); + } + + String output = lsRecursivo(diretorio, caminho, recursivo, usuario); + System.out.print(output); } @Override From ddfd8271aef8ea7554d5806316a6db67d3bd62d5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Leonardo=20de=20Souza=20Galv=C3=A3o?= <160603231+LeonardodeSouzaGalvao@users.noreply.github.com> Date: Tue, 10 Jun 2025 09:42:57 -0300 Subject: [PATCH 09/33] feature: Starting implementation of touch --- filesys/FileSystemImpl.java | 25 ++++++++++++++++++++++++- 1 file changed, 24 insertions(+), 1 deletion(-) diff --git a/filesys/FileSystemImpl.java b/filesys/FileSystemImpl.java index 6d61769..d37a540 100644 --- a/filesys/FileSystemImpl.java +++ b/filesys/FileSystemImpl.java @@ -180,9 +180,32 @@ public void rm(String caminho, String usuario, boolean recursivo) @Override public void touch(String caminho, String usuario) throws CaminhoJaExistenteException, PermissaoException { - throw new UnsupportedOperationException("Método não implementado 'touch'"); + if (caminho == null || usuario == null) { + throw new IllegalArgumentException("Caminho e usuário não podem ser nulos"); } + caminho = caminho.replace("\\", "/"); + if (caminho.endsWith("/")) caminho = caminho.substring(0, caminho.length() - 1); + + int idx = caminho.lastIndexOf('/'); + String nomeArquivo = caminho.substring(idx + 1); + String caminhoPai = (idx <= 0) ? "/" : caminho.substring(0, idx); + + Dir dirPai = irPara(caminhoPai); + + if (dirPai.getFilhos().containsKey(nomeArquivo)) { + throw new CaminhoJaExistenteException("Arquivo ou diretório já existe: " + caminho); + } + + if (!dirPai.temPerm(usuario, "w")) { + throw new PermissaoException("Usuário não tem permissão para criar arquivo: " + caminho); + } + + File novoArquivo = new File(nomeArquivo, usuario, "rwx"); + dirPai.addFilho(novoArquivo); + System.out.println("Arquivo criado: " + caminho); +} + @Override public void write(String caminho, String usuario, boolean anexar, byte[] buffer) throws CaminhoNaoEncontradoException, PermissaoException { From d50aae72b9ffa88b54d1592f26362c39bd0eabc8 Mon Sep 17 00:00:00 2001 From: PiterOfc Date: Tue, 10 Jun 2025 11:09:14 -0300 Subject: [PATCH 10/33] =?UTF-8?q?Fix:=20formatando=20e=20add=20exce=C3=A7?= =?UTF-8?q?=C3=A3o=20para=20funcionamento?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Main.java | 2 +- filesys/FileSystem.java | 2 +- filesys/FileSystemImpl.java | 41 +++++++++++++++++++------------------ filesys/IFileSystem.java | 3 ++- 4 files changed, 25 insertions(+), 23 deletions(-) diff --git a/Main.java b/Main.java index c4bfbbb..560b4b6 100644 --- a/Main.java +++ b/Main.java @@ -207,7 +207,7 @@ public static void rm() throws CaminhoNaoEncontradoException, PermissaoException fileSystem.rm(caminho, user, recursivo); } - public static void touch() throws CaminhoJaExistenteException, PermissaoException { + public static void touch() throws CaminhoJaExistenteException, PermissaoException, CaminhoNaoEncontradoException { System.out.println("Insira o caminho do arquivo a ser criado:"); String caminho = scanner.nextLine(); diff --git a/filesys/FileSystem.java b/filesys/FileSystem.java index 5abc4e5..13dcb1a 100644 --- a/filesys/FileSystem.java +++ b/filesys/FileSystem.java @@ -37,7 +37,7 @@ public void rm(String caminho, String usuario, boolean recursivo) } @Override - public void touch(String caminho, String usuario) throws CaminhoJaExistenteException, PermissaoException { + public void touch(String caminho, String usuario) throws CaminhoJaExistenteException, PermissaoException, CaminhoNaoEncontradoException { fileSystemImpl.touch(caminho, usuario); } diff --git a/filesys/FileSystemImpl.java b/filesys/FileSystemImpl.java index d37a540..677e1e1 100644 --- a/filesys/FileSystemImpl.java +++ b/filesys/FileSystemImpl.java @@ -179,32 +179,33 @@ public void rm(String caminho, String usuario, boolean recursivo) } @Override - public void touch(String caminho, String usuario) throws CaminhoJaExistenteException, PermissaoException { - if (caminho == null || usuario == null) { - throw new IllegalArgumentException("Caminho e usuário não podem ser nulos"); - } + public void touch(String caminho, String usuario) throws CaminhoJaExistenteException, PermissaoException, CaminhoNaoEncontradoException { + if (caminho == null || usuario == null) { + throw new IllegalArgumentException("Caminho e usuário não podem ser nulos"); + } - caminho = caminho.replace("\\", "/"); - if (caminho.endsWith("/")) caminho = caminho.substring(0, caminho.length() - 1); + caminho = caminho.replace("\\", "/"); + if (caminho.endsWith("/")) + caminho = caminho.substring(0, caminho.length() - 1); - int idx = caminho.lastIndexOf('/'); - String nomeArquivo = caminho.substring(idx + 1); - String caminhoPai = (idx <= 0) ? "/" : caminho.substring(0, idx); + int idx = caminho.lastIndexOf('/'); + String nomeArquivo = caminho.substring(idx + 1); + String caminhoPai = (idx <= 0) ? "/" : caminho.substring(0, idx); - Dir dirPai = irPara(caminhoPai); + Dir dirPai = irPara(caminhoPai); - if (dirPai.getFilhos().containsKey(nomeArquivo)) { - throw new CaminhoJaExistenteException("Arquivo ou diretório já existe: " + caminho); - } + if (dirPai.getFilhos().containsKey(nomeArquivo)) { + throw new CaminhoJaExistenteException("Arquivo ou diretório já existe: " + caminho); + } - if (!dirPai.temPerm(usuario, "w")) { - throw new PermissaoException("Usuário não tem permissão para criar arquivo: " + caminho); - } + if (!dirPai.temPerm(usuario, "w")) { + throw new PermissaoException("Usuário não tem permissão para criar arquivo: " + caminho); + } - File novoArquivo = new File(nomeArquivo, usuario, "rwx"); - dirPai.addFilho(novoArquivo); - System.out.println("Arquivo criado: " + caminho); -} + File novoArquivo = new File(nomeArquivo, usuario, "rwx"); + dirPai.addFilho(novoArquivo); + System.out.println("Arquivo criado: " + caminho); + } @Override public void write(String caminho, String usuario, boolean anexar, byte[] buffer) diff --git a/filesys/IFileSystem.java b/filesys/IFileSystem.java index 06e1738..3e339d5 100644 --- a/filesys/IFileSystem.java +++ b/filesys/IFileSystem.java @@ -21,7 +21,8 @@ public interface IFileSystem { void rm(String caminho, String usuario, boolean recursivo) throws CaminhoNaoEncontradoException, PermissaoException; // Cria um novo arquivo. Atenção: Se o arquivo já existir, será lançada uma exceção. - void touch(String caminho, String usuario) throws CaminhoJaExistenteException, PermissaoException; + // ADD: exceção CaminhoNaoEncontradoException + void touch(String caminho, String usuario) throws CaminhoJaExistenteException, PermissaoException, CaminhoNaoEncontradoException; // Escreve dados em um arquivo. Se o diretório não existir, será lançada uma exceção. // Caso o diretório exista, o arquivo será criado ou sobrescrito. From d52387d57f368b95e1c905dc2b38b72b334d93cb Mon Sep 17 00:00:00 2001 From: PiterOfc Date: Tue, 10 Jun 2025 11:10:17 -0300 Subject: [PATCH 11/33] Feat: melhorando visual de arquivos --- filesys/File.java | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/filesys/File.java b/filesys/File.java index fb63bcc..25195b8 100644 --- a/filesys/File.java +++ b/filesys/File.java @@ -109,11 +109,11 @@ public void removeFilho(String nome) { public String toString() { StringBuilder sb = new StringBuilder(); - sb.append("Arquivo: ").append(getNome()).append("\n") - .append(" - Dono: ").append(getDono()).append("\n") - .append(" - Permissões: ").append(getPermissoes()).append("\n") - .append(" - Tamanho: ").append(tamanho).append(" bytes\n") - .append(" - Blocos: ").append(blocos.size()).append("\n"); + sb.append(" Arquivo: ").append(getNome()).append("\n") + .append(" - Dono: ").append(getDono()).append("\n") + .append(" - Permissões: ").append(getPermissoes()).append("\n") + .append(" - Tamanho: ").append(tamanho).append(" bytes\n") + .append(" - Blocos: ").append(blocos.size()).append("\n"); return sb.toString(); } } From b95e69c97a4983e02f9a35604267fefae748e098 Mon Sep 17 00:00:00 2001 From: PiterOfc Date: Tue, 10 Jun 2025 11:36:43 -0300 Subject: [PATCH 12/33] Feat: chmod --- filesys/FileSystemImpl.java | 30 +++++++++++++++++++++++++++--- 1 file changed, 27 insertions(+), 3 deletions(-) diff --git a/filesys/FileSystemImpl.java b/filesys/FileSystemImpl.java index 677e1e1..7d891e8 100644 --- a/filesys/FileSystemImpl.java +++ b/filesys/FileSystemImpl.java @@ -167,9 +167,33 @@ public void mkdir(String caminho, String usuario) throws CaminhoJaExistenteExcep } @Override - public void chmod(String caminho, String usuario, String usuarioAlvo, String permissao) - throws CaminhoNaoEncontradoException, PermissaoException { - throw new UnsupportedOperationException("Método não implementado 'chmod'"); + public void chmod(String caminho, String usuario, String usuarioAlvo, String permissao) throws CaminhoNaoEncontradoException, PermissaoException { + if (caminho == null || usuario == null || usuarioAlvo == null || permissao == null) { + throw new IllegalArgumentException("Caminho, usuário, usuário alvo e permissão não podem ser nulos"); + } + + // Verifica se o usuário existe + usuarios.stream() + .filter(u -> u.getNome().equals(usuarioAlvo)) + .findFirst() + .orElseThrow(() -> new IllegalArgumentException("Usuário não encontrado: " + usuarioAlvo)); + + if (!permissao.matches("^[rwx-]{3}$")) { + throw new IllegalArgumentException("Permissão inválida: " + permissao); + } + + caminho = caminho.replace("\\", "/"); + if (caminho.endsWith("/")) + caminho = caminho.substring(0, caminho.length() - 1); + + Dir dir = irPara(caminho); + + if (!dir.temPerm(usuario, "w")) { + throw new PermissaoException("Usuário não tem permissão para alterar permissões: " + caminho); + } + + dir.setPermissoesUsuario(usuarioAlvo, permissao); + System.out.println("Permissão alterada para " + usuarioAlvo + " em " + caminho + ": " + permissao); } @Override From e3d185deb759c92cd09e0bb0a0fddef9914c8920 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Leonardo=20de=20Souza=20Galv=C3=A3o?= <160603231+LeonardodeSouzaGalvao@users.noreply.github.com> Date: Wed, 11 Jun 2025 20:39:28 -0300 Subject: [PATCH 13/33] =?UTF-8?q?feature:=20Remove=20OBS:=20Apenas=20lan?= =?UTF-8?q?=C3=A7a=20uma=20exce=C3=A7=C3=A3o?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Main.java | 30 ++++++++++++++++++++++++++++++ filesys/Dir.java | 24 ++++++++++++++++++++++++ filesys/FileSystemImpl.java | 34 +++++++++++++++++++++++++++++++--- 3 files changed, 85 insertions(+), 3 deletions(-) diff --git a/Main.java b/Main.java index 560b4b6..8326664 100644 --- a/Main.java +++ b/Main.java @@ -10,7 +10,9 @@ import exception.CaminhoJaExistenteException; import exception.CaminhoNaoEncontradoException; + import filesys.FileSystem; +import filesys.Dir; // MENU INTERATIVO PARA O SISTEMA DE ARQUIVOS // SINTA-SE LIVRE PARA ALTERAR A CLASSE MAIN @@ -201,12 +203,40 @@ public static void mkdir() throws CaminhoJaExistenteException, PermissaoExceptio public static void rm() throws CaminhoNaoEncontradoException, PermissaoException { System.out.println("Insira o caminho do diretório a ser removido:"); String caminho = scanner.nextLine(); + System.out.println("Remover recursivamente? (true/false):"); boolean recursivo = Boolean.parseBoolean(scanner.nextLine()); fileSystem.rm(caminho, user, recursivo); } + /* + TENTATIVA DE DEFINIR RECURSIVIDADE COMO TRUE CASO DIRETÓRIO TENHA SUBDIRETÓRIOS + + public static void rm() throws CaminhoNaoEncontradoException, PermissaoException { + System.out.println("Insira o caminho do arquivo ou diretório a ser removido:"); + String caminho = scanner.nextLine(); + + // Checa se o caminho é um diretório com subdiretórios + Dir dir = null; + dir = fileSystem.getDir(caminho, user); + + + + + boolean recursivo = false; + if (dir != null && !dir.isArquivo() && dir.temSubdiretorios()) { + System.out.println("O diretório contém subdiretórios."); + recursivo = true; + } else { + System.out.println("Remover recursivamente? (true/false):"); + recursivo = Boolean.parseBoolean(scanner.nextLine()); + } + + fileSystem.rm(caminho, user, recursivo); + } + */ + public static void touch() throws CaminhoJaExistenteException, PermissaoException, CaminhoNaoEncontradoException { System.out.println("Insira o caminho do arquivo a ser criado:"); String caminho = scanner.nextLine(); diff --git a/filesys/Dir.java b/filesys/Dir.java index 7334750..6fdd8c4 100644 --- a/filesys/Dir.java +++ b/filesys/Dir.java @@ -173,6 +173,30 @@ public boolean isArquivo() { return false; // Esta classe representa um diretório, não um arquivo } + public String getCaminhoCompleto(){ + if(this.getPai() == null){ + return "/" + this.getNome(); + } + else{ + String caminhoPai = this.getPai().getCaminhoCompleto(); + if(caminhoPai.endsWith("/")){ + return caminhoPai + this.getNome(); + } else { + return caminhoPai + "/" + this.getNome(); + } + } + } + + + public boolean temSubdiretorios() { + for (Dir filho : getFilhos().values()) { + if (!filho.isArquivo()) { + return true; + } + } + return false; +} + // Transformando em string @Override diff --git a/filesys/FileSystemImpl.java b/filesys/FileSystemImpl.java index 7d891e8..67f9ea9 100644 --- a/filesys/FileSystemImpl.java +++ b/filesys/FileSystemImpl.java @@ -197,9 +197,37 @@ public void chmod(String caminho, String usuario, String usuarioAlvo, String per } @Override - public void rm(String caminho, String usuario, boolean recursivo) - throws CaminhoNaoEncontradoException, PermissaoException { - throw new UnsupportedOperationException("Método não implementado 'rm'"); + public void rm(String caminho, String usuario, boolean recursivo) throws CaminhoNaoEncontradoException, PermissaoException { + if (caminho == null || usuario == null) { + throw new IllegalArgumentException("Caminho e usuário não podem ser nulos"); + } + + caminho = caminho.replace("\\", "/"); + if (caminho.endsWith("/")) + caminho = caminho.substring(0, caminho.length() - 1); + + Dir dir = irPara(caminho); + + if (!dir.temPerm(usuario, "w")) { + throw new PermissaoException("Usuário não tem permissão para remover: " + caminho); + } + if(dir.temSubdiretorios() && !recursivo) { + throw new PermissaoException("Esse diretório contém subdiretórios. Use o parâmetro recursivo para removê-lo."); + } + + + if (dir.isArquivo()) { + dir.getPai().removeFilho(dir.getNome()); + System.out.println("Arquivo removido: " + caminho); + } else { + if (recursivo) { + for (Dir filho : dir.getFilhos().values()) { + rm(filho.getCaminhoCompleto(), usuario, true); + } + } + dir.getPai().removeFilho(dir.getNome()); + System.out.println("Diretório removido: " + caminho); + } } @Override From 0d093fa8779627160e947833fc04b0c429c26bb5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Leonardo=20de=20Souza=20Galv=C3=A3o?= <160603231+LeonardodeSouzaGalvao@users.noreply.github.com> Date: Thu, 12 Jun 2025 19:17:58 -0300 Subject: [PATCH 14/33] feat: remove commented-out section --- Main.java | 26 -------------------------- 1 file changed, 26 deletions(-) diff --git a/Main.java b/Main.java index 8326664..3a35e5d 100644 --- a/Main.java +++ b/Main.java @@ -210,32 +210,6 @@ public static void rm() throws CaminhoNaoEncontradoException, PermissaoException fileSystem.rm(caminho, user, recursivo); } - /* - TENTATIVA DE DEFINIR RECURSIVIDADE COMO TRUE CASO DIRETÓRIO TENHA SUBDIRETÓRIOS - - public static void rm() throws CaminhoNaoEncontradoException, PermissaoException { - System.out.println("Insira o caminho do arquivo ou diretório a ser removido:"); - String caminho = scanner.nextLine(); - - // Checa se o caminho é um diretório com subdiretórios - Dir dir = null; - dir = fileSystem.getDir(caminho, user); - - - - - boolean recursivo = false; - if (dir != null && !dir.isArquivo() && dir.temSubdiretorios()) { - System.out.println("O diretório contém subdiretórios."); - recursivo = true; - } else { - System.out.println("Remover recursivamente? (true/false):"); - recursivo = Boolean.parseBoolean(scanner.nextLine()); - } - - fileSystem.rm(caminho, user, recursivo); - } - */ public static void touch() throws CaminhoJaExistenteException, PermissaoException, CaminhoNaoEncontradoException { System.out.println("Insira o caminho do arquivo a ser criado:"); From a064d88227e41452e0df06167f0c9e9cbf9e352a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Leonardo=20de=20Souza=20Galv=C3=A3o?= <160603231+LeonardodeSouzaGalvao@users.noreply.github.com> Date: Thu, 12 Jun 2025 21:00:33 -0300 Subject: [PATCH 15/33] feat: implement mv method (NOT FINISHED) --- filesys/FileSystemImpl.java | 21 ++++++++++++++++++++- 1 file changed, 20 insertions(+), 1 deletion(-) diff --git a/filesys/FileSystemImpl.java b/filesys/FileSystemImpl.java index 67f9ea9..77c8e8a 100644 --- a/filesys/FileSystemImpl.java +++ b/filesys/FileSystemImpl.java @@ -274,7 +274,26 @@ public void read(String caminho, String usuario, byte[] buffer) @Override public void mv(String caminhoAntigo, String caminhoNovo, String usuario) throws CaminhoNaoEncontradoException, PermissaoException { - throw new UnsupportedOperationException("Método não implementado 'mv'"); + if (caminhoAntigo == null || caminhoNovo == null || usuario == null) { + throw new IllegalArgumentException("Caminho antigo, caminho novo e usuário não podem ser nulos"); + } + Dir dirAntigo = irPara(caminhoAntigo); + Dir dirNovo = irPara(caminhoNovo); + if (!dirAntigo.temPerm(usuario, "w")) { + throw new PermissaoException("Usuário não tem permissão para mover: " + caminhoAntigo); + } + if (!dirNovo.temPerm(usuario, "w")) { + throw new PermissaoException("Usuário não tem permissão para mover para: " + caminhoNovo); + } + + /* + if( dirNovo.getFilhos().containsKey(dirAntigo.getNome())) { + throw new CaminhoJaExistenteException("Já existe um arquivo ou diretório com o mesmo nome em: " + caminhoNovo); + } + */ + + dirNovo.addFilho(dirAntigo); + dirAntigo.getPai().removeFilho(dirAntigo.getNome()); } @Override From aebf080166ccd5fc875417958befa209032e540f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Leonardo=20de=20Souza=20Galv=C3=A3o?= <160603231+LeonardodeSouzaGalvao@users.noreply.github.com> Date: Fri, 13 Jun 2025 19:20:28 -0300 Subject: [PATCH 16/33] =?UTF-8?q?TODO:=20Renomea=C3=A7=C3=A3o?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- filesys/FileSystemImpl.java | 29 ++++++++++++++++++++--------- 1 file changed, 20 insertions(+), 9 deletions(-) diff --git a/filesys/FileSystemImpl.java b/filesys/FileSystemImpl.java index 77c8e8a..c5eb854 100644 --- a/filesys/FileSystemImpl.java +++ b/filesys/FileSystemImpl.java @@ -272,11 +272,24 @@ public void read(String caminho, String usuario, byte[] buffer) } @Override - public void mv(String caminhoAntigo, String caminhoNovo, String usuario) - throws CaminhoNaoEncontradoException, PermissaoException { + public void mv(String caminhoAntigo, String caminhoNovo, String usuario) throws CaminhoNaoEncontradoException, PermissaoException { if (caminhoAntigo == null || caminhoNovo == null || usuario == null) { throw new IllegalArgumentException("Caminho antigo, caminho novo e usuário não podem ser nulos"); } + caminhoAntigo = caminhoAntigo.replace("\\", "/"); + caminhoNovo = caminhoNovo.replace("\\", "/"); + if (caminhoAntigo.endsWith("/")) { + caminhoAntigo = caminhoAntigo.substring(0, caminhoAntigo.length() - 1); + } + if (caminhoNovo.endsWith("/")) { + caminhoNovo = caminhoNovo.substring(0, caminhoNovo.length() - 1); + } + + if (caminhoAntigo.equals(caminhoNovo)) { + throw new IllegalArgumentException("Caminho antigo e caminho novo não podem ser iguais"); + } + + Dir dirAntigo = irPara(caminhoAntigo); Dir dirNovo = irPara(caminhoNovo); if (!dirAntigo.temPerm(usuario, "w")) { @@ -285,15 +298,13 @@ public void mv(String caminhoAntigo, String caminhoNovo, String usuario) if (!dirNovo.temPerm(usuario, "w")) { throw new PermissaoException("Usuário não tem permissão para mover para: " + caminhoNovo); } + + if( dirNovo.getFilhos().containsKey(dirAntigo.getNome())) { + throw new IllegalArgumentException("Já existe um arquivo ou diretório com o mesmo nome em: " + caminhoNovo); + } - /* - if( dirNovo.getFilhos().containsKey(dirAntigo.getNome())) { - throw new CaminhoJaExistenteException("Já existe um arquivo ou diretório com o mesmo nome em: " + caminhoNovo); - } - */ - - dirNovo.addFilho(dirAntigo); dirAntigo.getPai().removeFilho(dirAntigo.getNome()); + dirNovo.addFilho(dirAntigo); } @Override From 3bbf135864a701cae8c80d93720095d64aa53f49 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Leonardo=20de=20Souza=20Galv=C3=A3o?= <160603231+LeonardodeSouzaGalvao@users.noreply.github.com> Date: Fri, 13 Jun 2025 19:33:19 -0300 Subject: [PATCH 17/33] feat: implement cp method for copying files and directories --- filesys/FileSystemImpl.java | 41 ++++++++++++++++++++++++++++++++++++- 1 file changed, 40 insertions(+), 1 deletion(-) diff --git a/filesys/FileSystemImpl.java b/filesys/FileSystemImpl.java index 67f9ea9..693edb5 100644 --- a/filesys/FileSystemImpl.java +++ b/filesys/FileSystemImpl.java @@ -293,7 +293,46 @@ public void ls(String caminho, String usuario, boolean recursivo) @Override public void cp(String caminhoOrigem, String caminhoDestino, String usuario, boolean recursivo) throws CaminhoNaoEncontradoException, PermissaoException { - throw new UnsupportedOperationException("Método não implementado 'cp'"); + if (caminhoOrigem == null || caminhoDestino == null || usuario == null) { + throw new IllegalArgumentException("Caminho de origem, destino e usuário não podem ser nulos"); + } + caminhoOrigem = caminhoOrigem.replace("\\", "/"); + caminhoDestino = caminhoDestino.replace("\\", "/"); + if (caminhoOrigem.endsWith("/")){ + caminhoOrigem = caminhoOrigem.substring(0, caminhoOrigem.length() - 1); + } + if (caminhoDestino.endsWith("/")){ + caminhoDestino = caminhoDestino.substring(0, caminhoDestino.length() - 1); + } + Dir dirOrigem = irPara(caminhoOrigem); + Dir dirDestino = irPara(caminhoDestino); + if (!dirOrigem.temPerm(usuario, "r")) { + throw new PermissaoException("Usuário não tem permissão para ler o diretório de origem: " + caminhoOrigem); + } + if (!dirDestino.temPerm(usuario, "w")) { + throw new PermissaoException("Usuário não tem permissão para escrever no diretório de destino: " + caminhoDestino); + } + + String nomeArquivo = dirOrigem.getNome(); + String caminhoCompletoDestino = dirDestino.getCaminhoCompleto() + "/" + nomeArquivo; + if (dirDestino.getFilhos().containsKey(nomeArquivo)) { + throw new IllegalArgumentException("Arquivo ou diretório já existe no destino: " + caminhoCompletoDestino); + } + if (dirOrigem.isArquivo()) { + File novoArquivo = new File(nomeArquivo, usuario, "rwx"); + dirDestino.addFilho(novoArquivo); + System.out.println("Arquivo copiado de " + caminhoOrigem + " para " + caminhoCompletoDestino); + } else { + Dir novoDiretorio = new Dir(nomeArquivo, usuario, "rwx"); + dirDestino.addFilho(novoDiretorio); + for (Dir filho : dirOrigem.getFilhos().values()) { + String caminhoFilhoOrigem = filho.getCaminhoCompleto(); + String caminhoFilhoDestino = novoDiretorio.getCaminhoCompleto() + "/" + filho.getNome(); + cp(caminhoFilhoOrigem, caminhoFilhoDestino, usuario, recursivo); + } + System.out.println("Diretório copiado de " + caminhoOrigem + " para " + caminhoCompletoDestino); + } + } public void addUser(String user) { From 625f5b1d59f5cc28f8a2c621200966769f51936c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Leonardo=20de=20Souza=20Galv=C3=A3o?= <160603231+LeonardodeSouzaGalvao@users.noreply.github.com> Date: Fri, 13 Jun 2025 20:38:25 -0300 Subject: [PATCH 18/33] =?UTF-8?q?Update:=20renomea=C3=A7=C3=A3o=20implemen?= =?UTF-8?q?tada?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- filesys/FileSystemImpl.java | 73 ++++++++++++++++++++++++------------- 1 file changed, 48 insertions(+), 25 deletions(-) diff --git a/filesys/FileSystemImpl.java b/filesys/FileSystemImpl.java index c5eb854..d2e3872 100644 --- a/filesys/FileSystemImpl.java +++ b/filesys/FileSystemImpl.java @@ -272,40 +272,63 @@ public void read(String caminho, String usuario, byte[] buffer) } @Override - public void mv(String caminhoAntigo, String caminhoNovo, String usuario) throws CaminhoNaoEncontradoException, PermissaoException { - if (caminhoAntigo == null || caminhoNovo == null || usuario == null) { - throw new IllegalArgumentException("Caminho antigo, caminho novo e usuário não podem ser nulos"); - } - caminhoAntigo = caminhoAntigo.replace("\\", "/"); - caminhoNovo = caminhoNovo.replace("\\", "/"); - if (caminhoAntigo.endsWith("/")) { - caminhoAntigo = caminhoAntigo.substring(0, caminhoAntigo.length() - 1); +public void mv(String caminhoAntigo, String caminhoNovo, String usuario) throws CaminhoNaoEncontradoException, PermissaoException { + if (caminhoAntigo == null || caminhoNovo == null || usuario == null) { + throw new IllegalArgumentException("Caminho antigo, caminho novo e usuário não podem ser nulos"); + } + + caminhoAntigo = caminhoAntigo.replace("\\", "/"); + caminhoNovo = caminhoNovo.replace("\\", "/"); + + if (caminhoAntigo.endsWith("/")) { + caminhoAntigo = caminhoAntigo.substring(0, caminhoAntigo.length() - 1); + } + if (caminhoNovo.endsWith("/")) { + caminhoNovo = caminhoNovo.substring(0, caminhoNovo.length() - 1); + } + + if (caminhoAntigo.equals(caminhoNovo)) { + throw new IllegalArgumentException("Caminho antigo e caminho novo não podem ser iguais"); + } + + Dir dirantigo = irPara(caminhoAntigo); + + if (!dirantigo.temPerm(usuario, "w")) { + throw new PermissaoException("Usuário não tem permissão para mover: " + caminhoAntigo); + } + + try { + Dir destino = irPara(caminhoNovo); + if (!destino.temPerm(usuario, "w")) { + throw new PermissaoException("Sem permissão de escrita no destino"); } - if (caminhoNovo.endsWith("/")) { - caminhoNovo = caminhoNovo.substring(0, caminhoNovo.length() - 1); + if (destino.getFilhos().containsKey(dirantigo.getNome())) { + throw new IllegalArgumentException("Já existe um diretório ou arquivo com esse nome no destino"); } - if (caminhoAntigo.equals(caminhoNovo)) { - throw new IllegalArgumentException("Caminho antigo e caminho novo não podem ser iguais"); - } + dirantigo.getPai().removeFilho(dirantigo.getNome()); + destino.addFilho(dirantigo); + } catch (CaminhoNaoEncontradoException e) { + + int idx = caminhoNovo.lastIndexOf('/'); + String novoNome = caminhoNovo.substring(idx + 1); + String caminhoPaiNovo = (idx <= 0) ? "/" : caminhoNovo.substring(0, idx); + Dir novoPai = irPara(caminhoPaiNovo); - Dir dirAntigo = irPara(caminhoAntigo); - Dir dirNovo = irPara(caminhoNovo); - if (!dirAntigo.temPerm(usuario, "w")) { - throw new PermissaoException("Usuário não tem permissão para mover: " + caminhoAntigo); + if (!novoPai.temPerm(usuario, "w")) { + throw new PermissaoException("Sem permissão de escrita no novo caminho"); } - if (!dirNovo.temPerm(usuario, "w")) { - throw new PermissaoException("Usuário não tem permissão para mover para: " + caminhoNovo); + if (novoPai.getFilhos().containsKey(novoNome)) { + throw new IllegalArgumentException("Já existe um objeto com esse nome no destino"); } - if( dirNovo.getFilhos().containsKey(dirAntigo.getNome())) { - throw new IllegalArgumentException("Já existe um arquivo ou diretório com o mesmo nome em: " + caminhoNovo); - } - - dirAntigo.getPai().removeFilho(dirAntigo.getNome()); - dirNovo.addFilho(dirAntigo); + dirantigo.getPai().removeFilho(dirantigo.getNome()); + dirantigo.setNome(novoNome); + novoPai.addFilho(dirantigo); } +} + @Override public void ls(String caminho, String usuario, boolean recursivo) From 47286cf967974ad357eb276b2f3981c4cfdd8e0a Mon Sep 17 00:00:00 2001 From: PiterOfc Date: Sat, 14 Jun 2025 15:50:04 -0300 Subject: [PATCH 19/33] Formatando arquivo --- filesys/FileSystemImpl.java | 123 +++++++++++++++++++----------------- 1 file changed, 65 insertions(+), 58 deletions(-) diff --git a/filesys/FileSystemImpl.java b/filesys/FileSystemImpl.java index 0fae5fa..607909d 100644 --- a/filesys/FileSystemImpl.java +++ b/filesys/FileSystemImpl.java @@ -48,7 +48,8 @@ private Dir irPara(String caminho) throws CaminhoNaoEncontradoException { String[] partes = caminho.split("/"); for (String parte : partes) { - if (parte == null || parte.isEmpty()) continue; + if (parte == null || parte.isEmpty()) + continue; if (!diretorioAtual.getFilhos().containsKey(parte)) { throw new CaminhoNaoEncontradoException("Caminho não encontrado: " + caminho); } @@ -58,10 +59,12 @@ private Dir irPara(String caminho) throws CaminhoNaoEncontradoException { return diretorioAtual; } - // Lista o conteúdo de um diretório e, se recursivo=true, lista também os subdiretórios + // Lista o conteúdo de um diretório e, se recursivo=true, lista também os + // subdiretórios private String lsRecursivo(Dir diretorio, String caminho, boolean recursivo, String usuario) { StringBuilder saida = new StringBuilder(); - String nomeCaminho = (caminho == null || caminho.isEmpty() || !caminho.startsWith("/")) ? "/" + caminho : caminho; + String nomeCaminho = (caminho == null || caminho.isEmpty() || !caminho.startsWith("/")) ? "/" + caminho + : caminho; saida.append(nomeCaminho).append(":\n"); // Lista todos os filhos (arquivos e diretórios) do diretório atual @@ -167,7 +170,8 @@ public void mkdir(String caminho, String usuario) throws CaminhoJaExistenteExcep } @Override - public void chmod(String caminho, String usuario, String usuarioAlvo, String permissao) throws CaminhoNaoEncontradoException, PermissaoException { + public void chmod(String caminho, String usuario, String usuarioAlvo, String permissao) + throws CaminhoNaoEncontradoException, PermissaoException { if (caminho == null || usuario == null || usuarioAlvo == null || permissao == null) { throw new IllegalArgumentException("Caminho, usuário, usuário alvo e permissão não podem ser nulos"); } @@ -197,7 +201,8 @@ public void chmod(String caminho, String usuario, String usuarioAlvo, String per } @Override - public void rm(String caminho, String usuario, boolean recursivo) throws CaminhoNaoEncontradoException, PermissaoException { + public void rm(String caminho, String usuario, boolean recursivo) + throws CaminhoNaoEncontradoException, PermissaoException { if (caminho == null || usuario == null) { throw new IllegalArgumentException("Caminho e usuário não podem ser nulos"); } @@ -211,10 +216,10 @@ public void rm(String caminho, String usuario, boolean recursivo) throws Caminho if (!dir.temPerm(usuario, "w")) { throw new PermissaoException("Usuário não tem permissão para remover: " + caminho); } - if(dir.temSubdiretorios() && !recursivo) { - throw new PermissaoException("Esse diretório contém subdiretórios. Use o parâmetro recursivo para removê-lo."); + if (dir.temSubdiretorios() && !recursivo) { + throw new PermissaoException( + "Esse diretório contém subdiretórios. Use o parâmetro recursivo para removê-lo."); } - if (dir.isArquivo()) { dir.getPai().removeFilho(dir.getNome()); @@ -231,7 +236,8 @@ public void rm(String caminho, String usuario, boolean recursivo) throws Caminho } @Override - public void touch(String caminho, String usuario) throws CaminhoJaExistenteException, PermissaoException, CaminhoNaoEncontradoException { + public void touch(String caminho, String usuario) + throws CaminhoJaExistenteException, PermissaoException, CaminhoNaoEncontradoException { if (caminho == null || usuario == null) { throw new IllegalArgumentException("Caminho e usuário não podem ser nulos"); } @@ -272,63 +278,63 @@ public void read(String caminho, String usuario, byte[] buffer) } @Override -public void mv(String caminhoAntigo, String caminhoNovo, String usuario) throws CaminhoNaoEncontradoException, PermissaoException { - if (caminhoAntigo == null || caminhoNovo == null || usuario == null) { - throw new IllegalArgumentException("Caminho antigo, caminho novo e usuário não podem ser nulos"); - } + public void mv(String caminhoAntigo, String caminhoNovo, String usuario) + throws CaminhoNaoEncontradoException, PermissaoException { + if (caminhoAntigo == null || caminhoNovo == null || usuario == null) { + throw new IllegalArgumentException("Caminho antigo, caminho novo e usuário não podem ser nulos"); + } - caminhoAntigo = caminhoAntigo.replace("\\", "/"); - caminhoNovo = caminhoNovo.replace("\\", "/"); + caminhoAntigo = caminhoAntigo.replace("\\", "/"); + caminhoNovo = caminhoNovo.replace("\\", "/"); - if (caminhoAntigo.endsWith("/")) { - caminhoAntigo = caminhoAntigo.substring(0, caminhoAntigo.length() - 1); - } - if (caminhoNovo.endsWith("/")) { - caminhoNovo = caminhoNovo.substring(0, caminhoNovo.length() - 1); - } - - if (caminhoAntigo.equals(caminhoNovo)) { - throw new IllegalArgumentException("Caminho antigo e caminho novo não podem ser iguais"); - } + if (caminhoAntigo.endsWith("/")) { + caminhoAntigo = caminhoAntigo.substring(0, caminhoAntigo.length() - 1); + } + if (caminhoNovo.endsWith("/")) { + caminhoNovo = caminhoNovo.substring(0, caminhoNovo.length() - 1); + } - Dir dirantigo = irPara(caminhoAntigo); + if (caminhoAntigo.equals(caminhoNovo)) { + throw new IllegalArgumentException("Caminho antigo e caminho novo não podem ser iguais"); + } - if (!dirantigo.temPerm(usuario, "w")) { - throw new PermissaoException("Usuário não tem permissão para mover: " + caminhoAntigo); - } + Dir dirantigo = irPara(caminhoAntigo); - try { - Dir destino = irPara(caminhoNovo); - if (!destino.temPerm(usuario, "w")) { - throw new PermissaoException("Sem permissão de escrita no destino"); - } - if (destino.getFilhos().containsKey(dirantigo.getNome())) { - throw new IllegalArgumentException("Já existe um diretório ou arquivo com esse nome no destino"); + if (!dirantigo.temPerm(usuario, "w")) { + throw new PermissaoException("Usuário não tem permissão para mover: " + caminhoAntigo); } - dirantigo.getPai().removeFilho(dirantigo.getNome()); - destino.addFilho(dirantigo); + try { + Dir destino = irPara(caminhoNovo); + if (!destino.temPerm(usuario, "w")) { + throw new PermissaoException("Sem permissão de escrita no destino"); + } + if (destino.getFilhos().containsKey(dirantigo.getNome())) { + throw new IllegalArgumentException("Já existe um diretório ou arquivo com esse nome no destino"); + } - } catch (CaminhoNaoEncontradoException e) { - - int idx = caminhoNovo.lastIndexOf('/'); - String novoNome = caminhoNovo.substring(idx + 1); - String caminhoPaiNovo = (idx <= 0) ? "/" : caminhoNovo.substring(0, idx); - Dir novoPai = irPara(caminhoPaiNovo); + dirantigo.getPai().removeFilho(dirantigo.getNome()); + destino.addFilho(dirantigo); - if (!novoPai.temPerm(usuario, "w")) { - throw new PermissaoException("Sem permissão de escrita no novo caminho"); - } - if (novoPai.getFilhos().containsKey(novoNome)) { - throw new IllegalArgumentException("Já existe um objeto com esse nome no destino"); - } + } catch (CaminhoNaoEncontradoException e) { - dirantigo.getPai().removeFilho(dirantigo.getNome()); - dirantigo.setNome(novoNome); - novoPai.addFilho(dirantigo); - } -} + int idx = caminhoNovo.lastIndexOf('/'); + String novoNome = caminhoNovo.substring(idx + 1); + String caminhoPaiNovo = (idx <= 0) ? "/" : caminhoNovo.substring(0, idx); + Dir novoPai = irPara(caminhoPaiNovo); + + if (!novoPai.temPerm(usuario, "w")) { + throw new PermissaoException("Sem permissão de escrita no novo caminho"); + } + if (novoPai.getFilhos().containsKey(novoNome)) { + throw new IllegalArgumentException("Já existe um objeto com esse nome no destino"); + } + dirantigo.getPai().removeFilho(dirantigo.getNome()); + dirantigo.setNome(novoNome); + novoPai.addFilho(dirantigo); + } + } @Override public void ls(String caminho, String usuario, boolean recursivo) @@ -351,10 +357,10 @@ public void cp(String caminhoOrigem, String caminhoDestino, String usuario, bool } caminhoOrigem = caminhoOrigem.replace("\\", "/"); caminhoDestino = caminhoDestino.replace("\\", "/"); - if (caminhoOrigem.endsWith("/")){ + if (caminhoOrigem.endsWith("/")) { caminhoOrigem = caminhoOrigem.substring(0, caminhoOrigem.length() - 1); } - if (caminhoDestino.endsWith("/")){ + if (caminhoDestino.endsWith("/")) { caminhoDestino = caminhoDestino.substring(0, caminhoDestino.length() - 1); } Dir dirOrigem = irPara(caminhoOrigem); @@ -363,7 +369,8 @@ public void cp(String caminhoOrigem, String caminhoDestino, String usuario, bool throw new PermissaoException("Usuário não tem permissão para ler o diretório de origem: " + caminhoOrigem); } if (!dirDestino.temPerm(usuario, "w")) { - throw new PermissaoException("Usuário não tem permissão para escrever no diretório de destino: " + caminhoDestino); + throw new PermissaoException( + "Usuário não tem permissão para escrever no diretório de destino: " + caminhoDestino); } String nomeArquivo = dirOrigem.getNome(); From 906c9d61153aa34c83fcd43045b0357f8e6ea56f Mon Sep 17 00:00:00 2001 From: PiterOfc Date: Sat, 14 Jun 2025 17:37:27 -0300 Subject: [PATCH 20/33] =?UTF-8?q?Feat:=20implementa=C3=A7=C3=A3o=20do=20wr?= =?UTF-8?q?ite?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- filesys/File.java | 2 +- filesys/FileSystemImpl.java | 40 ++++++++++++++++++++++++++++++++++++- 2 files changed, 40 insertions(+), 2 deletions(-) diff --git a/filesys/File.java b/filesys/File.java index 25195b8..b2abcde 100644 --- a/filesys/File.java +++ b/filesys/File.java @@ -43,7 +43,7 @@ public void removeBloco(BlocoDeDados bloco) { } } - public void clearBlocos() { + public void limparBlocos() { this.blocos.clear(); this.tamanho = 0; // Reseta o tamanho do arquivo } diff --git a/filesys/FileSystemImpl.java b/filesys/FileSystemImpl.java index 607909d..2152321 100644 --- a/filesys/FileSystemImpl.java +++ b/filesys/FileSystemImpl.java @@ -268,7 +268,45 @@ public void touch(String caminho, String usuario) @Override public void write(String caminho, String usuario, boolean anexar, byte[] buffer) throws CaminhoNaoEncontradoException, PermissaoException { - throw new UnsupportedOperationException("Método não implementado 'write'"); + if (caminho == null || usuario == null || buffer == null) { + throw new IllegalArgumentException("Caminho, usuário e buffer não podem ser nulos"); + } + + caminho = caminho.replace("\\", "/"); + if (caminho.endsWith("/")) { + caminho = caminho.substring(0, caminho.length() - 1); + } + + Dir diretorio = irPara(caminho); + + if (!diretorio.isArquivo()) { + throw new IllegalArgumentException("O caminho especificado não é um arquivo: " + caminho); + } + + if (!diretorio.temPerm(usuario, "w")) { + throw new PermissaoException("Usuário não tem permissão para escrever: " + caminho); + } + + File arquivo = (File) diretorio; + if (!anexar) arquivo.limparBlocos(); + + int offset = 0; + + while (offset < buffer.length) { + // Tamanho do bloco a ser escrito + int tamanhoBloco = Math.min(buffer.length - offset, File.TAMANHO_BYTES_BLOCO); + // Bloco de dados a ser escrito + byte[] blocoDados = new byte[tamanhoBloco]; + // Copiar dados para o bloco + System.arraycopy(buffer, offset, blocoDados, 0, tamanhoBloco); + + // Criar novo bloco de dados + BlocoDeDados novoBloco = new BlocoDeDados(blocoDados); + // Adicionar bloco ao arquivo + arquivo.addBloco(novoBloco); + // Atualizar offset para o próximo bloco + offset += tamanhoBloco; + } } @Override From d8c0a73185e6f1fbdd14a0da0befc68a385cbfa8 Mon Sep 17 00:00:00 2001 From: PiterOfc Date: Sat, 14 Jun 2025 17:42:52 -0300 Subject: [PATCH 21/33] =?UTF-8?q?Feat:=20implementa=C3=A7=C3=A3o=20do=20re?= =?UTF-8?q?ad?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Main.java | 23 ++++++++++++++-- filesys/FileSystem.java | 4 +-- filesys/FileSystemImpl.java | 53 +++++++++++++++++++++++++++++++++++-- filesys/IFileSystem.java | 4 ++- 4 files changed, 77 insertions(+), 7 deletions(-) diff --git a/Main.java b/Main.java index 3a35e5d..0aef575 100644 --- a/Main.java +++ b/Main.java @@ -235,8 +235,27 @@ public static void read() throws CaminhoNaoEncontradoException, PermissaoExcepti System.out.println("Insira o caminho do arquivo a ser lido:"); String caminho = scanner.nextLine(); byte[] buffer = new byte[READ_BUFFER_SIZE]; // Exemplo de tamanho de buffer por load/leitura . O que acontece se o Buffer for menor que o conteúdo a ser lido? - - fileSystem.read(caminho, user, buffer); // Lógica para ler arquivos maiores que o buffer deve ser implementada. + + int offset = 0; // Offset para leitura + int offsetAntes; + int leitura; + + System.out.println("Lendo arquivo: " + caminho + "\n"); + + do { + offsetAntes = offset; // Salva o offset antes da leitura + offset += fileSystem.read(caminho, user, buffer, offset); // Lê o arquivo no caminho especificado + leitura = offset - offsetAntes; // Calcula a quantidade de bytes lidos nesta iteração + + if (leitura > 0) { + System.out.write(buffer, 0, leitura); // Escreve os bytes lidos no console + } else { + break; // Se não houver mais bytes para ler, sai do loop + } + } while (leitura > 0); // Garante que o offset seja não negativo + + System.out.flush(); // Garante que todos os bytes sejam escritos no console + System.out.println("\n\nLeitura concluída."); } public static void mv() throws CaminhoNaoEncontradoException, PermissaoException { diff --git a/filesys/FileSystem.java b/filesys/FileSystem.java index 13dcb1a..922d68d 100644 --- a/filesys/FileSystem.java +++ b/filesys/FileSystem.java @@ -48,9 +48,9 @@ public void write(String caminho, String usuario, boolean anexar, byte[] buffer) } @Override - public void read(String caminho, String usuario, byte[] buffer) + public int read(String caminho, String usuario, byte[] buffer, int offset) throws CaminhoNaoEncontradoException, PermissaoException { - fileSystemImpl.read(caminho, usuario, buffer); + return fileSystemImpl.read(caminho, usuario, buffer, offset); } @Override diff --git a/filesys/FileSystemImpl.java b/filesys/FileSystemImpl.java index 2152321..d80d5d9 100644 --- a/filesys/FileSystemImpl.java +++ b/filesys/FileSystemImpl.java @@ -310,9 +310,58 @@ public void write(String caminho, String usuario, boolean anexar, byte[] buffer) } @Override - public void read(String caminho, String usuario, byte[] buffer) + public int read(String caminho, String usuario, byte[] buffer, int offset) throws CaminhoNaoEncontradoException, PermissaoException { - throw new UnsupportedOperationException("Método não implementado 'read'"); + if (caminho == null || usuario == null || buffer == null) { + throw new IllegalArgumentException("Caminho, usuário e buffer não podem ser nulos"); + } + + caminho = caminho.replace("\\", "/"); + if (caminho.endsWith("/")) { + caminho = caminho.substring(0, caminho.length() - 1); + } + + Dir diretorio = irPara(caminho); + + if (!diretorio.isArquivo()) { + throw new IllegalArgumentException("O caminho especificado não é um arquivo: " + caminho); + } + + if (!diretorio.temPerm(usuario, "r")) { + throw new PermissaoException("Usuário não tem permissão para ler: " + caminho); + } + + File arquivo = (File) diretorio; + int bufferOffset = 0; + int arquivoOffset = 0; + + // Lê os blocos do arquivo e copia para o buffer + for (BlocoDeDados bloco : arquivo.getBlocos()) { + byte[] dadosBloco = bloco.getDados(); + int tamanhoBloco = dadosBloco.length; + + // Se o offset ainda não foi alcançado, pula bytes + if (arquivoOffset + tamanhoBloco <= offset) { + arquivoOffset += tamanhoBloco; + continue; + } + + // Calcula o início da leitura dentro do bloco + int inicioLeitura = Math.max(0, offset - arquivoOffset); + int bytesDisponiveis = tamanhoBloco - inicioLeitura; + int bytesRestantes = Math.min(buffer.length - bufferOffset, bytesDisponiveis); + + // Copia os dados do bloco para o buffer + System.arraycopy(dadosBloco, inicioLeitura, buffer, bufferOffset, bytesRestantes); + bufferOffset += bytesRestantes; + + // Se o buffer estiver cheio, sai do loop + if (bufferOffset >= buffer.length) { + break; + } + } + + return bufferOffset; } @Override diff --git a/filesys/IFileSystem.java b/filesys/IFileSystem.java index 3e339d5..82a8b20 100644 --- a/filesys/IFileSystem.java +++ b/filesys/IFileSystem.java @@ -32,7 +32,9 @@ public interface IFileSystem { // Lê dados de um arquivo. Se o arquivo não existir, será lançada uma exceção. // Leitura sequencial - todo o conteudo do arquivo sera lido e armazenado no buffer. - void read(String caminho, String usuario, byte[] buffer) throws CaminhoNaoEncontradoException, PermissaoException; + // ADD: offset para indicar a partir de qual posição do buffer os dados serão lidos. + // MOD: void -> int (objetivo: retornar offset do buffer após a leitura) + int read(String caminho, String usuario, byte[] buffer, int offset) throws CaminhoNaoEncontradoException, PermissaoException; // Move ou renomeia um arquivo ou diretório. Se o diretório não existir, será lançada uma exceção. // Se o diretório já existir, será sobrescrito. From 7bc2855a3cde13ab937abbd512d8ce69211fe287 Mon Sep 17 00:00:00 2001 From: PiterOfc Date: Sun, 15 Jun 2025 16:37:15 -0300 Subject: [PATCH 22/33] Feat: implementando addUser --- filesys/FileSystem.java | 5 +++++ filesys/FileSystemImpl.java | 18 ++++++++++++++++-- filesys/IFileSystem.java | 3 +++ 3 files changed, 24 insertions(+), 2 deletions(-) diff --git a/filesys/FileSystem.java b/filesys/FileSystem.java index 922d68d..57cfe93 100644 --- a/filesys/FileSystem.java +++ b/filesys/FileSystem.java @@ -70,4 +70,9 @@ public void cp(String caminhoOrigem, String caminhoDestino, String usuario, bool throws CaminhoNaoEncontradoException, PermissaoException { fileSystemImpl.cp(caminhoOrigem, caminhoDestino, usuario, recursivo); } + + @Override + public void addUser(Usuario usuario) { + fileSystemImpl.addUser(usuario); + } } \ No newline at end of file diff --git a/filesys/FileSystemImpl.java b/filesys/FileSystemImpl.java index d80d5d9..a56ea98 100644 --- a/filesys/FileSystemImpl.java +++ b/filesys/FileSystemImpl.java @@ -482,7 +482,21 @@ public void cp(String caminhoOrigem, String caminhoDestino, String usuario, bool } - public void addUser(String user) { - throw new UnsupportedOperationException("Método não implementado 'addUser'"); + @Override + public void addUser(Usuario usuario) { + if (usuario == null || usuario.getNome() == null || usuario.getPermissoes() == null) { + throw new IllegalArgumentException("Usuário, nome e permissões não podem ser nulos"); + } + + // Verifica se o usuário já existe + for (Usuario u : usuarios) { + if (u.getNome().equals(usuario.getNome())) { + throw new IllegalArgumentException("Usuário já existe: " + usuario.getNome()); + } + } + + // Adiciona o novo usuário + usuarios.add(usuario); + System.out.println("Usuário adicionado: " + usuario.getNome()); } } diff --git a/filesys/IFileSystem.java b/filesys/IFileSystem.java index 82a8b20..60a815c 100644 --- a/filesys/IFileSystem.java +++ b/filesys/IFileSystem.java @@ -47,4 +47,7 @@ public interface IFileSystem { // Copia um arquivo ou diretório. Se o diretório não existir, será lançada uma exceção. void cp(String caminhoOrigem, String caminhoDestino, String usuario, boolean recursivo) throws CaminhoNaoEncontradoException, PermissaoException; + + // ADD: adiciona um usuário ao sistema de arquivos + void addUser(Usuario usuario); } \ No newline at end of file From 4e8fe8cf389e36324242c32828ac68e8241fa84b Mon Sep 17 00:00:00 2001 From: PiterOfc Date: Sun, 15 Jun 2025 16:42:55 -0300 Subject: [PATCH 23/33] Feat: implementando testes mkdir, touch e chmod --- tests/PermissionTest.java | 81 ++++++++++++++++++++++++++++++++++++--- 1 file changed, 76 insertions(+), 5 deletions(-) diff --git a/tests/PermissionTest.java b/tests/PermissionTest.java index 6026e31..785c373 100644 --- a/tests/PermissionTest.java +++ b/tests/PermissionTest.java @@ -3,24 +3,95 @@ import static org.junit.Assert.assertTrue; import org.junit.jupiter.api.Test; + +import exception.CaminhoJaExistenteException; +import exception.CaminhoNaoEncontradoException; +import exception.PermissaoException; + +import static org.junit.jupiter.api.Assertions.*; import org.junit.jupiter.api.Assertions.*; import org.junit.jupiter.api.BeforeAll; import filesys.FileSystemImpl; import filesys.IFileSystem; +import filesys.Usuario; // Essa classe testa cenários de permissão public class PermissionTest { private static IFileSystem fileSystem; @BeforeAll - public static void setUp() { - fileSystem = new FileSystemImpl(/*args...*/); + public static void setUp() throws CaminhoJaExistenteException, PermissaoException, CaminhoNaoEncontradoException { + fileSystem = new FileSystemImpl(); + fileSystem.addUser(new Usuario("maria", "/", "r-x")); + fileSystem.addUser(new Usuario("joao", "/", "rwx")); + fileSystem.addUser(new Usuario("tiago", "/", "rw-")); + + fileSystem.mkdir("/area1", "joao"); + fileSystem.mkdir("/area1/area2", "tiago"); + } + + + // =============== MKDIR =============== + + @Test + public void testMkdirSuccess() throws CaminhoJaExistenteException, PermissaoException { + // Tenta criar um diretório com permissão de rwx + assertDoesNotThrow(() -> fileSystem.mkdir("/area1/area2/area3", "root")); + } + + @Test + public void testMkdirPermissionFail() { + // Tenta criar um diretório sem permissão + assertThrows(PermissaoException.class, () -> fileSystem.mkdir("/area1/area2/area3/area4", "maria")); + } + + @Test + public void testMkdirPathFail() { + // Tenta criar um diretório em um caminho inexistente + assertThrows(CaminhoNaoEncontradoException.class, () -> fileSystem.mkdir("/area1/area2/area3/inexistente/area5", "joao")); + } + + + // =============== TOUCH =============== + + @Test + public void testTouchSuccess() throws CaminhoJaExistenteException, PermissaoException, CaminhoNaoEncontradoException { + // Tenta criar um arquivo com permissão de rwx + assertDoesNotThrow(() -> fileSystem.touch("/area1/area2/arquivo.txt", "joao")); + } + + @Test + public void testTouchPermissionFail() { + // Tenta criar um arquivo sem permissão + assertThrows(PermissaoException.class, () -> fileSystem.touch("/area1/area2/arquivo2.txt", "maria")); } @Test - public void testPermission() { - // Teste de permissão - assertTrue(true); + public void testTouchPathFail() { + // Tenta criar um arquivo em um caminho inexistente + assertThrows(CaminhoNaoEncontradoException.class, () -> fileSystem.touch("/area1/area2/inexistente/arquivo3.txt", "root")); } + + + // =============== CHMOD =============== + + @Test + public void testChmodSuccess() throws CaminhoNaoEncontradoException, PermissaoException { + // Tenta alterar as permissões de um diretório existente + assertDoesNotThrow(() -> fileSystem.chmod("/area1/area2", "root", "tiago", "rwx")); + } + + @Test + public void testChmodPermissionFail() { + // Tenta alterar as permissões de um diretório sem permissão + assertThrows(PermissaoException.class, () -> fileSystem.chmod("/area1/area2", "maria", "tiago", "rwx")); + } + + @Test + public void testChmodPathFail() { + // Tenta alterar as permissões de um diretório inexistente + assertThrows(CaminhoNaoEncontradoException.class, () -> fileSystem.chmod("/area1/area2/inexistente", "root", "tiago", "rwx")); + } + } From 4fd166ecbe0cbc6f2c9a2a1188dc4f630bb9c5f6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Leonardo=20de=20Souza=20Galv=C3=A3o?= <160603231+LeonardodeSouzaGalvao@users.noreply.github.com> Date: Mon, 16 Jun 2025 19:36:55 -0300 Subject: [PATCH 24/33] =?UTF-8?q?Corre=C3=A7=C3=A3o=20de=20permiss=C3=B5es?= =?UTF-8?q?=20e=20mais=20testes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- filesys/FileSystemImpl.java | 8 +- tests/PermissionTest.java | 142 ++++++++++++++++++++++++++++++++++-- 2 files changed, 139 insertions(+), 11 deletions(-) diff --git a/filesys/FileSystemImpl.java b/filesys/FileSystemImpl.java index a56ea98..23f5584 100644 --- a/filesys/FileSystemImpl.java +++ b/filesys/FileSystemImpl.java @@ -368,7 +368,7 @@ public int read(String caminho, String usuario, byte[] buffer, int offset) public void mv(String caminhoAntigo, String caminhoNovo, String usuario) throws CaminhoNaoEncontradoException, PermissaoException { if (caminhoAntigo == null || caminhoNovo == null || usuario == null) { - throw new IllegalArgumentException("Caminho antigo, caminho novo e usuário não podem ser nulos"); + throw new PermissaoException("Caminho antigo, caminho novo e usuário não podem ser nulos"); } caminhoAntigo = caminhoAntigo.replace("\\", "/"); @@ -382,7 +382,7 @@ public void mv(String caminhoAntigo, String caminhoNovo, String usuario) } if (caminhoAntigo.equals(caminhoNovo)) { - throw new IllegalArgumentException("Caminho antigo e caminho novo não podem ser iguais"); + throw new PermissaoException("Caminho antigo e caminho novo não podem ser iguais"); } Dir dirantigo = irPara(caminhoAntigo); @@ -397,7 +397,7 @@ public void mv(String caminhoAntigo, String caminhoNovo, String usuario) throw new PermissaoException("Sem permissão de escrita no destino"); } if (destino.getFilhos().containsKey(dirantigo.getNome())) { - throw new IllegalArgumentException("Já existe um diretório ou arquivo com esse nome no destino"); + throw new PermissaoException("Já existe um diretório ou arquivo com esse nome no destino"); } dirantigo.getPai().removeFilho(dirantigo.getNome()); @@ -463,7 +463,7 @@ public void cp(String caminhoOrigem, String caminhoDestino, String usuario, bool String nomeArquivo = dirOrigem.getNome(); String caminhoCompletoDestino = dirDestino.getCaminhoCompleto() + "/" + nomeArquivo; if (dirDestino.getFilhos().containsKey(nomeArquivo)) { - throw new IllegalArgumentException("Arquivo ou diretório já existe no destino: " + caminhoCompletoDestino); + throw new PermissaoException("Arquivo ou diretório já existe no destino: " + caminhoCompletoDestino); } if (dirOrigem.isArquivo()) { File novoArquivo = new File(nomeArquivo, usuario, "rwx"); diff --git a/tests/PermissionTest.java b/tests/PermissionTest.java index 785c373..b5e0ba6 100644 --- a/tests/PermissionTest.java +++ b/tests/PermissionTest.java @@ -19,10 +19,12 @@ // Essa classe testa cenários de permissão public class PermissionTest { private static IFileSystem fileSystem; + byte[] buffer = new byte[1024]; @BeforeAll public static void setUp() throws CaminhoJaExistenteException, PermissaoException, CaminhoNaoEncontradoException { fileSystem = new FileSystemImpl(); + fileSystem.addUser(new Usuario("maria", "/", "r-x")); fileSystem.addUser(new Usuario("joao", "/", "rwx")); fileSystem.addUser(new Usuario("tiago", "/", "rw-")); @@ -46,12 +48,6 @@ public void testMkdirPermissionFail() { assertThrows(PermissaoException.class, () -> fileSystem.mkdir("/area1/area2/area3/area4", "maria")); } - @Test - public void testMkdirPathFail() { - // Tenta criar um diretório em um caminho inexistente - assertThrows(CaminhoNaoEncontradoException.class, () -> fileSystem.mkdir("/area1/area2/area3/inexistente/area5", "joao")); - } - // =============== TOUCH =============== @@ -94,4 +90,136 @@ public void testChmodPathFail() { assertThrows(CaminhoNaoEncontradoException.class, () -> fileSystem.chmod("/area1/area2/inexistente", "root", "tiago", "rwx")); } -} + // =============== LS =============== + @Test + public void testLsSuccess() throws CaminhoNaoEncontradoException, PermissaoException { + // Tenta listar o conteúdo de um diretório com permissão + assertDoesNotThrow(() -> fileSystem.ls("/area1", "joao", true)); + } + + @Test + public void testlsNaoRecursiveSuccess() throws CaminhoNaoEncontradoException, PermissaoException { + // Tenta listar o conteúdo de um diretório sem permissão de leitura recursiva + assertDoesNotThrow(() -> fileSystem.ls("/area1", "joao", false)); + } + + @Test + public void testLsPermissionFail() { + // Tenta listar o conteúdo de um diretório sem permissão + assertThrows(PermissaoException.class, () -> fileSystem.ls("/area1/area2", "maria", true)); + } + + @Test + public void testLsPathFail() { + // Tenta listar o conteúdo de um diretório inexistente + assertThrows(CaminhoNaoEncontradoException.class, () -> fileSystem.ls("/area1/area2/inexistente", "joao", true)); + } + + // =============== CP =============== + @Test + public void testCpSuccess() throws CaminhoNaoEncontradoException, PermissaoException { + // Tenta copiar um arquivo com permissão + assertDoesNotThrow(() -> fileSystem.cp("/area1/area2/arquivo.txt", "/area1/area2/arquivo_copiado.txt", "joao", true)); + } + + @Test + public void testCpPermissionFail() { + // Tenta copiar um arquivo sem permissão + assertThrows(PermissaoException.class, () -> fileSystem.cp("/area1/area2/arquivo.txt", "/area1/area2/arquivo_copiado.txt", "maria", true)); + } + + @Test + public void testCpPathFail() { + // Tenta copiar um arquivo de um caminho inexistente + assertThrows(CaminhoNaoEncontradoException.class, () -> fileSystem.cp("/area1/area2/inexistente/arquivo.txt", "/area1/area2/arquivo_copiado.txt", "joao", true)); + } + + // =============== RM =============== + @Test + public void testRmSuccess() throws CaminhoNaoEncontradoException, PermissaoException { + // Tenta remover um arquivo com permissão + assertDoesNotThrow(() -> fileSystem.rm("/area1/area2/arquivo.txt", "joao", true)); + } + + @Test + public void testRmPermissionFail() { + // Tenta remover um arquivo sem permissão + assertThrows(PermissaoException.class, () -> fileSystem.rm("/area1/area2/arquivo.txt", "maria", true)); + } + + @Test + public void testRmPathFail() { + // Tenta remover um arquivo de um caminho inexistente + assertThrows(CaminhoNaoEncontradoException.class, () -> fileSystem.rm("/area1/area2/inexistente/arquivo.txt", "joao", true)); + } + + // =============== MV =============== + + @Test + public void testMvInSamePlaceRenamingSuccess() throws CaminhoNaoEncontradoException, PermissaoException { + // Tenta mover um arquivo com permissão + assertDoesNotThrow(() -> fileSystem.mv("/area1/area2/arquivo.txt", "/area1/area2/arquivo_moved.txt", "joao")); + } + + @Test + public void testMvInSamePlaceFail() { + // Tenta mover um arquivo para o mesmo lugar sem permissão + assertThrows(PermissaoException.class, () -> fileSystem.mv("/area1/area2/arquivo.txt", "/area1/area2/arquivo.txt", "maria")); + } + + @Test + public void testMvPermissionFail() { + // Tenta mover um arquivo sem permissão + assertThrows(PermissaoException.class, () -> fileSystem.mv("/area1/area2/arquivo.txt", "/area1/area2/arquivo_moved.txt", "maria")); + } + + @Test + public void testMvPathFail() { + // Tenta mover um arquivo de um caminho inexistente + assertThrows(CaminhoNaoEncontradoException.class, () -> fileSystem.mv("/area1/area2/inexistente/arquivo.txt", "/area1/area2/arquivo_moved.txt", "joao")); + } + + // =============== READ =============== + + @Test + public void testReadSuccess() throws CaminhoNaoEncontradoException, PermissaoException { + // Tenta ler um arquivo com permissão + assertDoesNotThrow(() -> fileSystem.read("/area1/area2/arquivo.txt", "joao", buffer, 0)); + } + + @Test + public void testReadPermissionFail() { + // Tenta ler um arquivo sem permissão + assertThrows(PermissaoException.class, () -> fileSystem.read("/area1/area2/arquivo.txt", "maria", buffer, 0)); + } + + @Test + public void testReadPathFail() { + // Tenta ler um arquivo de um caminho inexistente + assertThrows(CaminhoNaoEncontradoException.class, () -> fileSystem.read("/area1/area2/inexistente/arquivo.txt", "joao", buffer, 0)); + } + + // =============== WRITE =============== + @Test + public void testWriteSuccess() throws CaminhoNaoEncontradoException, PermissaoException { + // Tenta escrever em um arquivo com permissão + assertDoesNotThrow(() -> fileSystem.write("/area1/area2/arquivo.txt", "joao", true, buffer)); + } + + @Test + public void testWritePermissionFail() { + // Tenta escrever em um arquivo sem permissão + assertThrows(PermissaoException.class, () -> fileSystem.write("/area1/area2/arquivo.txt", "maria", true, buffer)); + } + + @Test + public void testWritePathFail() { + // Tenta escrever em um arquivo de um caminho inexistente + assertThrows(CaminhoNaoEncontradoException.class, () -> fileSystem.write("/area1/area2/inexistente/arquivo.txt", "joao", true, buffer)); + } + + + + + +} \ No newline at end of file From 43ce51f0efc696d972a651d89482d53c6c45b5ca Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Leonardo=20de=20Souza=20Galv=C3=A3o?= <160603231+LeonardodeSouzaGalvao@users.noreply.github.com> Date: Tue, 17 Jun 2025 19:36:26 -0300 Subject: [PATCH 25/33] =?UTF-8?q?Feature/=20Comando=20Cp=20agora=20sobresc?= =?UTF-8?q?reve=20outros=20arquivos=20Corre=C3=A7=C3=A3o=20testes=20Junit?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- filesys/FileSystemImpl.java | 181 ++++++++++++++++++++++++++---------- tests/PermissionTest.java | 15 +-- 2 files changed, 141 insertions(+), 55 deletions(-) diff --git a/filesys/FileSystemImpl.java b/filesys/FileSystemImpl.java index 23f5584..82ac70e 100644 --- a/filesys/FileSystemImpl.java +++ b/filesys/FileSystemImpl.java @@ -149,15 +149,25 @@ public void mkdir(String caminho, String usuario) throws CaminhoJaExistenteExcep continue; // Se já existe, não cria novamente } - // Verifica se o usuário existe - usuarios.stream() - .filter(u -> u.getNome().equals(usuario)) - .findFirst() - .orElseThrow(() -> new IllegalArgumentException("Usuário não encontrado: " + usuario)); - // Verifica se o usuário tem permissão para criar o diretório - if (!diretorioAtual.temPerm(usuario, "w")) { - throw new PermissaoException("Usuário não tem permissão para criar diretório: " + caminhoAtual); + Usuario usuarioObj = null; + + for (Usuario user : usuarios) { + if (user.getNome().equals(usuario)) { + usuarioObj = user; + } + } + + if (usuarioObj == null) { + new IllegalArgumentException("Usuário não encontrado: " + usuario); + } + + if (!usuarioObj.getPermissoes().contains("w")) { + try { + diretorioAtual.temPerm(usuario, "w"); + } catch(IllegalArgumentException e) { + throw new PermissaoException("Usuário não tem permissão para criar diretório: " + diretorioAtual); + } } // Cria o novo diretório @@ -192,8 +202,25 @@ public void chmod(String caminho, String usuario, String usuarioAlvo, String per Dir dir = irPara(caminho); - if (!dir.temPerm(usuario, "w")) { - throw new PermissaoException("Usuário não tem permissão para alterar permissões: " + caminho); + // Verifica se o usuário tem permissão para criar o diretório + Usuario usuarioObj = null; + + for (Usuario user : usuarios) { + if (user.getNome().equals(usuario)) { + usuarioObj = user; + } + } + + if (usuarioObj == null) { + new IllegalArgumentException("Usuário não encontrado: " + usuario); + } + + if (!usuarioObj.getPermissoes().contains("w")) { + try { + dir.temPerm(usuario, "w"); + } catch(IllegalArgumentException e) { + throw new PermissaoException("Usuário não tem permissão para criar diretório: " + dir); + } } dir.setPermissoesUsuario(usuarioAlvo, permissao); @@ -428,8 +455,25 @@ public void ls(String caminho, String usuario, boolean recursivo) throws CaminhoNaoEncontradoException, PermissaoException { Dir diretorio = irPara(caminho); - if (!diretorio.temPerm(usuario, "r")) { - throw new PermissaoException("Você não tem permissão para listar este diretório!"); + // Verifica se o usuário tem permissão para criar o diretório + Usuario usuarioObj = null; + + for (Usuario user : usuarios) { + if (user.getNome().equals(usuario)) { + usuarioObj = user; + } + } + + if (usuarioObj == null) { + new IllegalArgumentException("Usuário não encontrado: " + usuario); + } + + if (!usuarioObj.getPermissoes().contains("r")) { + try { + diretorio.temPerm(usuario, "r"); + } catch(IllegalArgumentException e) { + throw new PermissaoException("Você não tem permissão para listar este diretório!"); + } } String output = lsRecursivo(diretorio, caminho, recursivo, usuario); @@ -437,50 +481,89 @@ public void ls(String caminho, String usuario, boolean recursivo) } @Override - public void cp(String caminhoOrigem, String caminhoDestino, String usuario, boolean recursivo) - throws CaminhoNaoEncontradoException, PermissaoException { - if (caminhoOrigem == null || caminhoDestino == null || usuario == null) { - throw new IllegalArgumentException("Caminho de origem, destino e usuário não podem ser nulos"); - } - caminhoOrigem = caminhoOrigem.replace("\\", "/"); - caminhoDestino = caminhoDestino.replace("\\", "/"); - if (caminhoOrigem.endsWith("/")) { - caminhoOrigem = caminhoOrigem.substring(0, caminhoOrigem.length() - 1); +public void cp(String caminhoOrigem, String caminhoDestino, String usuario, boolean recursivo) + throws CaminhoNaoEncontradoException, PermissaoException { + if (caminhoOrigem == null || caminhoDestino == null || usuario == null) { + throw new IllegalArgumentException("Caminho de origem, destino e usuário não podem ser nulos"); + } + + caminhoOrigem = caminhoOrigem.replace("\\", "/").replaceAll("/$", ""); + caminhoDestino = caminhoDestino.replace("\\", "/").replaceAll("/$", ""); + + Dir origem = irPara(caminhoOrigem); + Dir destino = irPara(caminhoDestino); + + Usuario usuarioObj = usuarios.stream() + .filter(u -> u.getNome().equals(usuario)) + .findFirst() + .orElseThrow(() -> new IllegalArgumentException("Usuário não encontrado: " + usuario)); + + if (!usuarioObj.getPermissoes().contains("rw")) { + if (!origem.temPerm(usuario, "r")) + throw new PermissaoException("Sem permissão de leitura em: " + caminhoOrigem); + if (!destino.temPerm(usuario, "w")) + throw new PermissaoException("Sem permissão de escrita em: " + caminhoDestino); + } + + String nomeOrigem = origem.getNome(); + + // Se destino for um arquivo, substituí-lo se possível + if (destino instanceof File) { + if (!origem.isArquivo()) { + throw new IllegalArgumentException("Não é possível copiar um diretório para um arquivo"); } - if (caminhoDestino.endsWith("/")) { - caminhoDestino = caminhoDestino.substring(0, caminhoDestino.length() - 1); + copiarConteudoArquivo((File) origem, (File) destino, usuario); + System.out.println("Arquivo sobrescrito: " + destino.getCaminhoCompleto()); + return; + } + + // Se for diretório, verificar se já existe um filho com o mesmo nome + Dir existente = destino.getFilhos().get(nomeOrigem); + + if (existente != null) { + // Se for arquivo, sobrescreve + if (existente.isArquivo() && origem.isArquivo()) { + copiarConteudoArquivo((File) origem, (File) existente, usuario); + System.out.println("Arquivo sobrescrito: " + existente.getCaminhoCompleto()); + return; + } else { + throw new PermissaoException("Já existe um diretório/arquivo com esse nome: " + existente.getCaminhoCompleto()); } - Dir dirOrigem = irPara(caminhoOrigem); - Dir dirDestino = irPara(caminhoDestino); - if (!dirOrigem.temPerm(usuario, "r")) { - throw new PermissaoException("Usuário não tem permissão para ler o diretório de origem: " + caminhoOrigem); + } + + if (origem.isArquivo()) { + File arquivoOrigem = (File) origem; + File arquivoNovo = new File(arquivoOrigem.getNome(), usuario, "rwx"); + for (BlocoDeDados bloco : arquivoOrigem.getBlocos()) { + // Copia física dos blocos + byte[] dadosCopiados = bloco.getDados().clone(); // copia conteúdo + arquivoNovo.addBloco(new BlocoDeDados(dadosCopiados)); } - if (!dirDestino.temPerm(usuario, "w")) { - throw new PermissaoException( - "Usuário não tem permissão para escrever no diretório de destino: " + caminhoDestino); + destino.addFilho(arquivoNovo); + System.out.println("Arquivo copiado: " + arquivoNovo.getCaminhoCompleto()); + } else { + if (!recursivo) { + throw new IllegalArgumentException("Cópia de diretório requer o modo recursivo"); } - String nomeArquivo = dirOrigem.getNome(); - String caminhoCompletoDestino = dirDestino.getCaminhoCompleto() + "/" + nomeArquivo; - if (dirDestino.getFilhos().containsKey(nomeArquivo)) { - throw new PermissaoException("Arquivo ou diretório já existe no destino: " + caminhoCompletoDestino); - } - if (dirOrigem.isArquivo()) { - File novoArquivo = new File(nomeArquivo, usuario, "rwx"); - dirDestino.addFilho(novoArquivo); - System.out.println("Arquivo copiado de " + caminhoOrigem + " para " + caminhoCompletoDestino); - } else { - Dir novoDiretorio = new Dir(nomeArquivo, usuario, "rwx"); - dirDestino.addFilho(novoDiretorio); - for (Dir filho : dirOrigem.getFilhos().values()) { - String caminhoFilhoOrigem = filho.getCaminhoCompleto(); - String caminhoFilhoDestino = novoDiretorio.getCaminhoCompleto() + "/" + filho.getNome(); - cp(caminhoFilhoOrigem, caminhoFilhoDestino, usuario, recursivo); - } - System.out.println("Diretório copiado de " + caminhoOrigem + " para " + caminhoCompletoDestino); + Dir novoDir = new Dir(origem.getNome(), usuario, "rwx"); + destino.addFilho(novoDir); + for (Dir filho : origem.getFilhos().values()) { + cp(filho.getCaminhoCompleto(), novoDir.getCaminhoCompleto(), usuario, true); } + System.out.println("Diretório copiado: " + novoDir.getCaminhoCompleto()); + } +} +// Método auxiliar +private void copiarConteudoArquivo(File origem, File destino, String usuario) { + destino.limparBlocos(); + for (BlocoDeDados bloco : origem.getBlocos()) { + byte[] dadosCopiados = bloco.getDados().clone(); + destino.addBloco(new BlocoDeDados(dadosCopiados)); } +} + @Override public void addUser(Usuario usuario) { @@ -499,4 +582,4 @@ public void addUser(Usuario usuario) { usuarios.add(usuario); System.out.println("Usuário adicionado: " + usuario.getNome()); } -} +} \ No newline at end of file diff --git a/tests/PermissionTest.java b/tests/PermissionTest.java index b5e0ba6..45295f8 100644 --- a/tests/PermissionTest.java +++ b/tests/PermissionTest.java @@ -28,9 +28,12 @@ public static void setUp() throws CaminhoJaExistenteException, PermissaoExceptio fileSystem.addUser(new Usuario("maria", "/", "r-x")); fileSystem.addUser(new Usuario("joao", "/", "rwx")); fileSystem.addUser(new Usuario("tiago", "/", "rw-")); + fileSystem.addUser(new Usuario("cega", "/", "-wx")); fileSystem.mkdir("/area1", "joao"); fileSystem.mkdir("/area1/area2", "tiago"); + + fileSystem.touch("/area1/area2/arquivo.txt", "root"); } @@ -106,7 +109,7 @@ public void testlsNaoRecursiveSuccess() throws CaminhoNaoEncontradoException, Pe @Test public void testLsPermissionFail() { // Tenta listar o conteúdo de um diretório sem permissão - assertThrows(PermissaoException.class, () -> fileSystem.ls("/area1/area2", "maria", true)); + assertThrows(PermissaoException.class, () -> fileSystem.ls("/area1/area2", "cega", true)); } @Test @@ -119,19 +122,19 @@ public void testLsPathFail() { @Test public void testCpSuccess() throws CaminhoNaoEncontradoException, PermissaoException { // Tenta copiar um arquivo com permissão - assertDoesNotThrow(() -> fileSystem.cp("/area1/area2/arquivo.txt", "/area1/area2/arquivo_copiado.txt", "joao", true)); + assertDoesNotThrow(() -> fileSystem.cp("/area1/area2/arquivo.txt", "/area1", "root", true)); } @Test public void testCpPermissionFail() { // Tenta copiar um arquivo sem permissão - assertThrows(PermissaoException.class, () -> fileSystem.cp("/area1/area2/arquivo.txt", "/area1/area2/arquivo_copiado.txt", "maria", true)); + assertThrows(PermissaoException.class, () -> fileSystem.cp("/area1/area2/arquivo.txt", "/area1/area2", "maria", true)); } @Test public void testCpPathFail() { // Tenta copiar um arquivo de um caminho inexistente - assertThrows(CaminhoNaoEncontradoException.class, () -> fileSystem.cp("/area1/area2/inexistente/arquivo.txt", "/area1/area2/arquivo_copiado.txt", "joao", true)); + assertThrows(CaminhoNaoEncontradoException.class, () -> fileSystem.cp("/area1/area2/inexistente/arquivo.txt", "/area1/area2", "root", true)); } // =============== RM =============== @@ -164,7 +167,7 @@ public void testMvInSamePlaceRenamingSuccess() throws CaminhoNaoEncontradoExcept @Test public void testMvInSamePlaceFail() { // Tenta mover um arquivo para o mesmo lugar sem permissão - assertThrows(PermissaoException.class, () -> fileSystem.mv("/area1/area2/arquivo.txt", "/area1/area2/arquivo.txt", "maria")); + assertThrows(PermissaoException.class, () -> fileSystem.mv("/area1/area2/arquivo.txt", "/area1/area2/arquivo.txt", "root")); } @Test @@ -176,7 +179,7 @@ public void testMvPermissionFail() { @Test public void testMvPathFail() { // Tenta mover um arquivo de um caminho inexistente - assertThrows(CaminhoNaoEncontradoException.class, () -> fileSystem.mv("/area1/area2/inexistente/arquivo.txt", "/area1/area2/arquivo_moved.txt", "joao")); + assertThrows(CaminhoNaoEncontradoException.class, () -> fileSystem.mv("/area1/area2/inexistente/arquivo.txt", "/area1/area2/arquivo_moved.txt", "root")); } // =============== READ =============== From 9f4ca12864b0d1e8af2c7243ef6734a27d4eca60 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Leonardo=20de=20Souza=20Galv=C3=A3o?= <160603231+LeonardodeSouzaGalvao@users.noreply.github.com> Date: Tue, 17 Jun 2025 20:12:48 -0300 Subject: [PATCH 26/33] Fixing some tests --- filesys/FileSystemImpl.java | 22 +++++++++++++++++++--- tests/PermissionTest.java | 8 +++++++- 2 files changed, 26 insertions(+), 4 deletions(-) diff --git a/filesys/FileSystemImpl.java b/filesys/FileSystemImpl.java index 82ac70e..a4e1614 100644 --- a/filesys/FileSystemImpl.java +++ b/filesys/FileSystemImpl.java @@ -283,9 +283,25 @@ public void touch(String caminho, String usuario) throw new CaminhoJaExistenteException("Arquivo ou diretório já existe: " + caminho); } - if (!dirPai.temPerm(usuario, "w")) { - throw new PermissaoException("Usuário não tem permissão para criar arquivo: " + caminho); - } + Usuario usuarioObj = null; + + for (Usuario user : usuarios) { + if (user.getNome().equals(usuario)) { + usuarioObj = user; + } + } + + if (usuarioObj == null) { + new IllegalArgumentException("Usuário não encontrado: " + usuario); + } + + if (!usuarioObj.getPermissoes().contains("w")) { + try { + dirPai.temPerm(usuario, "w"); + } catch(IllegalArgumentException e) { + throw new PermissaoException("Usuário não tem permissão para criar diretório: " + dirPai); + } + } File novoArquivo = new File(nomeArquivo, usuario, "rwx"); dirPai.addFilho(novoArquivo); diff --git a/tests/PermissionTest.java b/tests/PermissionTest.java index 45295f8..3ae8e61 100644 --- a/tests/PermissionTest.java +++ b/tests/PermissionTest.java @@ -57,7 +57,7 @@ public void testMkdirPermissionFail() { @Test public void testTouchSuccess() throws CaminhoJaExistenteException, PermissaoException, CaminhoNaoEncontradoException { // Tenta criar um arquivo com permissão de rwx - assertDoesNotThrow(() -> fileSystem.touch("/area1/area2/arquivo.txt", "joao")); + assertDoesNotThrow(() -> fileSystem.touch("/area1/arquivo.txt", "joao")); } @Test @@ -137,6 +137,12 @@ public void testCpPathFail() { assertThrows(CaminhoNaoEncontradoException.class, () -> fileSystem.cp("/area1/area2/inexistente/arquivo.txt", "/area1/area2", "root", true)); } + @Test + public void testSobrescreverArquivoSucesso() throws CaminhoNaoEncontradoException, PermissaoException { + // Tenta copiar um arquivo sobrescrevendo outro existente + assertDoesNotThrow(() -> fileSystem.cp("/area1/area2/arquivo.txt", "/area1/area2/arquivo.txt", "joao", true)); + } + // =============== RM =============== @Test public void testRmSuccess() throws CaminhoNaoEncontradoException, PermissaoException { From 80defbd972a51530d2ce48defbcc37beecdafef5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Leonardo=20de=20Souza=20Galv=C3=A3o?= <160603231+LeonardodeSouzaGalvao@users.noreply.github.com> Date: Wed, 18 Jun 2025 21:35:22 -0300 Subject: [PATCH 27/33] Fix: Some tests --- filesys/FileSystemImpl.java | 134 ++++++++++++++++++++++++++++-------- tests/PermissionTest.java | 12 +++- 2 files changed, 115 insertions(+), 31 deletions(-) diff --git a/filesys/FileSystemImpl.java b/filesys/FileSystemImpl.java index a4e1614..7f17c23 100644 --- a/filesys/FileSystemImpl.java +++ b/filesys/FileSystemImpl.java @@ -228,39 +228,82 @@ public void chmod(String caminho, String usuario, String usuarioAlvo, String per } @Override - public void rm(String caminho, String usuario, boolean recursivo) - throws CaminhoNaoEncontradoException, PermissaoException { - if (caminho == null || usuario == null) { - throw new IllegalArgumentException("Caminho e usuário não podem ser nulos"); - } +public void rm(String caminho, String usuario, boolean recursivo) + throws CaminhoNaoEncontradoException, PermissaoException { - caminho = caminho.replace("\\", "/"); - if (caminho.endsWith("/")) - caminho = caminho.substring(0, caminho.length() - 1); + if (caminho == null || usuario == null) { + throw new IllegalArgumentException("Caminho e usuário não podem ser nulos"); + } - Dir dir = irPara(caminho); + caminho = caminho.replace("\\", "/"); + if (caminho.endsWith("/")) + caminho = caminho.substring(0, caminho.length() - 1); + + Dir dir; + + try { + dir = irPara(caminho); + } catch (CaminhoNaoEncontradoException e) { + // Tentativa de recuperar o arquivo pelo pai + int ultimoBarra = caminho.lastIndexOf('/'); + if (ultimoBarra == -1) throw e; + + String caminhoPai = caminho.substring(0, ultimoBarra); + String nomeArquivo = caminho.substring(ultimoBarra + 1); + + Dir pai = irPara(caminhoPai); + Dir possivelArquivo = pai.getFilhos().get(nomeArquivo); + + if (possivelArquivo != null && possivelArquivo.isArquivo()) { + dir = possivelArquivo; + } else { + throw new CaminhoNaoEncontradoException("Arquivo ou diretório não encontrado: " + caminho); + } + } - if (!dir.temPerm(usuario, "w")) { - throw new PermissaoException("Usuário não tem permissão para remover: " + caminho); + // Busca o objeto usuário + Usuario usuarioObj = null; + for (Usuario user : usuarios) { + if (user.getNome().equals(usuario)) { + usuarioObj = user; + break; } - if (dir.temSubdiretorios() && !recursivo) { - throw new PermissaoException( - "Esse diretório contém subdiretórios. Use o parâmetro recursivo para removê-lo."); + } + + if (usuarioObj == null) { + throw new IllegalArgumentException("Usuário não encontrado: " + usuario); + } + + // Verifica permissão de escrita + if (!usuarioObj.getPermissoes().contains("w")) { + try { + dir.temPerm(usuario, "w"); + } catch (IllegalArgumentException e) { + throw new PermissaoException("Usuário não tem permissão para remover: " + dir.getNome()); } + } - if (dir.isArquivo()) { - dir.getPai().removeFilho(dir.getNome()); - System.out.println("Arquivo removido: " + caminho); - } else { - if (recursivo) { - for (Dir filho : dir.getFilhos().values()) { - rm(filho.getCaminhoCompleto(), usuario, true); - } + // Verifica se pode remover diretório com conteúdo + if (!dir.isArquivo() && dir.temSubdiretorios() && !recursivo) { + throw new PermissaoException( + "Esse diretório contém subdiretórios. Use o parâmetro recursivo para removê-lo."); + } + + // Remoção + if (dir.isArquivo()) { + dir.getPai().removeFilho(dir.getNome()); + System.out.println("Arquivo removido: " + caminho); + } else { + if (recursivo) { + for (Dir filho : new ArrayList<>(dir.getFilhos().values())) { + rm(filho.getCaminhoCompleto(), usuario, true); } - dir.getPai().removeFilho(dir.getNome()); - System.out.println("Diretório removido: " + caminho); } + dir.getPai().removeFilho(dir.getNome()); + System.out.println("Diretório removido: " + caminho); } +} + @Override public void touch(String caminho, String usuario) @@ -326,9 +369,25 @@ public void write(String caminho, String usuario, boolean anexar, byte[] buffer) throw new IllegalArgumentException("O caminho especificado não é um arquivo: " + caminho); } - if (!diretorio.temPerm(usuario, "w")) { - throw new PermissaoException("Usuário não tem permissão para escrever: " + caminho); - } + Usuario usuarioObj = null; + + for (Usuario user : usuarios) { + if (user.getNome().equals(usuario)) { + usuarioObj = user; + } + } + + if (usuarioObj == null) { + new IllegalArgumentException("Usuário não encontrado: " + usuario); + } + + if (!usuarioObj.getPermissoes().contains("w")) { + try { + diretorio.temPerm(usuario, "w"); + } catch(IllegalArgumentException e) { + throw new PermissaoException("Usuário não tem permissão para criar diretório: " + diretorio); + } + } File arquivo = (File) diretorio; if (!anexar) arquivo.limparBlocos(); @@ -370,10 +429,27 @@ public int read(String caminho, String usuario, byte[] buffer, int offset) throw new IllegalArgumentException("O caminho especificado não é um arquivo: " + caminho); } - if (!diretorio.temPerm(usuario, "r")) { - throw new PermissaoException("Usuário não tem permissão para ler: " + caminho); + Usuario usuarioObj = null; + + for (Usuario user : usuarios) { + if (user.getNome().equals(usuario)) { + usuarioObj = user; + } + } + + if (usuarioObj == null) { + new IllegalArgumentException("Usuário não encontrado: " + usuario); + } + + if (!usuarioObj.getPermissoes().contains("r")) { + try { + diretorio.temPerm(usuario, "r"); + } catch (IllegalArgumentException e) { + throw new PermissaoException("Usuário não tem permissão para criar diretório: " + diretorio); + } } + File arquivo = (File) diretorio; int bufferOffset = 0; int arquivoOffset = 0; diff --git a/tests/PermissionTest.java b/tests/PermissionTest.java index 3ae8e61..f5c1d6b 100644 --- a/tests/PermissionTest.java +++ b/tests/PermissionTest.java @@ -9,7 +9,7 @@ import exception.PermissaoException; import static org.junit.jupiter.api.Assertions.*; -import org.junit.jupiter.api.Assertions.*; + import org.junit.jupiter.api.BeforeAll; import filesys.FileSystemImpl; @@ -199,7 +199,7 @@ public void testReadSuccess() throws CaminhoNaoEncontradoException, PermissaoExc @Test public void testReadPermissionFail() { // Tenta ler um arquivo sem permissão - assertThrows(PermissaoException.class, () -> fileSystem.read("/area1/area2/arquivo.txt", "maria", buffer, 0)); + assertThrows(PermissaoException.class, () -> fileSystem.read("/area1/area2/arquivo.txt", "cega", buffer, 0)); } @Test @@ -227,7 +227,15 @@ public void testWritePathFail() { assertThrows(CaminhoNaoEncontradoException.class, () -> fileSystem.write("/area1/area2/inexistente/arquivo.txt", "joao", true, buffer)); } + //=============== User =============== + @Test + public void testAddUser() { + // Tenta adicionar um usuário com permissão + assertDoesNotThrow(() -> fileSystem.addUser(new Usuario("carlos", "/", "rwx"))); + } + + From 9c96c32ec8b97d7e9b99c22ea0ce770cbf593adb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Leonardo=20de=20Souza=20Galv=C3=A3o?= <160603231+LeonardodeSouzaGalvao@users.noreply.github.com> Date: Wed, 18 Jun 2025 21:50:13 -0300 Subject: [PATCH 28/33] Fix: tests --- tests/PermissionTest.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/tests/PermissionTest.java b/tests/PermissionTest.java index f5c1d6b..8440dfc 100644 --- a/tests/PermissionTest.java +++ b/tests/PermissionTest.java @@ -57,7 +57,7 @@ public void testMkdirPermissionFail() { @Test public void testTouchSuccess() throws CaminhoJaExistenteException, PermissaoException, CaminhoNaoEncontradoException { // Tenta criar um arquivo com permissão de rwx - assertDoesNotThrow(() -> fileSystem.touch("/area1/arquivo.txt", "joao")); + assertDoesNotThrow(() -> fileSystem.touch("/area1/arquivo2.txt", "joao")); } @Test @@ -212,7 +212,7 @@ public void testReadPathFail() { @Test public void testWriteSuccess() throws CaminhoNaoEncontradoException, PermissaoException { // Tenta escrever em um arquivo com permissão - assertDoesNotThrow(() -> fileSystem.write("/area1/area2/arquivo.txt", "joao", true, buffer)); + assertDoesNotThrow(() -> fileSystem.write("/area1/arquivo.txt", "joao", true, buffer)); } @Test From a69ff8f5be4117a72cccf654700c69358b7e99c7 Mon Sep 17 00:00:00 2001 From: PiterOfc Date: Thu, 19 Jun 2025 15:50:30 -0300 Subject: [PATCH 29/33] =?UTF-8?q?Fix:=20corrigindo=20testes=20e=20implemen?= =?UTF-8?q?ta=C3=A7=C3=A3o=20do=20mv?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- filesys/FileSystemImpl.java | 48 +++++++++++++++++++++++++++---------- tests/PermissionTest.java | 32 +++++++++++++++++++++---- 2 files changed, 63 insertions(+), 17 deletions(-) diff --git a/filesys/FileSystemImpl.java b/filesys/FileSystemImpl.java index 7f17c23..2eac825 100644 --- a/filesys/FileSystemImpl.java +++ b/filesys/FileSystemImpl.java @@ -487,7 +487,7 @@ public int read(String caminho, String usuario, byte[] buffer, int offset) public void mv(String caminhoAntigo, String caminhoNovo, String usuario) throws CaminhoNaoEncontradoException, PermissaoException { if (caminhoAntigo == null || caminhoNovo == null || usuario == null) { - throw new PermissaoException("Caminho antigo, caminho novo e usuário não podem ser nulos"); + throw new IllegalArgumentException("Caminho antigo, caminho novo e usuário não podem ser nulos"); } caminhoAntigo = caminhoAntigo.replace("\\", "/"); @@ -501,37 +501,53 @@ public void mv(String caminhoAntigo, String caminhoNovo, String usuario) } if (caminhoAntigo.equals(caminhoNovo)) { - throw new PermissaoException("Caminho antigo e caminho novo não podem ser iguais"); + throw new IllegalArgumentException("Caminho antigo e caminho novo não podem ser iguais"); } Dir dirantigo = irPara(caminhoAntigo); - if (!dirantigo.temPerm(usuario, "w")) { - throw new PermissaoException("Usuário não tem permissão para mover: " + caminhoAntigo); + Usuario usuarioObj = usuarios.stream() + .filter(u -> u.getNome().equals(usuario)) + .findFirst() + .orElseThrow(() -> new IllegalArgumentException("Usuário não encontrado: " + usuario)); + + if (!usuarioObj.getPermissoes().contains("r")) { + try { + dirantigo.temPerm(usuario, "r"); + } catch(IllegalArgumentException e) { + throw new PermissaoException("Usuário não tem permissão para mover: " + caminhoAntigo); + } } try { Dir destino = irPara(caminhoNovo); - if (!destino.temPerm(usuario, "w")) { + + try { + destino.temPerm(usuario, "w"); + } catch(IllegalArgumentException e) { throw new PermissaoException("Sem permissão de escrita no destino"); } + if (destino.getFilhos().containsKey(dirantigo.getNome())) { - throw new PermissaoException("Já existe um diretório ou arquivo com esse nome no destino"); + throw new IllegalArgumentException("Já existe um diretório ou arquivo com esse nome no destino"); } dirantigo.getPai().removeFilho(dirantigo.getNome()); destino.addFilho(dirantigo); - } catch (CaminhoNaoEncontradoException e) { - int idx = caminhoNovo.lastIndexOf('/'); String novoNome = caminhoNovo.substring(idx + 1); String caminhoPaiNovo = (idx <= 0) ? "/" : caminhoNovo.substring(0, idx); Dir novoPai = irPara(caminhoPaiNovo); - if (!novoPai.temPerm(usuario, "w")) { - throw new PermissaoException("Sem permissão de escrita no novo caminho"); + if (!usuarioObj.getPermissoes().contains("w")) { + try { + novoPai.temPerm(usuario, "w"); + } catch(IllegalArgumentException ex) { + throw new PermissaoException("Sem permissão de escrita no novo caminho"); + } } + if (novoPai.getFilhos().containsKey(novoNome)) { throw new IllegalArgumentException("Já existe um objeto com esse nome no destino"); } @@ -591,10 +607,16 @@ public void cp(String caminhoOrigem, String caminhoDestino, String usuario, bool .orElseThrow(() -> new IllegalArgumentException("Usuário não encontrado: " + usuario)); if (!usuarioObj.getPermissoes().contains("rw")) { - if (!origem.temPerm(usuario, "r")) + try { + origem.temPerm(usuario, "r"); + } catch(IllegalArgumentException e) { throw new PermissaoException("Sem permissão de leitura em: " + caminhoOrigem); - if (!destino.temPerm(usuario, "w")) + } + try { + origem.temPerm(usuario, "w"); + } catch(IllegalArgumentException e) { throw new PermissaoException("Sem permissão de escrita em: " + caminhoDestino); + } } String nomeOrigem = origem.getNome(); @@ -659,7 +681,7 @@ private void copiarConteudoArquivo(File origem, File destino, String usuario) { @Override public void addUser(Usuario usuario) { - if (usuario == null || usuario.getNome() == null || usuario.getPermissoes() == null) { + if (usuario == null || usuario.getNome() == null || usuario.getNome().isEmpty() || usuario.getPermissoes() == null || usuario.getPermissoes().isEmpty()) { throw new IllegalArgumentException("Usuário, nome e permissões não podem ser nulos"); } diff --git a/tests/PermissionTest.java b/tests/PermissionTest.java index 8440dfc..494bace 100644 --- a/tests/PermissionTest.java +++ b/tests/PermissionTest.java @@ -32,8 +32,10 @@ public static void setUp() throws CaminhoJaExistenteException, PermissaoExceptio fileSystem.mkdir("/area1", "joao"); fileSystem.mkdir("/area1/area2", "tiago"); + fileSystem.mkdir("/area1/area2/area_meh", "root"); fileSystem.touch("/area1/area2/arquivo.txt", "root"); + fileSystem.touch("/area1/area2/arquivo_meh.txt", "joao"); } @@ -167,19 +169,19 @@ public void testRmPathFail() { @Test public void testMvInSamePlaceRenamingSuccess() throws CaminhoNaoEncontradoException, PermissaoException { // Tenta mover um arquivo com permissão - assertDoesNotThrow(() -> fileSystem.mv("/area1/area2/arquivo.txt", "/area1/area2/arquivo_moved.txt", "joao")); + assertDoesNotThrow(() -> fileSystem.mv("/area1/area2/arquivo_meh.txt", "/area1/area2/arquivo_moved.txt", "root")); } @Test public void testMvInSamePlaceFail() { // Tenta mover um arquivo para o mesmo lugar sem permissão - assertThrows(PermissaoException.class, () -> fileSystem.mv("/area1/area2/arquivo.txt", "/area1/area2/arquivo.txt", "root")); + assertThrows(IllegalArgumentException.class, () -> fileSystem.mv("/area1/area2/arquivo_moved.txt", "/area1/area2/arquivo_moved.txt", "root")); } @Test public void testMvPermissionFail() { // Tenta mover um arquivo sem permissão - assertThrows(PermissaoException.class, () -> fileSystem.mv("/area1/area2/arquivo.txt", "/area1/area2/arquivo_moved.txt", "maria")); + assertThrows(PermissaoException.class, () -> fileSystem.mv("/area1/area2/area_meh", "/area1/area3", "maria")); } @Test @@ -235,7 +237,29 @@ public void testAddUser() { assertDoesNotThrow(() -> fileSystem.addUser(new Usuario("carlos", "/", "rwx"))); } - + @Test + public void testAddUserWithExistingName() { + // Tenta adicionar um usuário com nome já existente + assertThrows(IllegalArgumentException.class, () -> fileSystem.addUser(new Usuario("maria", "/", "rwx"))); + } + + @Test + public void testAddUserWithInvalidPermission() { + // Tenta adicionar um usuário com permissões inválidas + assertThrows(IllegalArgumentException.class, () -> fileSystem.addUser(new Usuario("carlos", "/", "rw"))); + } + + @Test + public void testAddUserWithEmptyName() { + // Tenta adicionar um usuário com nome vazio + assertThrows(IllegalArgumentException.class, () -> fileSystem.addUser(new Usuario("", "/", "rwx"))); + } + + @Test + public void testAddUserWithoutDirectory() { + // Tenta adicionar um usuário sem diretório + assertThrows(IllegalArgumentException.class, () -> fileSystem.addUser(new Usuario("carlos", null, "rwx"))); + } From 18e16da6f75f6b3115868fdd20ad08a13ac7df95 Mon Sep 17 00:00:00 2001 From: PiterOfc Date: Thu, 19 Jun 2025 15:51:10 -0300 Subject: [PATCH 30/33] Formatando FileSystemImpl --- filesys/FileSystemImpl.java | 339 ++++++++++++++++++------------------ 1 file changed, 170 insertions(+), 169 deletions(-) diff --git a/filesys/FileSystemImpl.java b/filesys/FileSystemImpl.java index 2eac825..0eaae8a 100644 --- a/filesys/FileSystemImpl.java +++ b/filesys/FileSystemImpl.java @@ -165,7 +165,7 @@ public void mkdir(String caminho, String usuario) throws CaminhoJaExistenteExcep if (!usuarioObj.getPermissoes().contains("w")) { try { diretorioAtual.temPerm(usuario, "w"); - } catch(IllegalArgumentException e) { + } catch (IllegalArgumentException e) { throw new PermissaoException("Usuário não tem permissão para criar diretório: " + diretorioAtual); } } @@ -218,7 +218,7 @@ public void chmod(String caminho, String usuario, String usuarioAlvo, String per if (!usuarioObj.getPermissoes().contains("w")) { try { dir.temPerm(usuario, "w"); - } catch(IllegalArgumentException e) { + } catch (IllegalArgumentException e) { throw new PermissaoException("Usuário não tem permissão para criar diretório: " + dir); } } @@ -228,82 +228,82 @@ public void chmod(String caminho, String usuario, String usuarioAlvo, String per } @Override -public void rm(String caminho, String usuario, boolean recursivo) - throws CaminhoNaoEncontradoException, PermissaoException { + public void rm(String caminho, String usuario, boolean recursivo) + throws CaminhoNaoEncontradoException, PermissaoException { - if (caminho == null || usuario == null) { - throw new IllegalArgumentException("Caminho e usuário não podem ser nulos"); - } + if (caminho == null || usuario == null) { + throw new IllegalArgumentException("Caminho e usuário não podem ser nulos"); + } - caminho = caminho.replace("\\", "/"); - if (caminho.endsWith("/")) - caminho = caminho.substring(0, caminho.length() - 1); + caminho = caminho.replace("\\", "/"); + if (caminho.endsWith("/")) + caminho = caminho.substring(0, caminho.length() - 1); - Dir dir; + Dir dir; - try { - dir = irPara(caminho); - } catch (CaminhoNaoEncontradoException e) { - // Tentativa de recuperar o arquivo pelo pai - int ultimoBarra = caminho.lastIndexOf('/'); - if (ultimoBarra == -1) throw e; + try { + dir = irPara(caminho); + } catch (CaminhoNaoEncontradoException e) { + // Tentativa de recuperar o arquivo pelo pai + int ultimoBarra = caminho.lastIndexOf('/'); + if (ultimoBarra == -1) + throw e; - String caminhoPai = caminho.substring(0, ultimoBarra); - String nomeArquivo = caminho.substring(ultimoBarra + 1); + String caminhoPai = caminho.substring(0, ultimoBarra); + String nomeArquivo = caminho.substring(ultimoBarra + 1); - Dir pai = irPara(caminhoPai); - Dir possivelArquivo = pai.getFilhos().get(nomeArquivo); + Dir pai = irPara(caminhoPai); + Dir possivelArquivo = pai.getFilhos().get(nomeArquivo); - if (possivelArquivo != null && possivelArquivo.isArquivo()) { - dir = possivelArquivo; - } else { - throw new CaminhoNaoEncontradoException("Arquivo ou diretório não encontrado: " + caminho); + if (possivelArquivo != null && possivelArquivo.isArquivo()) { + dir = possivelArquivo; + } else { + throw new CaminhoNaoEncontradoException("Arquivo ou diretório não encontrado: " + caminho); + } } - } - // Busca o objeto usuário - Usuario usuarioObj = null; - for (Usuario user : usuarios) { - if (user.getNome().equals(usuario)) { - usuarioObj = user; - break; + // Busca o objeto usuário + Usuario usuarioObj = null; + for (Usuario user : usuarios) { + if (user.getNome().equals(usuario)) { + usuarioObj = user; + break; + } } - } - if (usuarioObj == null) { - throw new IllegalArgumentException("Usuário não encontrado: " + usuario); - } + if (usuarioObj == null) { + throw new IllegalArgumentException("Usuário não encontrado: " + usuario); + } - // Verifica permissão de escrita - if (!usuarioObj.getPermissoes().contains("w")) { - try { - dir.temPerm(usuario, "w"); - } catch (IllegalArgumentException e) { - throw new PermissaoException("Usuário não tem permissão para remover: " + dir.getNome()); + // Verifica permissão de escrita + if (!usuarioObj.getPermissoes().contains("w")) { + try { + dir.temPerm(usuario, "w"); + } catch (IllegalArgumentException e) { + throw new PermissaoException("Usuário não tem permissão para remover: " + dir.getNome()); + } } - } - // Verifica se pode remover diretório com conteúdo - if (!dir.isArquivo() && dir.temSubdiretorios() && !recursivo) { - throw new PermissaoException( - "Esse diretório contém subdiretórios. Use o parâmetro recursivo para removê-lo."); - } + // Verifica se pode remover diretório com conteúdo + if (!dir.isArquivo() && dir.temSubdiretorios() && !recursivo) { + throw new PermissaoException( + "Esse diretório contém subdiretórios. Use o parâmetro recursivo para removê-lo."); + } - // Remoção - if (dir.isArquivo()) { - dir.getPai().removeFilho(dir.getNome()); - System.out.println("Arquivo removido: " + caminho); - } else { - if (recursivo) { - for (Dir filho : new ArrayList<>(dir.getFilhos().values())) { - rm(filho.getCaminhoCompleto(), usuario, true); + // Remoção + if (dir.isArquivo()) { + dir.getPai().removeFilho(dir.getNome()); + System.out.println("Arquivo removido: " + caminho); + } else { + if (recursivo) { + for (Dir filho : new ArrayList<>(dir.getFilhos().values())) { + rm(filho.getCaminhoCompleto(), usuario, true); + } } + dir.getPai().removeFilho(dir.getNome()); + System.out.println("Diretório removido: " + caminho); } - dir.getPai().removeFilho(dir.getNome()); - System.out.println("Diretório removido: " + caminho); } -} - @Override public void touch(String caminho, String usuario) @@ -328,23 +328,23 @@ public void touch(String caminho, String usuario) Usuario usuarioObj = null; - for (Usuario user : usuarios) { - if (user.getNome().equals(usuario)) { - usuarioObj = user; - } + for (Usuario user : usuarios) { + if (user.getNome().equals(usuario)) { + usuarioObj = user; } + } - if (usuarioObj == null) { - new IllegalArgumentException("Usuário não encontrado: " + usuario); - } + if (usuarioObj == null) { + new IllegalArgumentException("Usuário não encontrado: " + usuario); + } - if (!usuarioObj.getPermissoes().contains("w")) { - try { - dirPai.temPerm(usuario, "w"); - } catch(IllegalArgumentException e) { - throw new PermissaoException("Usuário não tem permissão para criar diretório: " + dirPai); - } + if (!usuarioObj.getPermissoes().contains("w")) { + try { + dirPai.temPerm(usuario, "w"); + } catch (IllegalArgumentException e) { + throw new PermissaoException("Usuário não tem permissão para criar diretório: " + dirPai); } + } File novoArquivo = new File(nomeArquivo, usuario, "rwx"); dirPai.addFilho(novoArquivo); @@ -371,26 +371,27 @@ public void write(String caminho, String usuario, boolean anexar, byte[] buffer) Usuario usuarioObj = null; - for (Usuario user : usuarios) { - if (user.getNome().equals(usuario)) { - usuarioObj = user; - } + for (Usuario user : usuarios) { + if (user.getNome().equals(usuario)) { + usuarioObj = user; } + } - if (usuarioObj == null) { - new IllegalArgumentException("Usuário não encontrado: " + usuario); - } + if (usuarioObj == null) { + new IllegalArgumentException("Usuário não encontrado: " + usuario); + } - if (!usuarioObj.getPermissoes().contains("w")) { - try { - diretorio.temPerm(usuario, "w"); - } catch(IllegalArgumentException e) { - throw new PermissaoException("Usuário não tem permissão para criar diretório: " + diretorio); - } + if (!usuarioObj.getPermissoes().contains("w")) { + try { + diretorio.temPerm(usuario, "w"); + } catch (IllegalArgumentException e) { + throw new PermissaoException("Usuário não tem permissão para criar diretório: " + diretorio); } + } File arquivo = (File) diretorio; - if (!anexar) arquivo.limparBlocos(); + if (!anexar) + arquivo.limparBlocos(); int offset = 0; @@ -449,7 +450,6 @@ public int read(String caminho, String usuario, byte[] buffer, int offset) } } - File arquivo = (File) diretorio; int bufferOffset = 0; int arquivoOffset = 0; @@ -507,14 +507,14 @@ public void mv(String caminhoAntigo, String caminhoNovo, String usuario) Dir dirantigo = irPara(caminhoAntigo); Usuario usuarioObj = usuarios.stream() - .filter(u -> u.getNome().equals(usuario)) - .findFirst() - .orElseThrow(() -> new IllegalArgumentException("Usuário não encontrado: " + usuario)); + .filter(u -> u.getNome().equals(usuario)) + .findFirst() + .orElseThrow(() -> new IllegalArgumentException("Usuário não encontrado: " + usuario)); if (!usuarioObj.getPermissoes().contains("r")) { try { dirantigo.temPerm(usuario, "r"); - } catch(IllegalArgumentException e) { + } catch (IllegalArgumentException e) { throw new PermissaoException("Usuário não tem permissão para mover: " + caminhoAntigo); } } @@ -524,7 +524,7 @@ public void mv(String caminhoAntigo, String caminhoNovo, String usuario) try { destino.temPerm(usuario, "w"); - } catch(IllegalArgumentException e) { + } catch (IllegalArgumentException e) { throw new PermissaoException("Sem permissão de escrita no destino"); } @@ -543,7 +543,7 @@ public void mv(String caminhoAntigo, String caminhoNovo, String usuario) if (!usuarioObj.getPermissoes().contains("w")) { try { novoPai.temPerm(usuario, "w"); - } catch(IllegalArgumentException ex) { + } catch (IllegalArgumentException ex) { throw new PermissaoException("Sem permissão de escrita no novo caminho"); } } @@ -579,7 +579,7 @@ public void ls(String caminho, String usuario, boolean recursivo) if (!usuarioObj.getPermissoes().contains("r")) { try { diretorio.temPerm(usuario, "r"); - } catch(IllegalArgumentException e) { + } catch (IllegalArgumentException e) { throw new PermissaoException("Você não tem permissão para listar este diretório!"); } } @@ -589,99 +589,100 @@ public void ls(String caminho, String usuario, boolean recursivo) } @Override -public void cp(String caminhoOrigem, String caminhoDestino, String usuario, boolean recursivo) - throws CaminhoNaoEncontradoException, PermissaoException { - if (caminhoOrigem == null || caminhoDestino == null || usuario == null) { - throw new IllegalArgumentException("Caminho de origem, destino e usuário não podem ser nulos"); - } + public void cp(String caminhoOrigem, String caminhoDestino, String usuario, boolean recursivo) + throws CaminhoNaoEncontradoException, PermissaoException { + if (caminhoOrigem == null || caminhoDestino == null || usuario == null) { + throw new IllegalArgumentException("Caminho de origem, destino e usuário não podem ser nulos"); + } - caminhoOrigem = caminhoOrigem.replace("\\", "/").replaceAll("/$", ""); - caminhoDestino = caminhoDestino.replace("\\", "/").replaceAll("/$", ""); + caminhoOrigem = caminhoOrigem.replace("\\", "/").replaceAll("/$", ""); + caminhoDestino = caminhoDestino.replace("\\", "/").replaceAll("/$", ""); - Dir origem = irPara(caminhoOrigem); - Dir destino = irPara(caminhoDestino); + Dir origem = irPara(caminhoOrigem); + Dir destino = irPara(caminhoDestino); - Usuario usuarioObj = usuarios.stream() - .filter(u -> u.getNome().equals(usuario)) - .findFirst() - .orElseThrow(() -> new IllegalArgumentException("Usuário não encontrado: " + usuario)); + Usuario usuarioObj = usuarios.stream() + .filter(u -> u.getNome().equals(usuario)) + .findFirst() + .orElseThrow(() -> new IllegalArgumentException("Usuário não encontrado: " + usuario)); - if (!usuarioObj.getPermissoes().contains("rw")) { - try { - origem.temPerm(usuario, "r"); - } catch(IllegalArgumentException e) { - throw new PermissaoException("Sem permissão de leitura em: " + caminhoOrigem); - } - try { - origem.temPerm(usuario, "w"); - } catch(IllegalArgumentException e) { - throw new PermissaoException("Sem permissão de escrita em: " + caminhoDestino); + if (!usuarioObj.getPermissoes().contains("rw")) { + try { + origem.temPerm(usuario, "r"); + } catch (IllegalArgumentException e) { + throw new PermissaoException("Sem permissão de leitura em: " + caminhoOrigem); + } + try { + origem.temPerm(usuario, "w"); + } catch (IllegalArgumentException e) { + throw new PermissaoException("Sem permissão de escrita em: " + caminhoDestino); + } } - } - String nomeOrigem = origem.getNome(); + String nomeOrigem = origem.getNome(); - // Se destino for um arquivo, substituí-lo se possível - if (destino instanceof File) { - if (!origem.isArquivo()) { - throw new IllegalArgumentException("Não é possível copiar um diretório para um arquivo"); + // Se destino for um arquivo, substituí-lo se possível + if (destino instanceof File) { + if (!origem.isArquivo()) { + throw new IllegalArgumentException("Não é possível copiar um diretório para um arquivo"); + } + copiarConteudoArquivo((File) origem, (File) destino, usuario); + System.out.println("Arquivo sobrescrito: " + destino.getCaminhoCompleto()); + return; } - copiarConteudoArquivo((File) origem, (File) destino, usuario); - System.out.println("Arquivo sobrescrito: " + destino.getCaminhoCompleto()); - return; - } - // Se for diretório, verificar se já existe um filho com o mesmo nome - Dir existente = destino.getFilhos().get(nomeOrigem); + // Se for diretório, verificar se já existe um filho com o mesmo nome + Dir existente = destino.getFilhos().get(nomeOrigem); - if (existente != null) { - // Se for arquivo, sobrescreve - if (existente.isArquivo() && origem.isArquivo()) { - copiarConteudoArquivo((File) origem, (File) existente, usuario); - System.out.println("Arquivo sobrescrito: " + existente.getCaminhoCompleto()); - return; - } else { - throw new PermissaoException("Já existe um diretório/arquivo com esse nome: " + existente.getCaminhoCompleto()); + if (existente != null) { + // Se for arquivo, sobrescreve + if (existente.isArquivo() && origem.isArquivo()) { + copiarConteudoArquivo((File) origem, (File) existente, usuario); + System.out.println("Arquivo sobrescrito: " + existente.getCaminhoCompleto()); + return; + } else { + throw new PermissaoException( + "Já existe um diretório/arquivo com esse nome: " + existente.getCaminhoCompleto()); + } } - } - if (origem.isArquivo()) { - File arquivoOrigem = (File) origem; - File arquivoNovo = new File(arquivoOrigem.getNome(), usuario, "rwx"); - for (BlocoDeDados bloco : arquivoOrigem.getBlocos()) { - // Copia física dos blocos - byte[] dadosCopiados = bloco.getDados().clone(); // copia conteúdo - arquivoNovo.addBloco(new BlocoDeDados(dadosCopiados)); - } - destino.addFilho(arquivoNovo); - System.out.println("Arquivo copiado: " + arquivoNovo.getCaminhoCompleto()); - } else { - if (!recursivo) { - throw new IllegalArgumentException("Cópia de diretório requer o modo recursivo"); - } + if (origem.isArquivo()) { + File arquivoOrigem = (File) origem; + File arquivoNovo = new File(arquivoOrigem.getNome(), usuario, "rwx"); + for (BlocoDeDados bloco : arquivoOrigem.getBlocos()) { + // Copia física dos blocos + byte[] dadosCopiados = bloco.getDados().clone(); // copia conteúdo + arquivoNovo.addBloco(new BlocoDeDados(dadosCopiados)); + } + destino.addFilho(arquivoNovo); + System.out.println("Arquivo copiado: " + arquivoNovo.getCaminhoCompleto()); + } else { + if (!recursivo) { + throw new IllegalArgumentException("Cópia de diretório requer o modo recursivo"); + } - Dir novoDir = new Dir(origem.getNome(), usuario, "rwx"); - destino.addFilho(novoDir); - for (Dir filho : origem.getFilhos().values()) { - cp(filho.getCaminhoCompleto(), novoDir.getCaminhoCompleto(), usuario, true); + Dir novoDir = new Dir(origem.getNome(), usuario, "rwx"); + destino.addFilho(novoDir); + for (Dir filho : origem.getFilhos().values()) { + cp(filho.getCaminhoCompleto(), novoDir.getCaminhoCompleto(), usuario, true); + } + System.out.println("Diretório copiado: " + novoDir.getCaminhoCompleto()); } - System.out.println("Diretório copiado: " + novoDir.getCaminhoCompleto()); } -} - -// Método auxiliar -private void copiarConteudoArquivo(File origem, File destino, String usuario) { - destino.limparBlocos(); - for (BlocoDeDados bloco : origem.getBlocos()) { - byte[] dadosCopiados = bloco.getDados().clone(); - destino.addBloco(new BlocoDeDados(dadosCopiados)); - } -} + // Método auxiliar + private void copiarConteudoArquivo(File origem, File destino, String usuario) { + destino.limparBlocos(); + for (BlocoDeDados bloco : origem.getBlocos()) { + byte[] dadosCopiados = bloco.getDados().clone(); + destino.addBloco(new BlocoDeDados(dadosCopiados)); + } + } @Override public void addUser(Usuario usuario) { - if (usuario == null || usuario.getNome() == null || usuario.getNome().isEmpty() || usuario.getPermissoes() == null || usuario.getPermissoes().isEmpty()) { + if (usuario == null || usuario.getNome() == null || usuario.getNome().isEmpty() + || usuario.getPermissoes() == null || usuario.getPermissoes().isEmpty()) { throw new IllegalArgumentException("Usuário, nome e permissões não podem ser nulos"); } From 1150af13c7b36ddf22058d97183c37e3de2ca6a4 Mon Sep 17 00:00:00 2001 From: PiterOfc Date: Thu, 19 Jun 2025 16:00:59 -0300 Subject: [PATCH 31/33] Finalizando testes --- ...ssionTest.java => FileSystemImplTest.java} | 27 ++++++++++++++++--- 1 file changed, 24 insertions(+), 3 deletions(-) rename tests/{PermissionTest.java => FileSystemImplTest.java} (95%) diff --git a/tests/PermissionTest.java b/tests/FileSystemImplTest.java similarity index 95% rename from tests/PermissionTest.java rename to tests/FileSystemImplTest.java index 494bace..3ae6c85 100644 --- a/tests/PermissionTest.java +++ b/tests/FileSystemImplTest.java @@ -17,7 +17,7 @@ import filesys.Usuario; // Essa classe testa cenários de permissão -public class PermissionTest { +public class FileSystemImplTest { private static IFileSystem fileSystem; byte[] buffer = new byte[1024]; @@ -74,6 +74,12 @@ public void testTouchPathFail() { assertThrows(CaminhoNaoEncontradoException.class, () -> fileSystem.touch("/area1/area2/inexistente/arquivo3.txt", "root")); } + @Test + public void testTouchAlreadyExists() { + // Tenta criar um arquivo que já existe + assertThrows(CaminhoJaExistenteException.class, () -> fileSystem.touch("/area1/area2/arquivo.txt", "joao")); + } + // =============== CHMOD =============== @@ -95,7 +101,15 @@ public void testChmodPathFail() { assertThrows(CaminhoNaoEncontradoException.class, () -> fileSystem.chmod("/area1/area2/inexistente", "root", "tiago", "rwx")); } + @Test + public void testChmodInvalidPermission() { + // Tenta alterar as permissões de um diretório com permissões inválidas + assertThrows(IllegalArgumentException.class, () -> fileSystem.chmod("/area1/area2", "root", "tiago", "rw")); + } + + // =============== LS =============== + @Test public void testLsSuccess() throws CaminhoNaoEncontradoException, PermissaoException { // Tenta listar o conteúdo de um diretório com permissão @@ -120,7 +134,9 @@ public void testLsPathFail() { assertThrows(CaminhoNaoEncontradoException.class, () -> fileSystem.ls("/area1/area2/inexistente", "joao", true)); } + // =============== CP =============== + @Test public void testCpSuccess() throws CaminhoNaoEncontradoException, PermissaoException { // Tenta copiar um arquivo com permissão @@ -145,7 +161,9 @@ public void testSobrescreverArquivoSucesso() throws CaminhoNaoEncontradoExceptio assertDoesNotThrow(() -> fileSystem.cp("/area1/area2/arquivo.txt", "/area1/area2/arquivo.txt", "joao", true)); } + // =============== RM =============== + @Test public void testRmSuccess() throws CaminhoNaoEncontradoException, PermissaoException { // Tenta remover um arquivo com permissão @@ -164,6 +182,7 @@ public void testRmPathFail() { assertThrows(CaminhoNaoEncontradoException.class, () -> fileSystem.rm("/area1/area2/inexistente/arquivo.txt", "joao", true)); } + // =============== MV =============== @Test @@ -190,6 +209,7 @@ public void testMvPathFail() { assertThrows(CaminhoNaoEncontradoException.class, () -> fileSystem.mv("/area1/area2/inexistente/arquivo.txt", "/area1/area2/arquivo_moved.txt", "root")); } + // =============== READ =============== @Test @@ -210,7 +230,9 @@ public void testReadPathFail() { assertThrows(CaminhoNaoEncontradoException.class, () -> fileSystem.read("/area1/area2/inexistente/arquivo.txt", "joao", buffer, 0)); } + // =============== WRITE =============== + @Test public void testWriteSuccess() throws CaminhoNaoEncontradoException, PermissaoException { // Tenta escrever em um arquivo com permissão @@ -229,6 +251,7 @@ public void testWritePathFail() { assertThrows(CaminhoNaoEncontradoException.class, () -> fileSystem.write("/area1/area2/inexistente/arquivo.txt", "joao", true, buffer)); } + //=============== User =============== @Test @@ -261,6 +284,4 @@ public void testAddUserWithoutDirectory() { assertThrows(IllegalArgumentException.class, () -> fileSystem.addUser(new Usuario("carlos", null, "rwx"))); } - - } \ No newline at end of file From 617cd884762d73a4fc9e62985732b818afb38289 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Leonardo=20de=20Souza=20Galv=C3=A3o?= <160603231+LeonardodeSouzaGalvao@users.noreply.github.com> Date: Thu, 19 Jun 2025 16:46:57 -0300 Subject: [PATCH 32/33] Fix: Error messeges fixed --- Main.java | 2 +- filesys/FileSystemImpl.java | 27 ++++++++++++++------------- 2 files changed, 15 insertions(+), 14 deletions(-) diff --git a/Main.java b/Main.java index 0aef575..fe6aaea 100644 --- a/Main.java +++ b/Main.java @@ -171,7 +171,7 @@ public static void menu() { default: System.out.println("Comando inválido!"); } - } catch (CaminhoNaoEncontradoException | CaminhoJaExistenteException | PermissaoException e) { + } catch (CaminhoNaoEncontradoException | CaminhoJaExistenteException | PermissaoException | IllegalArgumentException e) { System.out.println("Erro: " + e.getMessage()); } diff --git a/filesys/FileSystemImpl.java b/filesys/FileSystemImpl.java index 0eaae8a..a22c5fa 100644 --- a/filesys/FileSystemImpl.java +++ b/filesys/FileSystemImpl.java @@ -91,7 +91,7 @@ private String lsRecursivo(Dir diretorio, String caminho, boolean recursivo, Str @Override public void mkdir(String caminho, String usuario) throws CaminhoJaExistenteException, PermissaoException { - if (caminho == null || usuario == null) { + if (caminho == null || caminho.isEmpty() || usuario == null || usuario.isEmpty()) { throw new IllegalArgumentException("Caminho e usuário não podem ser nulos"); } @@ -166,7 +166,7 @@ public void mkdir(String caminho, String usuario) throws CaminhoJaExistenteExcep try { diretorioAtual.temPerm(usuario, "w"); } catch (IllegalArgumentException e) { - throw new PermissaoException("Usuário não tem permissão para criar diretório: " + diretorioAtual); + throw new PermissaoException("Usuário não tem permissão para criar diretório: " + caminhoAtual); } } @@ -182,7 +182,7 @@ public void mkdir(String caminho, String usuario) throws CaminhoJaExistenteExcep @Override public void chmod(String caminho, String usuario, String usuarioAlvo, String permissao) throws CaminhoNaoEncontradoException, PermissaoException { - if (caminho == null || usuario == null || usuarioAlvo == null || permissao == null) { + if (caminho == null || caminho.isEmpty() || usuario == null || usuario.isEmpty() || usuarioAlvo == null || usuarioAlvo.isEmpty() || permissao == null || permissao.isEmpty()) { throw new IllegalArgumentException("Caminho, usuário, usuário alvo e permissão não podem ser nulos"); } @@ -219,7 +219,7 @@ public void chmod(String caminho, String usuario, String usuarioAlvo, String per try { dir.temPerm(usuario, "w"); } catch (IllegalArgumentException e) { - throw new PermissaoException("Usuário não tem permissão para criar diretório: " + dir); + throw new PermissaoException("Usuário não tem permissão para criar diretório: " + caminho); } } @@ -231,9 +231,10 @@ public void chmod(String caminho, String usuario, String usuarioAlvo, String per public void rm(String caminho, String usuario, boolean recursivo) throws CaminhoNaoEncontradoException, PermissaoException { - if (caminho == null || usuario == null) { + if (caminho == null || caminho.isEmpty() || usuario == null || usuario.isEmpty()) { throw new IllegalArgumentException("Caminho e usuário não podem ser nulos"); } + caminho = caminho.replace("\\", "/"); if (caminho.endsWith("/")) @@ -308,7 +309,7 @@ public void rm(String caminho, String usuario, boolean recursivo) @Override public void touch(String caminho, String usuario) throws CaminhoJaExistenteException, PermissaoException, CaminhoNaoEncontradoException { - if (caminho == null || usuario == null) { + if (caminho == null || caminho.isEmpty() || usuario == null || usuario.isEmpty()) { throw new IllegalArgumentException("Caminho e usuário não podem ser nulos"); } @@ -342,7 +343,7 @@ public void touch(String caminho, String usuario) try { dirPai.temPerm(usuario, "w"); } catch (IllegalArgumentException e) { - throw new PermissaoException("Usuário não tem permissão para criar diretório: " + dirPai); + throw new PermissaoException("Usuário não tem permissão para criar arquivo: " + caminho); } } @@ -354,7 +355,7 @@ public void touch(String caminho, String usuario) @Override public void write(String caminho, String usuario, boolean anexar, byte[] buffer) throws CaminhoNaoEncontradoException, PermissaoException { - if (caminho == null || usuario == null || buffer == null) { + if (caminho == null || usuario == null || buffer == null || caminho.isEmpty() || usuario.isEmpty() || buffer.length == 0) { throw new IllegalArgumentException("Caminho, usuário e buffer não podem ser nulos"); } @@ -385,7 +386,7 @@ public void write(String caminho, String usuario, boolean anexar, byte[] buffer) try { diretorio.temPerm(usuario, "w"); } catch (IllegalArgumentException e) { - throw new PermissaoException("Usuário não tem permissão para criar diretório: " + diretorio); + throw new PermissaoException("Usuário não tem permissão para criar diretório: " + caminho); } } @@ -415,7 +416,7 @@ public void write(String caminho, String usuario, boolean anexar, byte[] buffer) @Override public int read(String caminho, String usuario, byte[] buffer, int offset) throws CaminhoNaoEncontradoException, PermissaoException { - if (caminho == null || usuario == null || buffer == null) { + if (caminho == null || usuario == null || buffer == null || caminho.isEmpty() || usuario.isEmpty() || buffer.length == 0) { throw new IllegalArgumentException("Caminho, usuário e buffer não podem ser nulos"); } @@ -446,7 +447,7 @@ public int read(String caminho, String usuario, byte[] buffer, int offset) try { diretorio.temPerm(usuario, "r"); } catch (IllegalArgumentException e) { - throw new PermissaoException("Usuário não tem permissão para criar diretório: " + diretorio); + throw new PermissaoException("Usuário não tem permissão para criar diretório: " + caminho); } } @@ -486,7 +487,7 @@ public int read(String caminho, String usuario, byte[] buffer, int offset) @Override public void mv(String caminhoAntigo, String caminhoNovo, String usuario) throws CaminhoNaoEncontradoException, PermissaoException { - if (caminhoAntigo == null || caminhoNovo == null || usuario == null) { + if (caminhoAntigo == null || caminhoNovo == null || usuario == null || caminhoAntigo.isEmpty() || caminhoNovo.isEmpty() || usuario.isEmpty()) { throw new IllegalArgumentException("Caminho antigo, caminho novo e usuário não podem ser nulos"); } @@ -591,7 +592,7 @@ public void ls(String caminho, String usuario, boolean recursivo) @Override public void cp(String caminhoOrigem, String caminhoDestino, String usuario, boolean recursivo) throws CaminhoNaoEncontradoException, PermissaoException { - if (caminhoOrigem == null || caminhoDestino == null || usuario == null) { + if (caminhoOrigem == null || caminhoDestino == null || usuario == null || caminhoOrigem.isEmpty() || caminhoDestino.isEmpty() || usuario.isEmpty()) { throw new IllegalArgumentException("Caminho de origem, destino e usuário não podem ser nulos"); } From a24be5a126ac64d43e840da70dcc510f608d8a09 Mon Sep 17 00:00:00 2001 From: PiterOfc Date: Fri, 20 Jun 2025 22:48:43 -0300 Subject: [PATCH 33/33] =?UTF-8?q?Fix:=20requerindo=20permiss=C3=A3o=20gera?= =?UTF-8?q?l=20e=20espec=C3=ADfica=20para=20as=20a=C3=A7=C3=B5es?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- filesys/FileSystemImpl.java | 50 ++++++++++++++++++++++++++--------- tests/FileSystemImplTest.java | 6 ++--- 2 files changed, 41 insertions(+), 15 deletions(-) diff --git a/filesys/FileSystemImpl.java b/filesys/FileSystemImpl.java index a22c5fa..6e67d46 100644 --- a/filesys/FileSystemImpl.java +++ b/filesys/FileSystemImpl.java @@ -215,12 +215,14 @@ public void chmod(String caminho, String usuario, String usuarioAlvo, String per new IllegalArgumentException("Usuário não encontrado: " + usuario); } - if (!usuarioObj.getPermissoes().contains("w")) { + if (usuarioObj.getPermissoes().contains("w")) { try { dir.temPerm(usuario, "w"); } catch (IllegalArgumentException e) { throw new PermissaoException("Usuário não tem permissão para criar diretório: " + caminho); } + } else { + throw new PermissaoException("Usuário não tem permissão para criar diretório: " + caminho); } dir.setPermissoesUsuario(usuarioAlvo, permissao); @@ -277,12 +279,14 @@ public void rm(String caminho, String usuario, boolean recursivo) } // Verifica permissão de escrita - if (!usuarioObj.getPermissoes().contains("w")) { + if (usuarioObj.getPermissoes().contains("w")) { try { dir.temPerm(usuario, "w"); } catch (IllegalArgumentException e) { throw new PermissaoException("Usuário não tem permissão para remover: " + dir.getNome()); } + } else { + throw new PermissaoException("Usuário não tem permissão para remover: " + dir.getNome()); } // Verifica se pode remover diretório com conteúdo @@ -339,12 +343,14 @@ public void touch(String caminho, String usuario) new IllegalArgumentException("Usuário não encontrado: " + usuario); } - if (!usuarioObj.getPermissoes().contains("w")) { + if (usuarioObj.getPermissoes().contains("w")) { try { dirPai.temPerm(usuario, "w"); } catch (IllegalArgumentException e) { throw new PermissaoException("Usuário não tem permissão para criar arquivo: " + caminho); } + } else { + throw new PermissaoException("Usuário não tem permissão para criar arquivo: " + caminho); } File novoArquivo = new File(nomeArquivo, usuario, "rwx"); @@ -366,6 +372,10 @@ public void write(String caminho, String usuario, boolean anexar, byte[] buffer) Dir diretorio = irPara(caminho); + if (diretorio == null) { + throw new CaminhoNaoEncontradoException("Caminho não encontrado: " + caminho); + } + if (!diretorio.isArquivo()) { throw new IllegalArgumentException("O caminho especificado não é um arquivo: " + caminho); } @@ -382,12 +392,14 @@ public void write(String caminho, String usuario, boolean anexar, byte[] buffer) new IllegalArgumentException("Usuário não encontrado: " + usuario); } - if (!usuarioObj.getPermissoes().contains("w")) { + if (usuarioObj.getPermissoes().contains("w")) { try { diretorio.temPerm(usuario, "w"); } catch (IllegalArgumentException e) { throw new PermissaoException("Usuário não tem permissão para criar diretório: " + caminho); } + } else { + throw new PermissaoException("Usuário não tem permissão para criar diretório: " + caminho); } File arquivo = (File) diretorio; @@ -443,12 +455,14 @@ public int read(String caminho, String usuario, byte[] buffer, int offset) new IllegalArgumentException("Usuário não encontrado: " + usuario); } - if (!usuarioObj.getPermissoes().contains("r")) { + if (usuarioObj.getPermissoes().contains("r")) { try { diretorio.temPerm(usuario, "r"); } catch (IllegalArgumentException e) { throw new PermissaoException("Usuário não tem permissão para criar diretório: " + caminho); } + } else { + throw new PermissaoException("Usuário não tem permissão para criar diretório: " + caminho); } File arquivo = (File) diretorio; @@ -512,20 +526,26 @@ public void mv(String caminhoAntigo, String caminhoNovo, String usuario) .findFirst() .orElseThrow(() -> new IllegalArgumentException("Usuário não encontrado: " + usuario)); - if (!usuarioObj.getPermissoes().contains("r")) { + if (usuarioObj.getPermissoes().contains("r")) { try { dirantigo.temPerm(usuario, "r"); } catch (IllegalArgumentException e) { throw new PermissaoException("Usuário não tem permissão para mover: " + caminhoAntigo); } + } else { + throw new PermissaoException("Usuário não tem permissão para mover: " + caminhoAntigo); } try { Dir destino = irPara(caminhoNovo); - try { - destino.temPerm(usuario, "w"); - } catch (IllegalArgumentException e) { + if (usuarioObj.getPermissoes().contains("w")) { + try { + destino.temPerm(usuario, "w"); + } catch (IllegalArgumentException e) { + throw new PermissaoException("Sem permissão de escrita no destino"); + } + } else { throw new PermissaoException("Sem permissão de escrita no destino"); } @@ -541,12 +561,14 @@ public void mv(String caminhoAntigo, String caminhoNovo, String usuario) String caminhoPaiNovo = (idx <= 0) ? "/" : caminhoNovo.substring(0, idx); Dir novoPai = irPara(caminhoPaiNovo); - if (!usuarioObj.getPermissoes().contains("w")) { + if (usuarioObj.getPermissoes().contains("w")) { try { novoPai.temPerm(usuario, "w"); } catch (IllegalArgumentException ex) { throw new PermissaoException("Sem permissão de escrita no novo caminho"); } + } else { + throw new PermissaoException("Sem permissão de escrita no novo caminho"); } if (novoPai.getFilhos().containsKey(novoNome)) { @@ -577,12 +599,14 @@ public void ls(String caminho, String usuario, boolean recursivo) new IllegalArgumentException("Usuário não encontrado: " + usuario); } - if (!usuarioObj.getPermissoes().contains("r")) { + if (usuarioObj.getPermissoes().contains("r")) { try { diretorio.temPerm(usuario, "r"); } catch (IllegalArgumentException e) { throw new PermissaoException("Você não tem permissão para listar este diretório!"); } + } else { + throw new PermissaoException("Você não tem permissão para listar este diretório!"); } String output = lsRecursivo(diretorio, caminho, recursivo, usuario); @@ -607,7 +631,7 @@ public void cp(String caminhoOrigem, String caminhoDestino, String usuario, bool .findFirst() .orElseThrow(() -> new IllegalArgumentException("Usuário não encontrado: " + usuario)); - if (!usuarioObj.getPermissoes().contains("rw")) { + if (usuarioObj.getPermissoes().contains("rw")) { try { origem.temPerm(usuario, "r"); } catch (IllegalArgumentException e) { @@ -618,6 +642,8 @@ public void cp(String caminhoOrigem, String caminhoDestino, String usuario, bool } catch (IllegalArgumentException e) { throw new PermissaoException("Sem permissão de escrita em: " + caminhoDestino); } + } else { + throw new PermissaoException("Usuário não tem permissão para copiar: " + caminhoOrigem); } String nomeOrigem = origem.getNome(); diff --git a/tests/FileSystemImplTest.java b/tests/FileSystemImplTest.java index 3ae6c85..8089084 100644 --- a/tests/FileSystemImplTest.java +++ b/tests/FileSystemImplTest.java @@ -31,10 +31,10 @@ public static void setUp() throws CaminhoJaExistenteException, PermissaoExceptio fileSystem.addUser(new Usuario("cega", "/", "-wx")); fileSystem.mkdir("/area1", "joao"); - fileSystem.mkdir("/area1/area2", "tiago"); + fileSystem.mkdir("/area1/area2", "joao"); fileSystem.mkdir("/area1/area2/area_meh", "root"); - fileSystem.touch("/area1/area2/arquivo.txt", "root"); + fileSystem.touch("/area1/area2/arquivo.txt", "joao"); fileSystem.touch("/area1/area2/arquivo_meh.txt", "joao"); } @@ -236,7 +236,7 @@ public void testReadPathFail() { @Test public void testWriteSuccess() throws CaminhoNaoEncontradoException, PermissaoException { // Tenta escrever em um arquivo com permissão - assertDoesNotThrow(() -> fileSystem.write("/area1/arquivo.txt", "joao", true, buffer)); + assertDoesNotThrow(() -> fileSystem.write("/area1/arquivo2.txt", "joao", true, buffer)); } @Test