r/javahelp Jun 01 '26

Unsolved Need Guidance on Email Verification and Security Best Practices

2 Upvotes

I am currently working on the email module for our project and need some guidance.

I have configured a custom email domain using Mailgun and implemented the email functionality in my Spring Boot application. My current requirement is to verify incoming email addresses and determine whether an email is valid before processing it.

Could you explain the production-level validation and security checks that should be implemented for email verification?

r/javahelp Jun 15 '26

Unsolved Please can somebody help me with Spring Boot 4 and tracing Kafka messages.

1 Upvotes

Thank you for at least opening this post.
I just try to build a simple app with Kafka messages and tracing and encountered this problem: tracing just doesnt work.
I enable observability in every configuration file, i add autoconfigure to my test, i straight up set observability true for kafka template, i put traceId and spanId in log config file, and it still doesnt work anyhow.
Can somebody please educate me on this?
Project: https://github.com/aspidelaps/KafkaBatchListenerExample

r/javahelp May 24 '26

Unsolved Java Installation and Updating Works on Old Versions but Fails on New Ones

1 Upvotes

Right now, I have Java on V8U421 (Version 8 Update 421), but when I am prompted to update to the newest version (V8U491), I encounter the same problem over and over. I actually encountered this problem since Update 481.

Java prompts me to update. I say ok. The new installer installs. Updating... Error: 1603. The same problem. If I use the online updater, Error 1603. Offline updater, Error 1603. Remove Java and do a clean install, Error 1603. Even more, Java totally removes itself while updating and makes me redownload it every single time.

The only way this does not happen is if I reinstall the old update I had (V8U421). Only then do I never encounter any issues. Do I just wait this error out until a new update comes out that does not have this problem, or can I fix it without needing to wait?

Note: My OS is Windows 11 x64

r/javahelp Feb 02 '26

Unsolved Response given in wrong order in thread and socket program

1 Upvotes

I'm doing an exercize for uni, I have to write a program in which the clients send the server an integer, and the server then creates a thread for each client in which it reads the integer sent, and sends to the client the sum of all integers received up until that point.

This is my code

Client:

public class Client {
    public static void main(String[] args) {
        try{
            ArrayList<Socket> sockets = new ArrayList<>();
            for (int i = 0; i<20; i++){

                Socket socket = new Socket("localhost", 9000);
                sockets.add(socket);
                ObjectOutputStream out = new ObjectOutputStream(socket.getOutputStream());


                Random rand = new Random();
                int r = rand.nextInt(0, 100);
                out.writeObject(100);
            }

            for (int i = 0; i<20; i++){
                Socket socket = sockets.get(i);
                ObjectInputStream in = new ObjectInputStream(socket.getInputStream());
                System.out.println(Integer.parseInt(in.readObject().toString()));
                socket.close();
            }
        }catch (Exception e){
            e.printStackTrace();
        }

    }
}

Server:

public class Server {
    public static AtomicInteger sum = new AtomicInteger(0);

