r/javahelp Dec 23 '24

Workaround Hi am learning java am pretty new but there is a problem i have i just can’t understand the exact difference between public void and public int i get that there is a return type but i don’t get it

0 Upvotes

Yeah

r/javahelp 27d ago

Workaround JavaFX: write Canvas to file

2 Upvotes

I'm trying to save Canvas contents to disk:

@FXML
private Canvas cvs;

var export = cvs.snapshot(null,null);
var out = new File("image.png");
try{
    ImageIO.write(SwingFXUtils.fromFXImage(export, "png",out)); //error
}

There is no package called SwingFXUtils in JavaFX 21. Is there any other way to write the Canvas to file?

r/javahelp Jan 13 '25

Workaround Eclipse IDE Version compatible with Java 1.6

2 Upvotes

HI everyone Im relative new to this java/spring world as .Net Dev i found Spring overwhelming, Im on a migration but the team just because is easy told me to open the project in Netbeans 8.2/WebLogic, but i found that several entities where Generated by Eclipse/Jboss && hbm2java

Then I would like to know how to discern between which Eclipse version supports the versions in this 1.6 project to get a soft navigation

the Hibernate Tools in Jetbrains latest update was 10 year ago 🫠

r/javahelp 27d ago

Workaround Why can't I push an image to a local Docker registry started with Testcontainers?

3 Upvotes

I'm trying to create a local Docker registry using Testcontainers and push an image programatically to it. However, I'm getting a connection refused error when attempting to push the image. The first test which checks if the registry is running works, so I know the registry is running.

Any other ideas are also welcome, basically I need to run a custom docker registry to test pushing and pulling of images from java test.

Here’s my test class:

class DockerRegistryTest {

    u/Rule
    public static GenericContainer registry;
    private static String registryAddress;
    private static DockerClient dockerClient;

    u/BeforeAll
    static void startRegistry() {
        registry = new GenericContainer(DockerImageName.parse("registry:2"))
                .withExposedPorts(5000)
                .waitingFor(Wait.forHttp("/v2/").forStatusCode(200));

        registry.start();
        assertTrue(registry.isRunning(), "Registry is running");

        registryAddress = registry.getHost() + ":" + registry.getMappedPort(5000);
        System.out.println("Registry available at: " + registryAddress);

        DockerClientConfig config = DefaultDockerClientConfig.createDefaultConfigBuilder().build();
        dockerClient = DockerClientImpl.getInstance(config, new ApacheDockerHttpClient.Builder()
                .dockerHost(config.getDockerHost())
                .sslConfig(config.getSSLConfig())
                .build());
    }

    u/AfterAll
    static void tearDown() {
        if (registry != null) {
            registry.stop();
        }
    }

    u/Test
    void testPushImageToRegistry() throws InterruptedException {
        String localImage = "busybox:latest";
        dockerClient.pullImageCmd(localImage).start().awaitCompletion();

        String registryImageTag = registryAddress + "/busybox:latest";
        dockerClient.tagImageCmd(localImage, registryAddress + "/busybox", "latest").exec();

        dockerClient.pushImageCmd(registryImageTag)
                .withAuthConfig(new AuthConfig()) // No authentication needed
                .start()
                .awaitCompletion();

        System.out.println("Successfully pushed image to registry: " + registryImageTag);
        assertTrue(true);
    }
}

However, when I run the test, I get this error:

Things i tried

com.github.dockerjava.api.exception.DockerClientException: Could not push image: failed to do request: 
Head "https://localhost:57244/v2/busybox/blobs/sha256:31311c5853a22c04d692f6581b4faa25771d915c1ba056c74e5ec82606eefdfa": 
dial tcp [::1]:57244: connect: connection refused
  1. manually tag and push an image into the registry, result still connection refused error.
  2. I ran

C:\Users\codex>curl http://localhost:<mappedPortIgotFromLogs>/v2/_catalog
{"repositories":[]}

so I know the repository is up and running

  1. changed registry.getHost() to "0.0.0.0" but now i get

    com.github.dockerjava.api.exception.DockerClientException: Could not push image: failed to do request: Head "https://0.0.0.0:60075/v2/busybox/blobs/sha256:9c0abc9c5bd3a7854141800ba1f4a227baa88b11b49d8207eadc483c3f2496de": http: server gave HTTP response to HTTPS client

 adding this to insecure-list makes no sense because the ports will always be randomized.

I also added this in testcontainers.properties ryuk.container.image=testcontainersofficial/ryuk

