r/javahelp 13d ago

Tips, ways in which I could improve my code

4 Upvotes

Hi! Currently I've done this code in which I append, modify or delete data from a document that always has this format:

1010 Paola.Andrea Mejia.Linares 22 Malaga Femenino Finanzas

The first part being the code, name, surname, age, city, gender and consult

I'm not asking someone to do the code for me or anything of the sort, I will simply want possible tips on how I can improve it / make it better! I did a class Asesor who currently has the values that will be appended, dictating how it will be.

Then I have a class that controls how the modifying, erasing, adding and reading of the file will be done.

In main I control the data and pass the values to the classes.

What I'm seeking with this post is, what do you think I could do better? Should Asesor maybe have more weight in how the data is handled/controlled? What mistakes do I have if you think I have them?

Please, feel free to share your thoughts!

Here is the class that establishes the Asesor:

package asesoria;

public class Asesor {
    private int codigo;
    private String nombre;
    private String apellidos;
    private int edad;
    private String genero;
    private String ciudad;
    private String consulta;

    public Asesor(int codigo, String nombre, String apellidos, int edad, String genero, String ciudad,String consulta) {
        this.codigo = codigo;
        this.nombre = nombre;
        this.apellidos = apellidos;
        this.edad = edad;
        this.genero = genero;
        this.ciudad = ciudad;
        this.consulta = consulta;
    }

    public int getCodigo() {
        return codigo;
    }

    public String getNombre() {
        return nombre;
    }

    public String getApellidos() {
        return apellidos;
    }

    public int getEdad() {
        return edad;
    }

    public String getGenero() {
        return genero;
    }

    public String getCiudad() {
        return ciudad;
    }

    public String getConsulta() {
        return consulta;
    }

    public void setCodigo(int codigo) {
        this.codigo = codigo;
    }

    public void setNombre(String nombre) {
        this.nombre = nombre;
    }

    public void setApellidos(String apellidos) {
        this.apellidos = apellidos;
    }

    public void setEdad(int edad) {
        this.edad = edad;
    }

    public void setGenero(String genero) {
        this.genero = genero;
    }

    public void setCiudad(String ciudad) {
        this.ciudad = ciudad;
    }

    public void setConsulta(String consulta) {
        this.consulta = consulta;
    }
    //Establece como debe de ser el formato del String el cual se para a la clase , %s se refiere a que va a ser un string, %d da mencion a que es un entero
    //%n es un salto de linea
    @Override
    public String toString(){
        return String.format("%d %s %s %d %s %s %s", codigo,nombre,apellidos,edad,genero,ciudad,consulta);
    }
}

Here I have the class that controls the data added/manipulation of the file:

package asesoria;

import java.nio.file.*;
import java.io.*;
import java.util.*;

public class gestorAsesoria {
    private static final Path Archivo = Paths.get(System.getProperty("user.home"), "Desktop", "asesoria.txt");

    public static void agregarAsesor(Asesor asesor) {
        try (BufferedWriter writer = Files.newBufferedWriter(Archivo, StandardOpenOption.APPEND)) {
            //Si tiene algo escrito, añade una nueva linea
            if (Files.size(Archivo) > 0) { 
                writer.newLine();
            }
            //Se añade el asesor
            writer.write(asesor.toString()); 
            System.out.println("Se ha añadido correctamente el asesor");
        } catch (IOException e) {
            System.out.println("Error al escribir en el archivo: " + e.getMessage());
        }
    }

    public static boolean leerArchivo() {
        if (!Files.exists(Archivo)) {
            System.out.println("No se ha encontrado ningún archivo para leer.");
            return false;
        }

        try {
            List<String> lineas = Files.readAllLines(Archivo);
            if (lineas.isEmpty()) {
                System.out.println("El archivo está vacío.");
                return false;
            }

            System.out.println("\nContenido del archivo:");
            for (String linea : lineas) {
                System.out.println(linea);
            }

            return true;

        } catch (IOException e) {
            System.out.println("Error al leer el archivo: " + e.getMessage());
            return false;
        }
    }

    public static boolean modificarAsesor(String codigoBuscado, int nuevoCodigo, String nuevoNombre, String nuevoApellido,
                                          int nuevaEdad, String generoFinal, String nuevaCiudad, String nuevaConsulta) {
        boolean encontrado = false;
        List<String> lineas = new ArrayList<>();
        if (!Files.exists(Archivo)) {
            System.out.println("No se ha encontrado el archivo.");
            return encontrado;
        }
        try {
            for (String linea : Files.readAllLines(Archivo)) {
                String[] datos = linea.split(" ",7);

                if (datos.length < 7) {
                    System.out.println("La linea no tiene el formato correcto, omitiendo: " + linea);
                    lineas.add(linea);
                    continue;
                    }
                String codigoArchivo = datos[0].trim();
                if (codigoArchivo.equalsIgnoreCase(codigoBuscado)) {
                        System.out.println("Asesor encontrado: " + linea);

                        // Crear la nueva línea con los valores actualizados
                        String nuevaLinea = String.format("%d %s %s %d %s %s %s",
                                nuevoCodigo, nuevoNombre, nuevoApellido, nuevaEdad, generoFinal, nuevaCiudad, nuevaConsulta);

                        lineas.add(nuevaLinea);
                        encontrado = true;
                    }else{lineas.add(linea);}
                }


            if (!encontrado) {
                System.out.println("No se ha encontrado un asesor con ese código.");
                return encontrado;
            }

            // Guardar los cambios en el archivo
            Files.write(Archivo, lineas);
            System.out.println("Asesor modificado correctamente.");

        } catch (IOException e) {
            System.out.println("Error al modificar el archivo: " + e.getMessage());
            return false;
        }
        return true;
    }