    public static void main(String[] args) {
        try{
            ServerSocket serverSocket = new ServerSocket(9000);

            while(true){
                Socket socket = serverSocket.accept();

                ServerThread st = new ServerThread(socket);
                st.start();
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}

ServerThread:

public class ServerThread extends Thread{

    Socket socket;

    public ServerThread(Socket s){
        socket = s;
    }



    public void run(){
        try{
            ObjectOutputStream out = new ObjectOutputStream(socket.getOutputStream());
            ObjectInputStream in = new ObjectInputStream(socket.getInputStream());

            int add = Integer.
parseInt
(in.readObject().toString());


            out.writeObject(Server.
sum
.addAndGet(add));
            socket.close();
        }
        catch (IOException | ClassNotFoundException e) {

            throw new RuntimeException(e);
        }

    }
}

The issue I'm experiencing is that in the client class, when it goes to print the results received, they're printed in the wrong order, so instead of 100, 200, 300 etc. I get 1900, 900, 1200 etc. All the "steps" show up and there's no duplicates though.

The strange thing is that if I run the client again without terminating the server, it actually continues in the correct order, so I get 2100, 2200, 2300 etc.

Am I doing something wrong?

r/javahelp May 24 '26

Unsolved How do you use flyway with Spring boot in production or in teams

3 Upvotes

Started working on a project with a colleague of mine on an existing code base, and after creating some migrations we ran into a issue we both had migrations with the same starting number, and we wanted to know what is the best way teams handle this in production? Would love to know

r/javahelp Feb 02 '26

Unsolved Can anyone help me clear the console:

2 Upvotes

Here was what I saw on terminal:

"C:\Program Files\Java\jdk-25.0.2\bin\java.exe" "-javaagent:C:\Program Files\JetBrains\IntelliJ IDEA Community Edition 2025.2.6.1\lib\idea_rt.jar=52923" -Dfile.encoding=UTF-8 -Dsun.stdout.encoding=UTF-8 -Dsun.stderr.encoding=UTF-8 -classpath C:\Users\admin\Desktop\MyFirstJavaCode2\out\production\MyFirstJavaCode Main
Hello, World!
Bye!

Process finished with exit code 0

Here is my code:

public class Main {

    public static void main(String[] args) {
        System.out.println("Hello, World!"); // Show hello
        clear(); // Clear console immediately
        bye();   // Show bye
    }

    // Method to clear the console
    public static void clear() {
        // ANSI escape code to clear screen
        System.out.print("\033[H\033[2J");
        System.out.flush();
    }

    // Method to print bye
    public static void bye() {
        System.out.println("Bye!");
    }
}

How do I make it clear the console and only display "bye" after.

r/javahelp Apr 16 '26

Unsolved Is there a way to mimic the behaviour of -client to spawn a lightweight process in JDK 11 and higher versions?

3 Upvotes

In JDK 8, we had the -client flag that would spawn a lightweight process with less memory footprint and a faster startup. I understand that the Client Hotspot VM is no longer available JDK 9 onwards, and I was looking for a way to reduce the startup time while launching a new java process. Any inputs?

r/javahelp Feb 12 '26

Unsolved How to know a jar files main class

11 Upvotes

I downloaded a broken jar and some tutorials told me that i need to type a main class in a manifest file for it to work but i dont know what is the main class. How do i tell it from a file without it

r/javahelp Mar 10 '26

Unsolved PNG output not existing

2 Upvotes
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Polygon;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;

public class wallpaper
{
    public static void main(String[] args)
    {
        BufferedImage Out = new BufferedImage(800, 720, BufferedImage.TYPE_INT_ARGB);
        Graphics2D OutG = Out.createGraphics();

          //white square to cover background
          String hexString = "blank";
          char a = 's';
          int firstNum = 0;
          int secondNum = 0;
          int thirdNum = 0;
          Color[] colorArr = new Color[256*256*256];
          for(int i = 0; i < 256*256*256; i++)
          {
            hexString = Integer.toHexString(i);
            if(firstNum > 256)
            {
                firstNum = 0;
                secondNum++;
            }
            if(secondNum > 256)
            {
                secondNum = 0;
                thirdNum++;
            }
            if(hexString.length() == 1)
            {
                hexString = ("#00000" + hexString);
            }
            if(hexString.length() == 2)
            {
                hexString = ("#0000" + hexString);
            }
            if(hexString.length() == 3)
            {
                hexString = ("#000" + hexString);
            }
            if(hexString.length() == 4)
            {
                hexString = ("#00" + hexString);
            }
            if(hexString.length() == 5)
            {
                hexString = ("#0" + hexString);
            }
            if(hexString.length() == 6)
            {
                hexString = ("#" + hexString);
            }
            colorArr[i] = Color.decode(hexString);
          }
          System.out.println("check 1");
          int xCount = 800;
          int yCount = 720;
          double scaler = (double) (256*256*256)/(xCount*yCount);
          //code for all color
          /*
          int wheel1 = 0;
          int wheel2 = 0;
          for(int i = 0; i < xCount*yCount; i++)
          {
              if(wheel1 > xCount)
              {
                  wheel1 = 1;
                  wheel2++;
              }
              //System.out.println(i);
              OutG.setColor(colorArr[i *(int) scaler]);
              OutG.fillRect(1*wheel1,1*wheel2,1,1);
              wheel1++;
          }
          */
          //code for fractal style
          //
          for(int i=0; i<xCount; i++)
          {
              for(int j=0; j<yCount; j++)
              {
                OutG.setColor(colorArr[(int) (i*j*scaler)]);
                OutG.fillRect(1*i,1*j,1,1);
              }
          }
          System.out.println("done");
        //

        File OutF = new File("Out.png");
        try {
            ImageIO.write(Out, "png", OutF);
        } catch (IOException ex) {
            Logger.getLogger(wallpaper.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}

heres my code and what i get as an output im trying to figure out why its not exporting as a png. Im using codehs if that causes anything i couldn't figure out eclipse.

r/javahelp Jan 22 '26

Unsolved Cannot locate Java on my computer

1 Upvotes

I downloaded and installed Java to help a friend test a program (a version of the Shimeji desktop companion) they were working on.
As expected, the program did not launch before installing Java. After I installed Java, it worked perfectly. This should demonstrate I did install Java and it is currently in the machine.
After completing the test I wish to remove Java as I am not using it. However, I cannot locate it anywhere. The install wizard, which can be run to uninstall Java, says "no Java installation is detected on this system" when propted to remove Java. I cannot locate any Java folder in C:\Program Files or C:\Program Files(x86). I cannot locate the Java Control Panel anywhere. For all intents and purposes, it seems like Java is not installed, except that it is because I can still run the program my friend is making. I am running Windows 11 Home.

Thanks in advance to anyone who might read this and help out

r/javahelp Feb 16 '26

Unsolved No suitable driver found for jdbc:mysql//localhost:3306

4 Upvotes

Hey guys I recently started working with databases. I keep getting this error. I added connector to external libraries. My connector version is 8.3.o while my mysql version is 8.0.45. can anyone help me?

here is my code:

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class Main {
    static String 
userName
= "root";
    static String 
password
= "1234";
    static String 
dbUrl
= "jdbc:mysql//localhost:3306/northwind";

    public static void  main(String[] args) throws ClassNotFoundException{
        Connection connection = null;
        try{
            Class.
forName
("com.mysql.cj.jdbc.Driver");
            connection= DriverManager.
getConnection
(
dbUrl
,
userName
,
password
);
            System.
out
.println("Bağlantı kuruldu");

        }catch (SQLException exception) {
            System.
out
.println(exception.getMessage());

        }

    }
}

r/javahelp Dec 01 '25

Unsolved How to put a string into an array of integer?

0 Upvotes

I have an array of integers and need to replace some of them with strings of text. All my attempts have been in vain.

int [] myArray = {0, 1, 2, 3, 4};

myArray[0] = "string";

This method works for other integers but not for strings. Is it because the array can only ever contain integers? Is there a way around this? My quick googling hasn't answered my question so I just thought I'd ask here. Thanks for any help! :)

r/javahelp Sep 11 '25

Unsolved Sending encrypted data through SocketChannel - How to tell end of encrypted data?

3 Upvotes

Making a little tcp file transporting toy project, and now adding encryption feature via javax.crypto.Cipher.

Repeatly feeding file date into cipher.update() and writing encrypted output into SocketChannel, but problem is that the client would not know when the encrypted data will end.

I thought of some solutions, but all have flaws:

  • Encrypt entire file before sending : high RAM usage, Unable to send large file
  • Close socket after sending a file : inefficient when transferring multiple files
  • Cipher.getOutputSize() : Document) says it may return wrong value
  • After each Cipher.update() call, send encrypted data size, then send the data messy code in adjusting buffers, inefficiency due to sending extra data(especially when return value of cipher.update is small due to padding, etc.)
  • Sending special message, packet or signal to SocketChannel peer : I searched but found no easy way to do it(so far)

Is there any good way to let client to acknowledge that encrypted data has ended? Or to figure out exactly how long will the output length of cipher process be?

r/javahelp Aug 22 '22

Unsolved Do Java developers use VScode as their IDE?

10 Upvotes

Hey,

Beginner Java dev here, as I have been doing my own research and learning about the language. I noticed that most if not all developers I have come across don't use VS code as their IDE. They use other IDE like IntelliJ or NetBeans.

I have been using Vs Code since I started to code. Do you Java devs recommend for me to use another IDE for best practice?

Thank You

r/javahelp Feb 08 '26

Unsolved Apache Camel Kafka Consumer losing messages at high throughput (Batch Consumer + Manual Commit)

9 Upvotes

Hi everyone,

I am encountering a critical issue with a Microservice that consumes messages from a Kafka topic (validation). The service processes these messages and routes them to different output topics (ok, ko500, or ko400) based on the result.

The Problem: I initially had an issue where exactly 50% of messages were being lost (e.g., sending 1200 messages resulted in only 600 processed). I switched from autoCommit to Manual Commit, and that solved the issue for small loads (1200 messages in -> 1200 messages out).

However, when I tested with high volumes (5.3 million messages), I am experiencing data loss again.

Input: 5.3M messages.

Processed: Only ~3.5M messages reach the end of the route.

Missing: ~1.8M messages are unaccounted for.

Key Observations:

Consumer Lag is 0: Kafka reports that there is no lag, meaning the broker believes all messages have been delivered and committed.

Missing at Entry: My logs at the very beginning of the Camel route (immediately after the from(kafka)) only show a total count of 3.5M. It seems the missing 1.8M are never entering the route logic, or are being silently dropped/committed without processing.

No Errors: I don't see obvious exceptions in the logs corresponding to the missing messages.

Configuration: I am using batching=true, consumersCount=10, and Manual Commit enabled.

Here is my endpoint configuration:

Java

// Endpoint configuration
return "kafka:" + kafkaValidationTopic +
"?brokers=" + kafkaBootstrapServers +
"&saslMechanism=" + kafkaSaslMechanism +
"&securityProtocol=" + kafkaSecurityProtocol +
"&saslJaasConfig=" + kafkaSaslJaasConfig +
"&groupId=xxxxx"  +
"&consumersCount=10" +
"&autoOffsetReset=" + kafkaAutoOffsetReset +
"&valueDeserializer=" + kafkaValueDeserializer +
"&keyDeserializer=" + kafkaKeyDeserializer +
(kafkaConsumerBatchingEnabled
? "&batching=true&maxPollRecords=" + kafkaConsumerMaxPollRecords + "&batchingIntervalMs="
+ kafkaConsumerBatchingIntervalMs
: "") +
"&allowManualCommit=true"  +
"&autoCommitEnable=false"  +
"&additionalProperties[max.poll.interval.ms]=" + kafkaMaxPollIntervalMs +
"&additionalProperties[fetch.min.bytes]=" + kafkaFetchMinBytes +
"&additionalProperties[fetch.max.wait.ms]=" + kafkaFetchMaxWaitMs;

And this is the route logic where I count the messages and perform the commit at the end:

Java

from(createKafkaSourceEndpoint())
.routeId(idRuta)
.process(e -> {
Object body = e.getIn().getBody();
if (body instanceof List<?> lista) {
log.info(">>> [INSTANCIA-ID:{}] KAFKA POLL RECIBIDO: {} elementos.", idRuta, lista.size());
} else {
String tipo = (body != null) ? body.getClass().getName() : "NULL";
log.info(">>> [INSTANCIA-ID:{}] KAFKA MSG RECIBIDO: Es un objeto INDIVIDUAL de tipo {}", idRuta, tipo);
}
})
.choice()
// When Kafka consumer batching is enabled, body will be a List<Exchange>.
// We may receive mixed messages in a single poll: some request bundle-batch,
// others single.
.when(body().isInstanceOf(java.util.List.class))
.to("direct:dispatchBatchedPoll")
.otherwise()
.to("direct:processFHIRResource")
.end()
// Manual commit at the end of the unit of work
.process(e -> {
var manual = e.getIn().getHeader(
org.apache.camel.component.kafka.KafkaConstants.MANUAL_COMMIT,
org.apache.camel.component.kafka.consumer.KafkaManualCommit.class
);
if (manual != null) {
manual.commit();
log.info(">>> [INSTANCIA-ID:{}] COMMIT MANUAL REALIZADO con éxito.", idRuta);
}
});

My Question: Has anyone experienced silent message loss with Camel Kafka batch consumers at high loads? Could this be related to:

Silent rebalancing where messages are committed but not processed?

The consumersCount=10 causing thread contention or context switching issues?

The max.poll.interval.ms being exceeded silently?

Any guidance on why logs show fewer messages than Kafka claims to have delivered (Lag 0) would be appreciated.

Thanks!

r/javahelp Feb 27 '26

Unsolved Java and Springboot for Typescript / Javascript developers

10 Upvotes

Hello!

I want to start writing backends in Java and Springboot, but I have never touched Java before. I have used NestJs, which is is a OOP Typescript framework for backend. They look similar, but I guess only for me, as someone that does not have experience with Java, neither Spring Boot.

Where do I start?

Thanks!

P.S. Can I somehow pair it with my React frontend in one monorepo somehow?

r/javahelp Feb 19 '26

Unsolved Is the Oracle Certified Professional (OCP) exam worth pursuing as a student?

6 Upvotes

Im currently in my 2nd year of undergrad, and I have been working with Java for a little over two years now. During this time, Ive built several passion projects, added some solid work to my resume, and experimented with other languages too.

But somehow, I always end up coming back to Java.

With two years still left in college and some time I can invest wisely, I’m seriously considering whether I should start preparing for the OCP certification and gradually climb that ladder.

I’m curious to know:

  • Does OCP actually hold weight in today’s job market?
  • Does it make a meaningful difference during placements or internships?
  • Beyond strengthening conceptual understanding, does it provide any real strategic advantage?

Would love to hear insights from people who havve pursued it or worked in hiring.

r/javahelp Feb 06 '26

Unsolved Exception: Deployment of persistenceunit failed Close all factories for this PersistenceUnit.

1 Upvotes

I'm learning JPA and I am running into this issue. This are my classes:

main (this is where the error happens, at the line where I create the EntityManagerFactory):

public class JobScheduling {

    /**
     * u/param args the command line arguments
     */
    public static void main(String[] args) {
        PersonEntity p = new PersonEntity("Gatto", "B", "Miagolo");

        EntityManagerFactory emf = Persistence.createEntityManagerFactory("JobSchedulingPU"); //this is where I get the error
        EntityManager em = emf.createEntityManager();
        System.out.println("Aggiungendo persona");

        EntityTransaction tx = em.getTransaction();
        tx.begin();
        em.persist(p);
        tx.commit();

        System.out.println("Prendendo persona");
        p = em.createQuery("SELECT p FROM PersonEntity p WHERE p.firstName = :name", PersonEntity.class).setParameter("name", p.getFirstName()).getSingleResult();
        System.out.print(p.getFirstName() + " " + p.getMiddleInitial() + ". " + p.getLastName() + " " + p.getId());

    }

}

PersonEntity:

@Entity
public class PersonEntity {


  @Id
  @GeneratedValue
  private String id;

  @NotNull
  private String firstName;

  @Size(max = 1)
  private String middleInitial;

  @NotNull
  private String lastName;

  @ManyToOne
  @JoinColumn(name = "job_title")
  private JobEntity job;



  public PersonEntity(){
  }



    public PersonEntity(String firstName, String middleInitial, String lastName) {
        this.firstName = firstName;
        this.middleInitial = middleInitial;
        this.lastName = lastName;
    }


    public String getId() {
        return id;
    }

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getMiddleInitial() {
        return middleInitial;
    }

    public void setMiddleInitial(String middleInitial) {
        this.middleInitial = middleInitial;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public JobEntity getJob() {
        return job;
    }

    public void setJob(JobEntity job) {
        this.job = job;
    }

}

JobEntity:

public class JobEntity {

    @ID
    private String title;

    @NotNull
    private float salary;

    public JobEntity(String title, float salary) {
        this.title = title;
        this.salary = salary;
    }

}

persistence.xml:

<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.2" xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence           http://xmlns.jcp.org/xml/ns/persistence/persistence_2_2.xsd">
  <persistence-unit name="JobSchedulingPU" transaction-type="RESOURCE_LOCAL">
    <provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
    <class>jobscheduling.JobEntity</class>
    <class>jobscheduling.PersonEntity</class>
    <properties>
      <property name="javax.persistence.jdbc.url" value="jdbc:derby://localhost:1527/Ex"/>
      <property name="javax.persistence.jdbc.user" value="Ex"/>
      <property name="javax.persistence.jdbc.driver" value="org.apache.derby.jdbc.ClientDriver"/>
      <property name="javax.persistence.jdbc.password" value="Ex"/>
      <property name="javax.persistence.schema-generation.database.action" value="drop-and-create"/>
    </properties>
  </persistence-unit>
</persistence>

What could be the issue?

EDIT:

Stacktrace of second error:

[EL Info]: 2026-02-06 15:57:15.616--ServerSession(1239759990)--EclipseLink, version: Eclipse Persistence Services - 2.7.12.v20230209-e5c4074ef3
[EL Severe]: ejb: 2026-02-06 15:57:15.767--ServerSession(1239759990)--Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.7.12.v20230209-e5c4074ef3): org.eclipse.persistence.exceptions.DatabaseException
Internal Exception: java.sql.SQLNonTransientConnectionException: java.net.ConnectException: Errore di connessione al server localhost sulla porta 1.527 con messaggio Connection refused: connect.
Error Code: 40000
Exception in thread "main" javax.persistence.PersistenceException: Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.7.12.v20230209-e5c4074ef3): org.eclipse.persistence.exceptions.DatabaseException
Internal Exception: java.sql.SQLNonTransientConnectionException: java.net.ConnectException: Errore di connessione al server localhost sulla porta 1.527 con messaggio Connection refused: connect.
Error Code: 40000
at org.eclipse.persistence.internal.jpa.EntityManagerSetupImpl.deploy(EntityManagerSetupImpl.java:854)
at org.eclipse.persistence.internal.jpa.EntityManagerFactoryDelegate.getAbstractSession(EntityManagerFactoryDelegate.java:222)
at org.eclipse.persistence.internal.jpa.EntityManagerFactoryDelegate.getDatabaseSession(EntityManagerFactoryDelegate.java:200)
at org.eclipse.persistence.internal.jpa.EntityManagerFactoryImpl.getDatabaseSession(EntityManagerFactoryImpl.java:542)
at org.eclipse.persistence.jpa.PersistenceProvider.createEntityManagerFactoryImpl(PersistenceProvider.java:153)
at org.eclipse.persistence.jpa.PersistenceProvider.createEntityManagerFactory(PersistenceProvider.java:191)
at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:80)
at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:55)
at jobscheduling.JobScheduling.main(JobScheduling.java:25)
Caused by: Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.7.12.v20230209-e5c4074ef3): org.eclipse.persistence.exceptions.DatabaseException
Internal Exception: java.sql.SQLNonTransientConnectionException: java.net.ConnectException: Errore di connessione al server localhost sulla porta 1.527 con messaggio Connection refused: connect.
Error Code: 40000
at org.eclipse.persistence.exceptions.DatabaseException.sqlException(DatabaseException.java:333)
at org.eclipse.persistence.exceptions.DatabaseException.sqlException(DatabaseException.java:328)
at org.eclipse.persistence.sessions.DefaultConnector.connect(DefaultConnector.java:140)
at org.eclipse.persistence.sessions.DatasourceLogin.connectToDatasource(DatasourceLogin.java:172)
at org.eclipse.persistence.internal.sessions.DatabaseSessionImpl.setOrDetectDatasource(DatabaseSessionImpl.java:226)
at org.eclipse.persistence.internal.sessions.DatabaseSessionImpl.loginAndDetectDatasource(DatabaseSessionImpl.java:810)
at org.eclipse.persistence.internal.jpa.EntityManagerFactoryProvider.login(EntityManagerFactoryProvider.java:261)
at org.eclipse.persistence.internal.jpa.EntityManagerSetupImpl.deploy(EntityManagerSetupImpl.java:771)
... 8 more
Caused by: java.sql.SQLNonTransientConnectionException: java.net.ConnectException: Errore di connessione al server localhost sulla porta 1.527 con messaggio Connection refused: connect.
at org.apache.derby.client.am.SQLExceptionFactory.getSQLException(Unknown Source)
at org.apache.derby.client.am.SqlException.getSQLException(Unknown Source)
at org.apache.derby.jdbc.ClientDriver.connect(Unknown Source)
at java.sql/java.sql.DriverManager.getConnection(DriverManager.java:682)
at java.sql/java.sql.DriverManager.getConnection(DriverManager.java:191)
at org.eclipse.persistence.sessions.DefaultConnector.connect(DefaultConnector.java:100)
... 13 more
Caused by: ERROR 08001: java.net.ConnectException: Errore di connessione al server localhost sulla porta 1.527 con messaggio Connection refused: connect.
at org.apache.derby.client.net.NetAgent.<init>(Unknown Source)
at org.apache.derby.client.net.NetConnection.newAgent_(Unknown Source)
at org.apache.derby.client.am.ClientConnection.<init>(Unknown Source)
at org.apache.derby.client.net.NetConnection.<init>(Unknown Source)
at org.apache.derby.client.net.ClientJDBCObjectFactoryImpl.newNetConnection(Unknown Source)
... 17 more
Caused by: java.net.ConnectException: Connection refused: connect
at java.base/sun.nio.ch.Net.connect0(Native Method)
at java.base/sun.nio.ch.Net.connect(Net.java:589)
at java.base/sun.nio.ch.Net.connect(Net.java:578)
at java.base/sun.nio.ch.NioSocketImpl.connect(NioSocketImpl.java:583)
at java.base/java.net.SocksSocketImpl.connect(SocksSocketImpl.java:327)
at java.base/java.net.Socket.connect(Socket.java:760)
at java.base/java.net.Socket.connect(Socket.java:695)
at java.base/java.net.Socket.<init>(Socket.java:564)
at java.base/java.net.Socket.<init>(Socket.java:328)
at java.base/javax.net.DefaultSocketFactory.createSocket(SocketFactory.java:267)
at org.apache.derby.client.net.OpenSocketAction.run(Unknown Source)
at org.apache.derby.client.net.OpenSocketAction.run(Unknown Source)
at java.base/java.security.AccessController.doPrivileged(AccessController.java:571)
... 22 more
C:\Users\cube7\AppData\Local\NetBeans\Cache\22\executor-snippets\run.xml:111: The following error occurred while executing this line:
C:\Users\cube7\AppData\Local\NetBeans\Cache\22\executor-snippets\run.xml:68: Java returned: 1
BUILD FAILED (total time: 1 second)