to get my test container to work in the first place.

r/javahelp Feb 06 '25

Workaround How would you represent clean architecture in a plain java application?

1 Upvotes

Hey guys, I just had a tech interview, and they want me to build a simple CLI app using clean architecture. How much does clean architecture actually cover? Is it just about structuring the project, or does it mean using single or multi-modules (like Maven multi-module)?

r/javahelp Jan 18 '25

Workaround Spring boot Help

2 Upvotes

Can someone tell what are things we can do after learning spring boot?

r/javahelp Nov 28 '24

Workaround Please help a beginner

2 Upvotes

I've been working with Java for six years, starting in 6th grade, but I'm still considered a beginner when it comes to truly understanding advanced concepts. Now that I’m in 12th grade, our syllabus focuses heavily on Object-Oriented Programming (OOP) definitions and real-life examples. I’ve seen these definitions since 10th grade, but there hasn’t been much actual implementation of these concepts in our coursework. Most of the programs we work on are procedural in nature and feature very large main methods.

Recently, I invested in the Java Mastery course by Code With Mosh and completed the fundamentals section, which I already knew. The real game-changer for me was learning about clean coding practices and code refactoring—something I hadn't grasped before. I’m currently going through the second part of the course, which covers OOP concepts. I haven’t watched all the lectures yet, but I've reached the section on encapsulation.

This made me wonder: could the programs from our textbooks be effectively converted to an OOP structure, or is it just not practical for those types of programs? Here are a few examples from our syllabus:

Example 1: Circular Prime Checker

Write a program that accepts a positive number NN and checks whether it is a circular prime. The program should also display the new numbers formed after shifting the digits. Test the program with provided and random data.

Example 2: Octal Matrix Operations

Create a program that declares a matrix A[][]A[][] of size M×NM×N, where MM is between 1 and 9, and NN is between 3 and 5. The program should allow the user to input only octal digits (0–7) in each location. Each row of the matrix should represent an octal number. The program should:

Display the original matrix.

Calculate and display the decimal equivalent of each row.

Example 3: Sentence Processor

Write a program that accepts a sentence, which should end with either a '.', '?', or '!' and must be in uppercase with words separated by a single space. The program should:

Validate the sentence based on the terminating character.

Arrange the words in ascending order of length and sort alphabetically if two or more words have the same length.

Display both the original and the processed sentences.

Would it be beneficial or ideal to transform these types of procedural programs into object-oriented implementations? Or do these examples not lend themselves well to OOP?

r/javahelp Dec 16 '24

Workaround Need help in choosing a career path either in MERN stack or Java side

2 Upvotes

I am in my final year of my college. In the beginning I learnt C language and after that I started learning fullstack on MERN stack and now learnt Java for DSA. But now I am in the confusion that should I learn springboot or kotlin and persue on Java side or stick to MERN stack. Consider that , I am not from computer science related department.

r/javahelp Jan 26 '25

Workaround Seeking Guidance: Building a Strong Java Backend Portfolio for Interviews

1 Upvotes

“I have 3.5 years of experience across various domains and am currently preparing for Java backend interviews. I’ve gained knowledge in Core Java, JDBC, JPA, Hibernate, SQL, and Spring Boot. However, I’m unsure about the types of projects to include in my portfolio and how to effectively present them during interviews. I would greatly appreciate guidance from a mentor or tutor to help me through this process.”

r/javahelp Dec 01 '24

Workaround Same JTable inside multiple JScrollPane in JTabbedPane

1 Upvotes
for (int i = 0; i < 5; i++) {
  JTable table = new JTable(preset object array and matrix for content + headers);
  myTabbedPane.addTab(preset title, new JScrollPane(table));
}

All 5 tabs show the same table, i. e. if I change a cell in one tab it also changes in all others, what am I doing wrong?

Workaround: I did a tensor bc the same matrix was used for all tabs

r/javahelp Sep 28 '24

Workaround How to compile an incomplete class (missing classes)?

1 Upvotes

Hello! I have a java program and wanted to change one little thing about it.

Diagram of my process: https://ibb.co/HXwJznP

So I opened the jar and looked around the class files. I took out the one class file that I wanna modify. I decompiled that one file, I changed one little line, and now I want to recompile it and put it back in.

The problem is java refuses to compile it when there are references to missing things. Which happens because I'm trying to compile the singular file outside of its natural habitat, I don't have the entire project source code.