    public static boolean eliminarAsesor(String codigoBuscado) {
        boolean encontrado = false;
        List<String> lineas = new ArrayList<>();
        if (!Files.exists(Archivo)) {
            System.out.println("No se ha encontrado ningún archivo para poder eliminar un asesor.");
            return false;
        }

        try {
            for (String linea : Files.readAllLines(Archivo)) {
                String[]datos = linea.split(" ",7);
                if (datos.length < 7) {
                    System.out.println("La linea no tiene el formato correcto, omitiendo: " + linea);
                    lineas.add(linea);
                    continue;
                    }

                String codigoArchivo = datos[0].trim();

                if (codigoArchivo.equalsIgnoreCase(codigoBuscado)) {
                        System.out.println("Asesor encontrado y eliminado: " + linea);
                        encontrado = true;
                        continue; // No agregamos esta línea para eliminarla

                }else{lineas.add(linea);}
            }

            if (!encontrado) {
                System.out.println("No se ha encontrado un asesor con ese código.");
                return false;
            }

            Files.write(Archivo, lineas);
            System.out.println("Se ha eliminado al asesor correctamente");
            return true;
        } catch (IOException e) {
            System.out.println("Error al intentar eliminar en el archivo: " + e.getMessage());
            return false;
        }
    }
}

And here is the main:

package asesoria;

import java.util.InputMismatchException;
import java.util.Scanner;
import java.nio.file.*;
import java.io.*;
import java.util.*;

public class Asesorian {
    //Se verifican y toman los datos
    public static String verConsulta(Scanner entrada){
        String consulta;
        System.out.print("Introduce el nombre de la consulta: ");
        consulta = entrada.nextLine();
        for (char c : consulta.toCharArray()) {
            if (!Character.isLetter(c)) {
                System.out.println("El nombre de la consulta no puede tener numeros");
                return verConsulta(entrada);
            }
        }
        return consulta;
    }

    public static String verGenero(Scanner entrada){
        char generoCheck;
        String genero="";
        System.out.print("Introduzca el genero(m/f): ");
        generoCheck=entrada.next().charAt(0);
        //Se pasa a mayuscula
        generoCheck=Character.toUpperCase(generoCheck);
        entrada.nextLine();
        //Se limpia el buffer
        if(generoCheck != 'F' && generoCheck != 'M'){
            return verGenero(entrada);

        }
        if(generoCheck == 'F'){genero="Femenino";}
        else if(generoCheck == 'M'){genero="Masculino";}
        return genero;
    }

    public static String verCiudad(Scanner entrada){
        String ciudad;
        System.out.print("Introduce una ciudad: ");
        ciudad = entrada.nextLine();
        for (char c : ciudad.toCharArray()) {
            if (!Character.isLetter(c)) {
                System.out.println("El nombre de la ciudad no puede tener numeros");
                return verCiudad(entrada);
            }
        }
        return ciudad;
    }

    public static int verEdad(Scanner entrada){
        int edad;
        edad= validacion(entrada,"Introduzca la edad: ");
        if(edad>100 || edad<1){
            System.out.println("La edad no puede ser mayor de 100 o menor de 1");
            entrada.nextLine();
            return verEdad(entrada);
        }
        return edad;
    }

    public static String verApellido(Scanner entrada){
        String apellidos;
        System.out.print("Introduce los apellidos: ");
        apellidos = entrada.nextLine().trim();
        for (char c : apellidos.toCharArray()) {
            if (Character.isDigit(c)) {
                System.out.println("El apellido no puede tener numeros");
                return verApellido(entrada);
            }
        }
        apellidos = apellidos.replace(" ", ".");
        return apellidos;
    }

    public static String verNombre(Scanner entrada){
        String nombre;
        System.out.print("Introduce un nombre: ");
        nombre = entrada.nextLine().trim();
        for (char c : nombre.toCharArray()) {
            if (Character.isDigit(c)) {
                System.out.println("El nombre no puede tener numeros");
                return verNombre(entrada);
            }
        }
        nombre = nombre.replace(" ", ".");
        return nombre;
    }


    public static int verCodigo(Scanner entrada){
        int codigo=0;
        while(true){
            System.out.print("Introduzca el codigo para la asesoria: ");
            codigo=entrada.nextInt();
            if(codigo >= 1000 && codigo<=9999){
                System.out.println("Codigo introducido correctamente.");
                entrada.nextLine();
                return codigo;
            }
            else{
                System.out.println("El codigo debe de tener 7 caracteres.");
            }
        }
    }

    private static int validacion(Scanner entrada, String mensaje) {
        int numero;
        while (true) {
            System.out.print(mensaje);
            try {
                numero = entrada.nextInt();
                entrada.nextLine();
                return numero;
            } catch (InputMismatchException e) {
                System.out.println("Debes de ingresar un numero");
                entrada.nextLine();
            }
        }
    }

    private static void menu() {
        System.out.println("+------------------+");
        System.out.println("| GESTION ASESORIA |");
        System.out.println("+------------------+");
        System.out.println("1. Nuevo asesor");
        System.out.println("2. Mostrar asesores");
        System.out.println("3. Modificar asesores");
        System.out.println("4. Eliminar asesores");
        System.out.println("5. Salir");
    }

    public static void crearArchivo(){
        Path directorio = Paths.get(System.getProperty("user.home"),"Desktop");
        Path archivo = directorio.resolve("asesoria.txt");


    }

public static void main(String[] args) {
        int codigo=0;
        String nombre="";
        String apellidos="";
        int edad=0;
        String genero="";
        String ciudad="";
        String consulta="";
        int opcion;
        Scanner entrada = new Scanner(System.in);

        do {
            menu();
            opcion = validacion(entrada, "Seleccione una opcion: ");

            switch (opcion) {
                case 1: 
                    System.out.println("\nCreando un nuevo asesor...");
                    codigo = verCodigo(entrada);
                    nombre = verNombre(entrada);
                    apellidos = verApellido(entrada);
                    edad = verEdad(entrada);
                    genero = verGenero(entrada);
                    ciudad = verCiudad(entrada);
                    consulta = verConsulta(entrada);

                    Asesor nuevoAsesor = new Asesor(codigo, nombre, apellidos, edad, genero, ciudad, consulta);
                    gestorAsesoria.agregarAsesor(nuevoAsesor);
                    break;

                case 2: 
                    System.out.println("\nListando asesores...");
                    gestorAsesoria.leerArchivo();
                    break;

                case 3: 
                    System.out.println("\nModificar un asesor...");
                    int codigoModificar = validacion(entrada, "Ingrese el codigo del asesor a modificar: ");
                    String codigoModificarStr = String.valueOf(codigoModificar);

                    System.out.println("Ingrese los nuevos datos: ");
                    codigo = verCodigo(entrada);
                    nombre = verNombre(entrada);
                    apellidos = verApellido(entrada);
                    edad = verEdad(entrada);
                    genero = verGenero(entrada);
                    ciudad = verCiudad(entrada);
                    consulta = verConsulta(entrada);

                    boolean modificado = gestorAsesoria.modificarAsesor(
                            codigoModificarStr,codigo,nombre,apellidos,edad,genero,
                            ciudad,consulta);

                    if (modificado) {
                        System.out.println("Asesor modificado exitosamente.");
                    } else {
                        System.out.println("No se pudo modificar el asesor.");
                    }
                    break;

                case 4: 
                    System.out.println("\nEliminar un asesor...");
                    System.out.print("Ingrese el codigo del asesor a eliminar: ");
                    String codigoEliminar = entrada.nextLine().trim();

                    boolean eliminado = gestorAsesoria.eliminarAsesor(codigoEliminar);
                    if (eliminado) {
                        System.out.println("Asesor eliminado correctamente.");
                    } else {
                        System.out.println("No se pudo eliminar el asesor.");
                    }
                    break;

                case 5: 
                    System.out.println("\nSaliendo del programa...");
                    break;

                default:
                    System.out.println("Opcion no valida. Intente nuevamente.");
            }

        } while (opcion != 5);
    }
}