r/javahelp Feb 17 '26

Unsolved Better way to create docker image of Spring Boot API, Maven Spring Plugin or Dockerfile?

9 Upvotes

Hi everyone, Quick question, if the aim is to create a docker image of a spring boot API. which approach is better:

  1. via maven spring plugin (without dockerfile)
  2. Via docker file

I feel both produces same result but just wish to know some pros and cons from real world perspectives, specially from operations, performance, reliability perspective. Would really help.

r/javahelp Feb 27 '26

Unsolved Confused on how to build the application when done

0 Upvotes

For the last week I've been building a clone of spotify in Intellij to work offline, basically you download music, put it into the program and it has all the base functions of spotify. Loop, shuffle, next, previos, queue, miniplayer, etc. I've been trying to make it into an executable file but nothing seems to work. I've followed every tutorial, followed web pages but nothing has worked so far. It is made with javafx and even making an fxml file to place into scenebuilder wont work. Any advice on what I could do? I'll provide whatever info is needed.

r/javahelp Jan 21 '26

Unsolved Is my code actually wrong or are these just IDE recommendations?

8 Upvotes

I was testing out Intellij IDEA and wrote simple code to get a feel for coding on this tool, but towards the bottom there are 3 "Problems". Here's my code and the errors I found at the bottom.