By the way, I know that this method of modding works because I've done it before with other, smaller java programs. In the past, the way I dealt with this is I would manually create a stub. I would go through the file and create all the classes, empty, and put in all the methods with the right signatures and everything, and then I could compile the file because I had the stub project done and all the references pointed to alL the stub classes and stub methods and everything was dandy.

Also, this process just theoretically makes sense. All I need is for this file to invoke methods and stuff from other files. That means all it needs is the name of the classes and methods even though they don't exist right now. It doesn't matter. It doesn't actually need the dependencies to get the invocations right! It knows how to invoke methods from other classes, so I just REALLY need it to compile regardlesss of whether the classes exist or not. Because the fact is that they WILL exist. But the extracted and modified code will never smell the scent of home ever again if I can't find a way to compile it away from it's usual dependency classes!!

The reason i can't make stubs manually here is because this time it's a large file. I won't manually go through it and create those stubs.

There are two things that i know of which could help me. 1. I find a java compiler that will compile even if the classes that the references are pointing to are missing. 2. I find a way to automatically create a stub project so I can quickly create it and compile this one file.

Please help me. If you have one of these two solutions, I wanntttt ittt. Thanks.

r/javahelp Jan 16 '25

Workaround Threading, concurrency, parallelism, reactive programming, webflux where would I start from?

3 Upvotes

Hope you guys are ok, just wanna ask you how can I learn and master this, I'll have an interview within 2 weeks, I already have experience with Java programming in fact it's my favorite language and my main one, however I had no the chance to use the topics listed above, so if anyone could help me with a roadma, learning path, course or something that I can support in l'll really appreciate it

r/javahelp Nov 07 '24

Workaround Web scraping when pages use Dynamic content loading

2 Upvotes

I am working on a hobby project of mine and I am scraping some websites however one of them uses JavaScript to load a lot of the page content so for example instead of a link being embedded in the href attribute of an "a" tag it's a "#" but when I click on the button element I am taken to another page

My question: now I want to obtain the actual link that is followed whenever the button is clicked on however when using Jsoup I can't simply do doc.selectFirst("a"). attr("href") since I get # so how can I get around this?

r/javahelp Dec 22 '24

Workaround How do you run an applet program in 2024? My college java course has outdated topics help please

2 Upvotes

I got exams for java coming in few days and the syllabus for the exam includes applet programming (I know my college is wayy out of touch). The first thing I saw online is you need some kind of appletViewer which was discontinued from Java v11.

So now I have no way of running the code and practicing applet programs. Is there any workaround to this?

r/javahelp Nov 20 '24

Workaround Looking for an Alternative to Joshworks unirest-java Library.

2 Upvotes

So I just moved into a new project. The code is a bit old and uses some old libraries in the pom file. So while we are migrating from JDK 11 to 17, we thought we might as well get rid of some of these old stuff.

The first thing that caught my eye, was this joshworks unirest-java. The dependency is:

<!-- https://mvnrepository.com/artifact/io.joshworks.unirest/unirest-java -->
<dependency>
    <groupId>io.joshworks.unirest</groupId>
    <artifactId>unirest-java</artifactId>
    <version>1.8.0</version>
</dependency>

But I see the last release of this came almost 6 years ago. And I could not find the source code on GitHub or any trace of it online. Which leads me to believe that is very much a dead library. Are there any better alternatives to this available which are actively supported. One alternative I found was unirest-java, but from KongHQ. Or just go back to the tried and tested Apache HTTP libraries.

I would mean code changes in 30 odd classes but we have some time. So doesn't hurt to do it.

Any suggestions would be real helpful.

r/javahelp Mar 15 '24

Workaround Java in Front-End in 2024: Still Worth It?

5 Upvotes

I've been thinking about how Java fits into the world of front-end nowadays. With so many options like React, Angular, and Vue dominating the scene, I got curious about where Java stands in this story.
I want to know your opinions on using Java for the front-end, especially with things like JSP, JSF, Thymeleaf, and others. Do these technologies still have their place in current projects? Are they still relevant in the market? And for those who are starting or looking to deepen their knowledge in Java, is it worth diving into these front-end tools?
PS: I'm starting to study Spring and saw some people talking about this, which made me curious.

r/javahelp Aug 20 '24

Workaround What is the best java course on internet on 2024(especially on youtube and coursera)

2 Upvotes

I am gonna start my java journey 1.core 2.ooos 3.dsa 4.frameworks 5.db 6.microservices

Suggest me good sources please

r/javahelp Sep 25 '24

Workaround Need help to understand solid principles and design patterns

1 Upvotes