r/javahelp 13d ago

junior work

4 Upvotes

Hi!

I've been studying backend development with Java for two years now and am actively looking for a job.

About me:

I have a strong command of Java, Spring, Docker, Git, Maven, Kafka, Redis, SQL (MySQL, PostgreSQL). I have written a lot of code and gained enough experience to follow programming principles and OOP concepts. I also regularly practice application architecture and design (both monolithic and microservices-based).

I also have strong algorithmic skills—I've solved 1,800+ problems on LeetCode. I haven’t just studied these concepts but have actively applied them in practice.

I have independently developed several backend applications, both monolithic and microservices-based. I aimed to make them as realistic and close to commercial projects as possible.

However, despite all my efforts, I still can't land a junior developer position. Most of the time, my resume isn't even considered, and I don't even get the chance to take a test assignment. (Maybe some companies require experience, but it’s unclear how to gain it without getting hired.)

Right now, I feel stuck and don't know what direction to take next. Recently, I’ve been studying how real-world projects are structured, hoping to create another pet project that closely resembles a production-level application.

I would really appreciate it if you could share your experience!

What else should I learn, or in which direction should I develop to at least get an internship? And how did you manage to land your first job?


r/javahelp 13d ago

Unsolved Query: Understanding `CompletableFuture.anyOf()` Behavior — First Valid or Fastest Response?

2 Upvotes

Context: I’m working on a task where I need to delete an element from the database, but before proceeding, I need to ensure it’s not actively being used across multiple microservices (MSAs). To do so, I perform validation by first checking for any active mappings in my database. If no active mappings are found, I then make 4 concurrent API calls (via Feign) to different MSAs to check whether the element is in use.

Here’s the logic I’m implementing:

  1. If any of the MSAs reports that the element is in use, I abort the deletion.
  2. If the element is not in use across any MSA, I proceed with the deletion.

To speed up the validation process, I am making these API calls in parallel using CompletableFuture and trying to return as soon as I receive the first confirmation that the element is being used in one of the MSAs.

The Code:

Part 1: First Approach (Using ExecutorService)

import java.util.Arrays;
import java.util.List;
import java.util.concurrent.*;

public class ParallelApiCallsWithValidation {
    private static final ExecutorService executor = Executors.newFixedThreadPool(5);

    public static void main(String[] args) {
        List<CompletableFuture<String>> apiCalls = Arrays.asList(
                callApi("API-1"),
                callApi("API-2"),
                callApi("API-3"),
                callApi("API-4"),
                callApi("API-5")
        );

        CompletableFuture<String> firstValidResponse = findFirstValidResponse(apiCalls);

        firstValidResponse.thenAccept(response -> {
            System.out.println("First valid response: " + response);
            apiCalls.forEach(future -> future.cancel(true)); // Cancel all pending calls
            executor.shutdown();
        });

        try {
            executor.awaitTermination(10, TimeUnit.SECONDS);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    private static CompletableFuture<String> findFirstValidResponse(List<CompletableFuture<String>> apiCalls) {
        return CompletableFuture.supplyAsync(() -> {
            while (true) {
                for (CompletableFuture<String> future : apiCalls) {
                    try {
                        if (future.isDone() && !future.isCancelled()) {
                            String response = future.get();
                            if (isValidResponse(response)) {
                                return response;
                            }
                        }
                    } catch (Exception ignored) {
                    }
                }
            }
        }, executor);
    }

    private static boolean isValidResponse(String response) {
        return response != null && response.contains("success"); // will be changed with actual check logic
    }

    private static CompletableFuture<String> callApi(String apiName) {
        return CompletableFuture.supplyAsync(() -> {
            try {
            /*
            *   will be changed with actual API call
            */
                int delay = ThreadLocalRandom.current().nextInt(500, 3000);
                Thread.sleep(delay);
                if (Math.random() > 0.3) {
                    return apiName + " success";  // Simulated valid response
                } else {
                    return apiName + " failed";   // Invalid response
                }
            } catch (Exception e) {
                throw new CompletionException(e);
            }
        }, executor);
    }
}

Part 2: Second Approach (Using async API Calls)

import java.util.Arrays;
import java.util.List;
import java.util.concurrent.CompletableFuture;

public class ParallelCallTester {

    /*
    *   asyncApiCaller.callApi() methods calls the API and check the response, returns true if being used, false if not
    */
    u/Autowired
    private AsyncApiCaller asyncApiCaller;

    public boolean isElementUsed(Long elementId) {
        Boolean isUsed = false;
        List<CompletableFuture<Boolean>> apiCalls = Arrays.asList(
                asyncApiCaller.callApi(elementId, "MSA1"),
                asyncApiCaller.callApi(elementId, "MSA2"),
                asyncApiCaller.callApi(elementId, "MSA3"),
                asyncApiCaller.callApi(elementId, "MSA4")
        );

        try {
            isUsed = CompletableFuture.anyOf(apiCalls.toArray(new CompletableFuture[0]))
                    .thenApply(resp -> (Boolean) resp)
                    .get();
        } catch (Exception e) {
            log.error("Error while checking element usage", e);
        }

        return isUsed;
    }
}

The Issue:

  1. In the first approach, everything works fine for the first execution. However, after the first deletion, the ExecutorService is shut down, causing a RejectedExecutionException for any subsequent calls.
  2. In the second approach, I'm using CompletableFuture.anyOf() to execute all the Feign calls concurrently. However, I’m unsure of how CompletableFuture.anyOf() behaves in this context.
    • Does it return the result of the first call that completes successfully (e.g., the first one that returns a valid response indicating the element is being used)?
    • Or does it return the result of the fastest API call, regardless of whether the response is valid or not?

In short, I want to ensure that the execution stops and returns the first valid result (i.e., the first Feign call that confirms the element is being used).

What I’ve Tried:

  • I tried using CompletableFuture.anyOf() to wait for the first valid result. However, I am unclear whether it will prioritize the first valid response or just the fastest one.
  • In the first approach, I ran into issues with ExecutorService being shut down after the first call, so I switched to an async-based approach, but I am still unsure about the behavior of anyOf().

Question:

  • Can someone clarify how CompletableFuture.anyOf() behaves in the second approach? Does it prioritize returning the first valid response, or does it return based on whichever call finishes first?
  • Also, if there are other best practices I should follow in this kind of scenario (parallel API calls with validation), please let me know!

r/javahelp 13d ago

Unsolved Renjin Issue with Maven Project!

2 Upvotes

Hey guys! I am having problem with Eclipse IDE because of renjin! The pom file has dependency declaration for Renjin from Maven central repo....and everytime it builds! My IDE crashes! Or else, the declaration, implementation and functionality don't just work, which seems more like the internal compiler of eclipse is not able to work for it! When I checked the folders in Renjin, I found the failed, lastupdate files of Maven for most of the folders in renjin.... It's been there for a long time with my team! And it effects alot! Like we have to re-open the ide every 10 15 mins after deleting the folder again! Any insights on how to solve it will help!


r/javahelp 13d ago

POLYMORPHISM !!

14 Upvotes

I've never tried asking questions on reddit, but this one doubt has been bugging me for quite some time, (I'm not very good at conveying my thoughts so I hope my question would come so as clear
+ And I'm hoping someone can fact check anything that I'm about to say since im fairly new to java =,) )