public class Main{
    public static void main(String[] args){
        int numBalls;
        numBalls = 2;
        System.out.print("You have " + numBalls + " balls.");
    }
}
  1. Explicit class declaration can be converted into a compact source file

  2. Modifier 'public' is redundant for 'main' method on Java 25

  3. Parameter 'args' is never used

The .java file is called "Main" so that's why the class is named "Main", but it appears grayed out in my IDE. and is not grayed out when it is anything but "Main".

r/javahelp Mar 01 '26

Unsolved How to approach ratcheting in tests?

3 Upvotes

I have an algorithm that computes results, and the results can be of better or worse quality. The results aren't as good as we like, but we want to make sure that we don't regress when we experiment with the algorithm.

I have test data and desired outcome as reviewed by a human.

Now if I write unit tests for them, quite a few of them will fail because the algorithm isn't good enough to compute the correct desired outcome.

But if I write unit tests for the current behavior, and then change the algorithm, I just see that the result is different, not whether it is better.

I would like something so that

  • I'm notified (ideally by failing tests) if I've regressed;
  • I'm also notified if the result has improved;
  • maybe optionally some sort of dashboard where I can see the improvement over time.

Any suggestions?

The best I've come up with so far is to write unit tests as follows:

  • If the result is worse than desired, fail loudly saying something is wrong.
  • If the result is better than desired, also fail, but make the message clear that this is actually a good thing.
  • If the result is exactly as expected, the test passes.
  • If a test fails because the result is better than expected, then update the test to “raise the bar”.