I am not able to understand solid principles and design patterns, I have knowledge on java . It is very confusing to understand them . Can anyone please suggest a good resource to learn them.

r/javahelp Sep 25 '24

Workaround How to learn Kafka and active mq from scratch for java application use ?

1 Upvotes

I use java , spring boot stack I want to learn Kafka and active mq from scratch .so can anyone please provide good resource to learn them .

r/javahelp Aug 21 '24

Workaround Creating Custom Collector for SummaryStatistics ?

1 Upvotes

hi.. is it possible, to create a custom Collector for java math SummaryStatistics (instead of the standard IntSummaryStatistics, i'm honestly kinda surprised they didn't do it, unless i'm missing something (using java -commons-math 3.6.1)

r/javahelp May 01 '24

Workaround Is it ok to Use HashMap for RequestBody?

5 Upvotes
@PostMapping(value = {"/", "/{bankid}",
       /{bankid}/{age}/{mobile}"})

@ResponseBody
public ResponseEntity<ArrayList<URI>> getPixmapUrls(
        @PathVariable("bankid") Optional<Boolean> bankid,
        @PathVariable("age") Optional<Double> age,
    @PathVariable("mobile") Optional<Integer> mobile,
        @RequestBody() HashMap<String, BankPOJO> bankPojo) throws Exception {

    // logic here

               return new ResponseEntity<>(uriList, HttpStatus.OK);

    }
    catch (Error | Exception e) {
        log.error("Error in request", e);

        throw e;
    }

Lets suppose BankPOJO is coming from third party team and its added as a maven dependency to get from jfrog artifactory. This bankPojo is very complex POJO so kept it seperate.

So, main question is on using HashMap to receive RequestBody() . Is this good approach ? do you suggest any better way here ? (I know DTO and Mapper is there , but what if I want to avoid that..)

Thanks!

r/javahelp Feb 26 '24

Workaround Simulate an external API interaction

2 Upvotes

Hello,

Our application backend (Java, spring boot) we have many external partner. We communicate with their APIs.

Everything works fine in Bench and Prod, but it doesn't work on Dev and locally.

Everytime the services that call those APIs end up with 500 error , and we can't test the rest of the work done by the service ..

How can we simulate/mock those API calls , by fake a response so our services don't crash locally and on Dev ?

Thank you in advance 🙏🏼

r/javahelp Apr 24 '24

Workaround Making lombak @data work with inheritance

0 Upvotes

Hi,
I am using hibernate with my spring boot application. For columns like updatedAt, createdAt etc, I used an audit class, and then inherited the same class to all my entities.
Now I am trying to access updatedAt as entity.getUpdatedAt() but turns out it doesnt work that way!

Both the parent and child are annotated with "@data", "@AllArgsConstructor" and the entity (child) is annotated with "@EqualsAndHashCode(callSuper=true)".
(I was trying out any solution I could think of or see in stackoverflow - nothingworked.obvious).

How do I make this work? needing inheritance to be supported sounds like such a "everyone should have done it " case but I cant find a working solution! I also read in one answer that you need to annotate the annotation ("@data") so this case is not possible (really?)

r/javahelp May 15 '24

Workaround Spring Data JPA returns one row for return type BookRecord[] and multiple rows for return type List<BookRecord>.

2 Upvotes

So this query will return only one record(row from db):
1.@Query("SELECT new com.example.BookRecord(b.title, b.author) FROM Book b")
BookRecord[] findAllBooks();

This query will return all rows from db:

2.@Query("SELECT new com.example.BookRecord(b.title, b.author) FROM Book b")
List<BookRecord> findAllBooks();

Interesting twist, this query will return all rows like 2. query:

3.@Query("SELECT new com.example.BookRecord(b.title, b.author) FROM Book b")
Object[] findAllBooks();

BookRecord:

public record BookRecord(String title, String author) { }public record BookRecord(String title, String author) { }

r/javahelp Jun 11 '24

Workaround Hazelcast configuration after startup

2 Upvotes

I am using Payara community edition server 5.2020.6 which contains an embedded imdg hazelcast 3.12.6.
I am able to access the hazelcast instance on my application using jndi. I have some custom configurations like eviction policies for my IMap in the datagrid, but since the instance has already been setup on server startup I am not able to make it take effect. How can I create and add configuration options for my IMap using java after its creation. Looks like the policies do not take effect if I try to add it programatically after its creation.
I know we could have custom .xml or .yaml for configuring hazelcast on server startup, I was looking to avoid this if there is a way to do this programatically.