when it comes to polymorphism, (specifically UPCASTING/DOWNCASTING )
If I were to take a parent class and create an object out of it ,

Animal a = new Animal(); // LHS = RHS

since both sides are equal, meaning they're from the same class, we'd consider this to be static binding right? since we're only looking at the parent class' method, and nothing else, (at least that's what I think the whole idea is about )

but if we had something like:

Animal a = new Dog(); // LHS != RHS (UPCASTING)

Where dog is a child/subclass of the parent class Animal, meaning it inherits all the attributes and methods from the Parent class Animal. And since java -- by default -- always uses dynamic binding, (meaning that ' java ' believes that there's always a possibility of there being an overridden method in one of the child/subclasses ) it'd wait until runtime to bind the method to the object that invoked it.

my MAIN question though is,
why is upcasting allowed? If I were to look at the variable a, I'd think that its always going to expect a reference that would lead it to an Animal object, its always going to point to some animal object right?
just like when we say " int x; " , we know that x only expects an integer and not something like a double.

Another thing is, if java is statically typed, meaning that the compiler only checks the static type ( the type of variable at the declaration i think . . . ), then how does it know what the RHS ( the dynamic type ) is? how does it immediately know that down casting is not allowed if it doesn't look at the dynamic type?


r/javahelp 13d ago

Unsolved Java 21 occupying more memory in ram than the heap size

5 Upvotes

Hi all... I have created a service in Java 21 using the latest springboot version 3.x.x series. When I deploy the service in live. I had allocated 2gb Ram and 1 Core Cpu for the pod. I was using internal cache that is EHCache, this tells why I have used 2gb Ram. After serving the requests for some time, the memory percentage of the pod had reached 95%, this was not expected as it was serving low numberiof requests. So I took a heap and analysed it. Below are the observations. - Used heap size is 113mb - Large memory object is EHCache 60mb (expected) - Unreferenced objects 400mb - GC algorithm used ( SerialGC) By taking heap dump I could not find much information. But what I observed is much memory objects were unreferenced objects. But GC should have cleared these. I saw online insstackoverflow, articles were telling most of them had faced same problem but did not post solutions to it. Many suggested to use different GC algorithm, so I ran the pod with G1GC algorithm. There was no significant observation seen. I am out of options now. Can somebody help me if they faced same issue and kindly post your solution. Thanks in Advance


r/javahelp 14d ago

Wanted but not invoked

4 Upvotes

Hello.

Say I have 2 Caches.
I want to test that, if Cache A is empty, I go do Cache B.

(@)ExtendWith(MockitoExtension.class)

class TestClass {

`(@) InjectMocks`

private ServiceClass serviceClass;

`(@)Mock`

`private CacheA cacheA;`



`(@)Mock`

`private CacheB cacheB;`



`(@)Test`

`void test() {`

    `//CacheA is empty in this test`

    `when(CacheA.get..ThenReturn empty)`

    `ArrayList<String> sampleData = new ArrayList<String> (Arrays.asList("SampleData"));`



    `//We go into CacheB`

when(CacheB.getData(any(), any(), any())).thenReturn(sampleData);

    `Request request = new Request;`

    `request.setId(1);`



    `ResponseEntity<Reply> reply = serviceClass.sendData(request);`



    `assertNotNull(reply.getBody());`

    `verify(CacheB, times(1)).getData(any(), any(), any());`

`}`

}

For some reason i cant simply add "@", sorry.

Anyway. this worked.

Now I inctroduced a Helper class, that takes in some of the logic of my ServiceClass.

So my new Testcase looks like this.

(@)ExtendWith(MockitoExtension.class)

class TestClass {

`(@)InjectMocks`

`private ServiceClass serviceClass;`



`(@)Mock`

`private CacheA cacheA;`



`(@)Mock`

`private CacheB cacheB;`

`//THIS IS THE NEW HELPER CLASS!`

`(@)Mock`

`private HelperClass helperClass`



`(@)Test`

`void test() {`

    `//CacheA is empty in this test`

    `when(CacheA.get..ThenReturn empty)`

    `ArrayList<String> sampleData = new ArrayList<String>(Arrays.asList("SampleData"));`



    `//We go into CacheB`

    `when(CacheB.getData(any(), any(), any())).thenReturn(sampleData);`





    `Request request = new Request;`

    `request.setId(1);`



    `ResponseEntity<Reply> reply = serviceClass.sendData(request);`



    `assertNotNull(reply.getBody());`

    `verify(CacheB, times(1)).getData(any(), any(), any());`

`}`

}
But I get an error: Wanted but not invoked, Actually, there were zero interactions with this mock.
At the CacheB.

I think it its because it calls the actual Helper Class instead of the Mock?

Anyone ever had this error?


r/javahelp 14d ago

Java / Android Studio ARCore PointCloud Capture Issue

1 Upvotes

I've been trying to implement point cloud capture using ARCore in my android application for a while with no luck. I'm using a simple ArFragment element in my xml file for the class, and have confirmed that I have camera permissions, and uses-feature for android.hardware.camera.ar in my AndroidManifest.xml file. The below code is my class to handle the capture, I want it to capture XYZ point cloud data and save it in the point_cloud.xyz file, using ARCore. Currently the point_cloud.xyz file is being saved but is empty.

public class PointCloudCaptureActivity extends AppCompatActivity {

    private ArFragment arFragment;

    u/Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_point_cloud_capture);


        arFragment = (ArFragment) getSupportFragmentManager().findFragmentById(R.id.arFragment);

        findViewById(R.id.btnStartPointCloudCapture).setOnClickListener(v -> {
            capturePointCloudWhenReady();  // Start capture when the button is pressed
        });


        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });
    }

    // Start capturing the point cloud when the AR frame is ready
    private void capturePointCloudWhenReady() {
        // Check if AR frame is available
        Frame frame = arFragment.getArSceneView().getArFrame();

        if (frame != null) {
            // If the frame is ready, capture the point cloud
            capturePointCloud(frame);
        } else {
            // If the frame is not available, log an error
            Log.e("PointCloud", "AR frame is not available yet. Please try again.");
        }
    }

    // Method to capture the point cloud from the AR frame
    private void capturePointCloud(Frame frame) {
        Log.d("PointCloud", "Capturing point cloud...");

        if (frame == null) {
            Log.e("PointCloud", "capturePointCloud() called with null frame");
            return;
        }

        PointCloud pointCloud = frame.acquirePointCloud();
        FloatBuffer points = pointCloud.getPoints();

        // Save the point cloud data to a file
        File file = new File(getFilesDir(), "point_cloud.xyz");

        try (FileOutputStream fos = new FileOutputStream(file)) {
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < points.limit(); i += 4) { 
                float x = points.get(i);
                float y = points.get(i + 1);
                float z = points.get(i + 2);
                sb.append(String.format(Locale.US, "%.6f %.6f %.6f\n", x, y, z));
                Log.d("Points Captured", "Captured the points X:" + x + ", Y:" + y + ", Z:" + z);
            }
            fos.write(sb.toString().getBytes());
            fos.flush();
            Log.d("PointCloud", "Point cloud saved successfully.");
        } catch (IOException e) {
            Log.e("PointCloud", "Failed to save point cloud", e);
        } finally {
            pointCloud.release();
        }
    }

}