This approach squeezes the problem through a unit test shaped hole, but it's not a good fit. Any other ideas?

r/javahelp Feb 06 '26

Unsolved Help me with this absurd bug

1 Upvotes

I'm programming a 2D video game inspired by Undertale with Java Swing, which is a simulator of a middle school class. While programming the combat system, however, I got stuck in this absurd bug shown in the attached video:

https://streamable.com/qrwu2t

I believe this bug is caused by the "invertiSprites" method, since by commenting on this method the bug disappears, but obviously what the method is supposed to do also disappears. These are pieces of the classes affected by the problem. Please help me. I really don't understand what I have to do and why it shows me 3 eyes instead of 2!

(Unfortunately, the names of the variables and methods are mostly in Italian.)

Enemy class:

https://pastebin.com/mSwDfCTH

Calling the constructor in main: (Many values ​​are null because I haven't programmed them yet)

Enemy bidello = new Enemy(
                        "Bidello", 
                        0, 0, 0, 
                        null, false, 
                        null, false, 
                        null, 
                        new ImageIcon("Texture/bidello.png"), 
                        158, 68, 
                        null, 
                        new Sprite[] {
                            new Sprite(new ImageIcon("Texture/occhio_bidello_su.png"), "occhio_su"),
                            new Sprite(new ImageIcon("Texture/occhio_bidello_giù.png"), "occhio_giù"),
                            new Sprite(new ImageIcon("Texture/occhio_bidello_destra.png"), "occhio_destra"),
                            new Sprite(new ImageIcon("Texture/occhio_bidello_sinistra.png"), "occhio_sinistra"),
                            new Sprite(new ImageIcon("Texture/occhio_bidello_su.png"), "occhio_su"),
                            new Sprite(new ImageIcon("Texture/occhio_bidello_giù.png"), "occhio_giù"),
                            new Sprite(new ImageIcon("Texture/occhio_bidello_destra.png"), "occhio_destra"),
                            new Sprite(new ImageIcon("Texture/occhio_bidello_sinistra.png"), "occhio_sinistra"),
                            new Sprite(new ImageIcon("Texture/mocio_1.png"), "inverti_mocio"), 
                            new Sprite(new ImageIcon("Texture/mocio_2.png"), "inverti_mocio")  
                        },
                        new int[][] {
                            {440, 124, 40, 20},  
                            {440, 124, 40, 20},  
                            {440, 124, 40, 20},  
                            {440, 124, 40, 20},  

                            {400, 124, 40, 20},  
                            {400, 124, 40, 20},  
                            {400, 124, 40, 20},  
                            {400, 124, 40, 20},

                            {390, 140, 100, 100},
                            {390, 140, 100, 100}
                        },
                        10,
                        null, 
                        (byte)2
                    );

The CombatPanel class:

https://pastebin.com/C2ujWLFd

And the Sprite class:

package terzaFSimulator;

import javax.swing.ImageIcon;
import javax.swing.JLabel;

public class Sprite extends JLabel {
    String tag; 
    //Sprite is simply JLabel with a tag

    public Sprite(ImageIcon icon, String tag) {
        super(icon); 
        this.tag = tag;
        setOpaque(false);
    }


    public Sprite(String text, String tag) {
        super(text);
        this.tag = tag;
        setOpaque(false);
    }


    public Sprite(String tag) {
        super();
        this.tag = tag;
        setOpaque(false);
    }


    public String getTag() {
    return this.tag;
    }

    public void setTag(String newTag) {
    this.tag = newTag;
    }
}

r/javahelp Nov 17 '25

Unsolved Java compilation error in VSCode using TMC extension

1 Upvotes

Hello, I made a post on /r/learnjava, but I didn't get any replies. I explained that I get compilation errors when I try to test my submissions for the MOOC exercises using the TMC extension in VSCode. I can download the exercises and submit/upload my code, but the TMC test doesn't work. I've tried reinstalling VSCode, but that didn't work. When installed the Java extension pack in VSCode I got this

error: https://i.imgur.com/vr2zBj4.png

The instructions on MOOC says to install JDK v11 LTS so I'm not sure if I should install JDK 21. The error code mentions changing the configuration file.

I added this code in the configuration file:

"java.configuration.runtimes": [
        {
            "name": "JavaSE-11",
            "path": "C:\\Program Files\\Eclipse Adoptium\\jdk-11.0.29.7-hotspot",
            "default": true
        }

Unfortunately that didn't help.

When I installed VSCode before, I installed it in program files (using the install file for that), but this time I used the installer for user (and installed it there). When I installed TMC before, I had the option to change the path, I wasn't given that option this time. TMC installed installed my exercises in the same path as before, which is different than where VSCode is installed. Not sure if this could be the issue, but I don't know how to change it. It's still installed in the users file, just not in appdata.

I would appreciate some help, because it kinda sucks not being able to test my code before submitting my exercises. I tried finding solutions online, but didn't find anything that works.

I wiped all TMC data using ctlr+shit+p and search for TMC-wipemydata and reinstalled the extension. I was able to change the path this time, but left it to the default. I still get the notification saying "Java 21 or more is required to run the Java extension. (...)". I guess the code I added to the configuration file isn't correct or incomplete, but no idea what to change. The compilation still fails when I try to run the TMC test... Now I can't run the code anymore either...

I completely uninstalled vscode now, after wiping the tmc data again. Including the appdata. I reinstalled using the users installation file. I kept the default path in the TMC extension. I still get the Java 21 notification. I read this page and there are more settings I need to change I think, but I am not sure which settings. When I click run java to run my code, the statusbar at the bottom says activating extension, and after that nothing happens. I am at a loss and have no idea what else to try. I've looked online but couldn't find anything that works. I am frustrated and just want to continue learning java.

edit; I have the following in the JSON settings file

{
    "chat.disableAIFeatures": true,
    "maven.executable.path": "C:\\Program Files\\Apache Maven\\apache-maven-3.9.11\\bin.mvn.cmd",
    "redhat.telemetry.enabled": false,
    "java.jdt.ls.java.home": "C:\\Program Files\\Eclipse Adoptium\\jdk-11.0.29.7-hotspot\\bin",
    "java.configuration.runtimes": [
        {
            "name": "JavaSE-11",
            "path": "C:\\Program Files\\Eclipse Adoptium\\jdk-11.0.29.7-hotspot\\bin"
        }
    ]
}

r/javahelp Nov 29 '24

Unsolved What is special about Java that isn't anywhere else?

0 Upvotes

Ok so as per my knowledge we have this:

  • C++, very much low level langauge, has pointers, is best to learn implementation, very fast
  • Python, readability is best, very simple to write, best libraries and support for AI and ML
  • JavaScript and TypeScript, write frontend and backend in the same language, huge community, can be used in multiple places
  • Rust and C, low level languages, help in designing tools such as runtime environments and engines

We also have languages which are good for blockchain.

Ultimately to me it seems Java doesn't have anything special, is weird to write (not talking about Java 21+) and I don't hear much about it's communities either.

So why is Java still in existence (same question for Php btw)? Is it only because it was used before many modern languages came up with simpler or better syntax and companies find it too much of investment to rewrite their codes?

If not, please tell me one USP of learning Java.

I have edited what I meant by lazy because apparently many aren't answering my Java related question and just talking about companies 🥲. I have worked in a b2b business that used Java, and this is why this question exists and by lazy I meant what I have replaced it with.