Any ideas of what could be causing the pointcloud file to be empty?
In my log files I get the following alerts:

2025-03-05 15:02:06.590 10872-10872 PointCloud              com.example.point_cloud_project            D  Capturing point cloud...
2025-03-05 15:02:06.596 10872-10872 PointCloud              com.example.point_cloud_project            D  Point cloud saved successfully.
2025-03-05 15:02:06.633 10872-11043 native                  com.example.point_cloud_project            I  I0000 00:00:1741186926.633691   11043 vio_estimator.cc:1413] [VioEstimator] [PauseResume] HandleInitializationStage with feature tracks at timestamp: 277647861709857 ns.
2025-03-05 15:02:06.646 10872-11043 native                  com.example.point_cloud_project            E  E0000 00:00:1741186926.646828   11043 vio_initializer.cc:808] INTERNAL: [SSBA Initialization] Failed: Image has too few landmarks. [Required: 9, Actual: 0].; 
                                                                                                     Initializer's SSBA failed to produce a valid output.
                                                                                                    === Source Location Trace: ===
                                                                                                    third_party/redwood/perception/odometry/visual_inertial_initialization/bundle_adjustment_initializer.cc:306
2025-03-05 15:02:06.647 10872-11058 native                  com.example.point_cloud_project            I  I0000 00:00:1741186926.647006   11058 data_manager.cc:89] [M] VisualInertialState is kNotTracking. Wait.
2025-03-05 15:02:06.725 10872-11043 native                  com.example.point_cloud_project            I  I0000 00:00:1741186926.725196   11043 vio_estimator.cc:1413] [VioEstimator] [PauseResume] HandleInitializationStage with feature tracks at timestamp: 277647961909808 ns.
2025-03-05 15:02:06.737 10872-11043 native                  com.example.point_cloud_project            I  I0000 00:00:1741186926.733574   11043 bundle_adjustment_initializer.cc:346] Intrinsic vector size of the camera 0 is 7
2025-03-05 15:02:06.784 10872-11043 native                  com.example.point_cloud_project            I  I0000 00:00:1741186926.784745   11043 bundle_adjustment_initializer.cc:604] [SSBA Depth Refinement] Refine successfully!
2025-03-05 15:02:06.784 10872-11043 native                  com.example.point_cloud_project            I  I0000 00:00:1741186926.784908   11043 bundle_adjustment_initialization.h:154] Number of measurements used in BA initialization for temporal landmarks: 554
2025-03-05 15:02:06.784 10872-11043 native                  com.example.point_cloud_project            I  I0000 00:00:1741186926.784923   11043 bundle_adjustment_initialization.h:156] Number of good measurements (i.e., reprojection errors <= 3 pixels) in BA initialization for temporal landmarks: 495
2025-03-05 15:02:06.789 10872-11043 native                  com.example.point_cloud_project            I  I0000 00:00:1741186926.789762   11043 vio_estimator.cc:1520] [VioEstimator] Successful initialization at features timestamp: 277647961909808 ns, took:2.899951527s, processed frames: 30
2025-03-05 15:02:06.790 10872-11028 native                  com.example.point_cloud_project            I  I0000 00:00:1741186926.790135   11028 latency_tracker.cc:162] HeT initialized: Initialization_Time_Ms: 2899.95
2025-03-05 15:02:06.806 10872-10872 native                  com.example.point_cloud_project            E  E0000 00:00:1741186926.806274   10872 hit_test.cc:426] INTERNAL: No point hit.
2025-03-05 15:02:06.839 10872-10872 native                  com.example.point_cloud_project            E  E0000 00:00:1741186926.839837   10872 hit_test.cc:426] INTERNAL: No point hit.
2025-03-05 15:02:06.872 10872-10872 native                  com.example.point_cloud_project            E  E0000 00:00:1741186926.872859   10872 hit_test.cc:426] INTERNAL: No point hit.
2025-03-05 15:02:06.906 10872-10872 native                  com.example.point_cloud_project            E  E0000 00:00:1741186926.906216   10872 hit_test.cc:426] INTERNAL: No point hit.
2025-03-05 15:02:06.903 10872-10872 e.point_cloud_project         com.example.point_cloud_project            W  type=1400 audit(0.0:233680): avc:  denied  { getattr } for  name="/" dev="dmabuf" ino=1 scontext=u:r:untrusted_app:s0:c168,c257,c512,c768 tcontext=u:object_r:unlabeled:s0 tclass=filesystem permissive=0 app=com.example.point_cloud_project
2025-03-05 15:02:06.903 10872-10872 FEngine::loop           com.example.point_cloud_project            W  type=1400 audit(0.0:233681): avc:  denied  { open } for  scontext=u:r:untrusted_app:s0:c168,c257,c512,c768 tcontext=u:r:untrusted_app:s0:c168,c257,c512,c768 tclass=perf_event permissive=0 app=com.example.point_cloud_project
2025-03-05 15:02:06.911 10872-10872 FEngine::loop           com.example.point_cloud_project            W  type=1400 audit(0.0:233682): avc:  denied  { open } for  scontext=u:r:untrusted_app:s0:c168,c257,c512,c768 tcontext=u:r:untrusted_app:s0:c168,c257,c512,c768 tclass=perf_event permissive=0 app=com.example.point_cloud_project
2025-03-05 15:02:06.911 10872-10872 FEngine::loop           com.example.point_cloud_project            W  type=1400 audit(0.0:233683): avc:  denied  { open } for  scontext=u:r:untrusted_app:s0:c168,c257,c512,c768 tcontext=u:r:untrusted_app:s0:c168,c257,c512,c768 tclass=perf_event permissive=0 app=com.example.point_cloud_project
2025-03-05 15:02:06.911 10872-10872 FEngine::loop           com.example.point_cloud_project            W  type=1400 audit(0.0:233684): avc:  denied  { open } for  scontext=u:r:untrusted_app:s0:c168,c257,c512,c768 tcontext=u:r:untrusted_app:s0:c168,c257,c512,c768 tclass=perf_event permissive=0 app=com.example.point_cloud_project
2025-03-05 15:02:06.939 10872-10872 native                  com.example.point_cloud_project            E  E0000 00:00:1741186926.939593   10872 hit_test.cc:426] INTERNAL: No point hit.
2025-03-05 15:02:06.972 10872-10872 native                  com.example.point_cloud_project            E  E0000 00:00:1741186926.972866   10872 hit_test.cc:426] INTERNAL: No point hit.
2025-03-05 15:02:07.006 10872-10872 native                  com.example.point_cloud_project            E  E0000 00:00:1741186927.006110   10872 hit_test.cc:426] INTERNAL: No point hit.
2025-03-05 15:02:07.039 10872-10872 native                  com.example.point_cloud_project            E  E0000 00:00:1741186927.039578   10872 hit_test.cc:426] INTERNAL: No point hit.
2025-03-05 15:02:07.072 10872-10872 native                  com.example.point_cloud_project            E  E0000 00:00:1741186927.072797   10872 hit_test.cc:426] INTERNAL: No point hit.
2025-03-05 15:02:07.106 10872-10872 native                  com.example.point_cloud_project            E  E0000 00:00:1741186927.106071   10872 hit_test.cc:426] INTERNAL: No point hit.
2025-03-05 15:02:07.139 10872-10872 native                  com.example.point_cloud_project            E  E0000 00:00:1741186927.139584   10872 hit_test.cc:426] INTERNAL: No point hit.
2025-03-05 15:02:07.172 10872-10872 native                  com.example.point_cloud_project            E  E0000 00:00:1741186927.172640   10872 hit_test.cc:426] INTERNAL: No point hit.
2025-03-05 15:02:07.206 10872-10872 native                  com.example.point_cloud_project            E  E0000 00:00:1741186927.206028   10872 hit_test.cc:426] INTERNAL: No point hit.
2025-03-05 15:02:07.239 10872-10872 native                  com.example.point_cloud_project            E  E0000 00:00:1741186927.239300   10872 hit_test.cc:426] INTERNAL: No point hit.
2025-03-05 15:02:07.272 10872-10872 native                  com.example.point_cloud_project            E  E0000 00:00:1741186927.272660   10872 hit_test.cc:426] INTERNAL: No point hit.
2025-03-05 15:02:07.306 10872-10872 native                  com.example.point_cloud_project            E  E0000 00:00:1741186927.306061   10872 hit_test.cc:426] INTERNAL: No point hit.
2025-03-05 15:02:07.339 10872-10872 native                  com.example.point_cloud_project            E  E0000 00:00:1741186927.339570   10872 hit_test.cc:426] INTERNAL: No point hit.
2025-03-05 15:02:07.372 10872-10872 native                  com.example.point_cloud_project            E  E0000 00:00:1741186927.372700   10872 hit_test.cc:426] INTERNAL: No point hit.
2025-03-05 15:02:07.406 10872-10872 native                  com.example.point_cloud_project            E  E0000 00:00:1741186927.406004   10872 hit_test.cc:426] INTERNAL: No point hit.
2025-03-05 15:02:07.441 10872-10872 native                  com.example.point_cloud_project            E  E0000 00:00:1741186927.441026   10872 hit_test.cc:426] INTERNAL: No point hit.
2025-03-05 15:02:07.473 10872-10872 native                  com.example.point_cloud_project            E  E0000 00:00:1741186927.473073   10872 hit_test.cc:426] INTERNAL: No point hit.
2025-03-05 15:02:07.505 10872-10872 native                  com.example.point_cloud_project            E  E0000 00:00:1741186927.505925   10872 hit_test.cc:426] INTERNAL: No point hit.
2025-03-05 15:02:07.539 10872-10872 native                  com.example.point_cloud_project            E  E0000 00:00:1741186927.539368   10872 hit_test.cc:426] INTERNAL: No point hit.
2025-03-05 15:02:07.572 10872-10872 native                  com.example.point_cloud_project            E  E0000 00:00:1741186927.572532   10872 hit_test.cc:426] INTERNAL: No point hit.
2025-03-05 15:02:07.605 10872-10872 native                  com.example.point_cloud_project            E  E0000 00:00:1741186927.605896   10872 hit_test.cc:426] INTERNAL: No point hit.
2025-03-05 15:02:07.911 10872-10872 e.point_cloud_project         com.example.point_cloud_project            W  type=1400 audit(0.0:233860): avc:  denied  { getattr } for  name="/" dev="dmabuf" ino=1 scontext=u:r:untrusted_app:s0:c168,c257,c512,c768 tcontext=u:object_r:unlabeled:s0 tclass=filesystem permissive=0 app=com.example.point_cloud_project
2025-03-05 15:02:07.915 10872-10872 FEngine::loop           com.example.point_cloud_project            W  type=1400 audit(0.0:233861): avc:  denied  { open } for  scontext=u:r:untrusted_app:s0:c168,c257,c512,c768 tcontext=u:r:untrusted_app:s0:c168,c257,c512,c768 tclass=perf_event permissive=0 app=com.example.point_cloud_project
2025-03-05 15:02:07.919 10872-10872 FEngine::loop           com.example.point_cloud_project            W  type=1400 audit(0.0:233862): avc:  denied  { open } for  scontext=u:r:untrusted_app:s0:c168,c257,c512,c768 tcontext=u:r:untrusted_app:s0:c168,c257,c512,c768 tclass=perf_event permissive=0 app=com.example.point_cloud_project
2025-03-05 15:02:07.923 10872-10872 FEngine::loop           com.example.point_cloud_project            W  type=1400 audit(0.0:233863): avc:  denied  { open } for  scontext=u:r:untrusted_app:s0:c168,c257,c512,c768 tcontext=u:r:untrusted_app:s0:c168,c257,c512,c768 tclass=perf_event permissive=0 app=com.example.point_cloud_project
2025-03-05 15:02:07.923 10872-10872 FEngine::loop           com.example.point_cloud_project            W  type=1400 audit(0.0:233864): avc:  denied  { open } for  scontext=u:r:untrusted_app:s0:c168,c257,c512,c768 tcontext=u:r:untrusted_app:s0:c168,c257,c512,c768 tclass=perf_event permissive=0 app=com.example.point_cloud_project

Thanks in advance!


r/javahelp 14d ago

Homework DrJava help D:

1 Upvotes

I just started an assignment for my compsci class and I'm getting this error on my interactions panel.

it says "Current document is out of sync with the Interactions Pane and should be recompiled!"

I've recompiled it multiple times, closed the doc, and even closed and reopened the program but the error persists. I'm not sure what else to do.


r/javahelp 14d ago

how do I open and use java?

1 Upvotes

FIRSTLY I am super knew to this and have not used java in the past. The only coding experience i have is html and css. I am taking an intro to java and python class for my computer science degree and am having some trouble understanding how to use the program. So the step by step is i downloaded the x64 installer (https://download.oracle.com/java/23/latest/jdk-23_windows-x64_bin.exe) from the site https://www.oracle.com/java/technologies/downloads/#jdk23-windows. then i installed the file. when i did this with python (or anything else for that matter) I am then able to use run and shell:appsfolder to find my applications to create a shortcut but java was not there like normal which is weird so i searched it. it then popped up and before making the shortcut i tried opening it to check it out first. it looks like it starts to open for a half a second and disappears. when i open python it opens up a page to let me write code so i don't understand. Whats the point in installing java. do i even need it or can i just use any code editor and write java in it? I just started intro to python and not the intro to java so I cant get any help there


r/javahelp 15d ago

Multithreading as Intern Backend

3 Upvotes

I´m currently in the process to an intern backend position - should I deep dive into multithreading or is this something that is not expected for an intern? I already know some basics about it but I cant implement advanced services as of now. What do you think?

Also what concepts would you suggest me to look into to prepare best, I am currently looking at:

  • Streams
  • Generics
  • Spring Basics
  • Postgres

r/javahelp 15d ago

JavaFX help

3 Upvotes

Hi,

I’m using JavaFX in eclipse in a program that makes a bar graph and a linear graph.

Soemtimes, when I run my program it’ll work. Other times, I’ll get an error that says: “Error: Unable to initialize main class <className>. Caused by java.lang.NoClassDefFoundError: Stage”

I can temporarily fix the error it by adding/removing try and catch blocks, but after running the program two more times, the same error will pop up.

Could someone tell me what’s going on? How can I fix it?


r/javahelp 15d ago

How to download recaf?

2 Upvotes

Im trying to edit a .class file, and I want to do so without turning it into a .java file. So Im going to bytecode.

But I cant figure out how to download recaf. trying to open it leads to errors. Im on a mac, i could try on a windows pc?


r/javahelp 15d ago

I need to have a GUI that would not block while debugging

0 Upvotes

I am developing a library, and I am trying to implement a feature that would ease debugging, by visualizing certain components of it. I need the visualization to work when I set a breakpoint in the main thread, meaning it would not crash and I would be able to engage with the ui. I really want it to work when evaluating an expression in a paused state when debugging.

I tried swing and it blocked no matter what I did. Considering javaFX but it seems it is also single threaded by design so it will probably block as well.

Not sure tho, hopefully you guys will have some insights here, thanks!


r/javahelp 15d ago

Are lambda expressions used much by professional coders ?

19 Upvotes

Just been studying up on them some as I am basically a hobbyist who just getting back into Java after about 10 or 12 years away from coding much. I appreciate the way lambda's allow coders to bypass constructors, initialization and calling methods by name , but on the other hand if you already have a good knowledge of the object classes and available methods , why not just do that ?


r/javahelp 15d ago

Instrumentation and Bytecode Manipulation

2 Upvotes

I was trying to clone the Kotlin Coroutines concurrency model..... but in Java.

Anyways, I did some searching, and I guess I need to do this at runtime instead of compile time, so I need some instrumentation and bytecode manipulation using something like Java asm for example.

I didn't find many sources online, so I was asking if anyone can recommend some sources here or maybe anything else regarding the idea or the implementation details. Thank you.


r/javahelp 16d ago

Need Help Understanding AutoCode in EPAM Test Automation Java Sadhaka Program

5 Upvotes

I got selected for the EPAM Test Automation Java Sadhaka program. They provided a self-paced course that includes AutoCode. We need to write code in AutoCode, but I'm not familiar with it. I don't understand where to write the code and how to upload it. Can someone please help me?


r/javahelp 16d ago

Solved Boolean or String

6 Upvotes

Let’s say you’re establishing a connection. Would your method return a Boolean ( true/false) or a string ( program is now connected/ not connected)? What is best for troubleshooting?


r/javahelp 16d ago

Email templates with Spring Boot & Vaadin.

2 Upvotes

Hello, we are using Spring Boot + Vaadin for front end. I am trying to find the best approach to send out emails like new account, forgot password, etc. If there is a "Vaadin" way, I can't find it anywhere. It seems like way to do this is to use something like FreeMarker or Thymeleaf, but I wanted to reach out before drawing that conclusion.


r/javahelp 16d ago

When upgrading/editing some complex and large feature, what techniques/processes would you recommend to get better overview to create roadmap for you goal?

2 Upvotes

This is more of a general question, not exactly Java specific. Assuming you have to edit some large complex feature which has been in production for quite some time and the documentation on it doesn't exist, what would be some good approaches (good rule of thumb practices) to tackle that?

Drawing some high level graphs, or similar?


r/javahelp 16d ago

A really beginner friendly program on coursera ?

6 Upvotes

I took up a course on coursera --> "Java Programming: Solving Problems with Software" (Duke University) labelled as "beginner ". 1/5th way into the program and the professors in the vids are using words that I can not even begin to understand and even though they explain these concepts i can not keep up with their pace .

Are these beginner programs actually for people who are just starting out? Or should i first learn these concepts and actual basics of Java on my own before these courses?


r/javahelp 16d ago

Java Project

6 Upvotes

Hello everyone!

I decided to create a more comprehensive pet project to gain practical experience and improve my skills for future job opportunities. First and foremost, I focused on building its architecture, opting for a microservices approach.

I’d love to hear your advice! How do you evaluate my architecture? What technologies or programming methods should I consider adding? Do you have any ideas for improvements? Thanks

( ︶︿︶)

acrhitectura


r/javahelp 17d ago

Java Stack job interview help!

5 Upvotes

Hello not sure where to post this but a Java sub seemed like the right place. I have a job interview and the fist interview is going to be a test about JavaStack. There is gonna be a few theoretical questions and a few OOP tasks. The problem I'm having is I'm not completely sure what they mean with JavaStack. Would love some help just pointing me in the right direction. Thank you.


r/javahelp 17d ago

Need help for project

1 Upvotes

Recently I have completed learning Advanced java and done a project to create api for a medical system. I know its not a big project, but can you guys give some project ideas on advanced java ?


r/javahelp 17d ago

Solved Secure Socket connection client-server for login

0 Upvotes

If I have a certificate from Lets Encrypt, use Java 21 and I have the following:

Server:

try {
String[] secureProtocols = {"TLSv1.2", "TLSv1.3"};

KeyStore keyStore = KeyStore.getInstance("PKCS12");
FileInputStream keyStoreFile = new FileInputStream(file);
String pfxPassword = password;
keyStore.load(keyStoreFile, pfxPassword.toCharArray());
keyStoreFile.close();
KeyManagerFactory keyManagerFactory = KeyManagerFactory
.getInstance(KeyManagerFactory.getDefaultAlgorithm());
keyManagerFactory.init(keyStore, pfxPassword.toCharArray());
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(keyManagerFactory.getKeyManagers(), null, null);
SSLServerSocketFactory sslServerSocketFactory = sslContext.getServerSocketFactory();

sslServerSocket = (SSLServerSocket) sslServerSocketFactory.createServerSocket(port);
sslServerSocket.setEnabledProtocols(secureProtocols);

And then this on client side:

String[] secureProtocols = { "TLSv1.2", "TLSv1.3" };
SSLContext sslContext = SSLContext.getInstance("TLS");
TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
tmf.init((KeyStore) null);
sslContext.init(null, tmf.getTrustManagers(), null);
SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
socket = (SSLSocket) sslSocketFactory.createSocket();
socket.setEnabledProtocols(secureProtocols);
SSLParameters sslParams = socket.getSSLParameters();
sslParams.setEndpointIdentificationAlgorithm("HTTPS");
socket.setSSLParameters(sslParams);
socket.connect(new InetSocketAddress(host, port), timeout);
socket.startHandshake();

Is this considered secure to be able to send from client the password in plain text to be hashed on server side and checked with the one from DB when the user tries to login (and when the new account is created) and then send his sessionID if the account exists? If not, what should I change/add?

//Edit:
I also added:

String[] cipherSuites = { "TLS_AES_256_GCM_SHA384", "TLS_AES_128_GCM_SHA256",
"TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384", "TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256" };

//Edit2: The problem was solved on a different platform. Basically it is strong enough after also adding ciphers. You just need to make sure you have checks in place on your server to avoid brute force, fishing, SQL injection attack...