Register a SA Forums Account here!
JOINING THE SA FORUMS WILL REMOVE THIS BIG AD, THE ANNOYING UNDERLINED ADS, AND STUPID INTERSTITIAL ADS!!!

You can: log in, read the tech support FAQ, or request your lost password. This dumb message (and those ads) will appear on every screen until you register! Get rid of this crap by registering your own SA Forums Account and joining roughly 150,000 Goons, for the one-time price of $9.95! We charge money because it costs us money per month for bills, and since we don't believe in showing ads to our users, we try to make the money back through forum registrations.
 
  • Post
  • Reply
i vomit kittens
Apr 25, 2019


Can someone help me with converting this bit of code from Python/Flask to Java/Spring Boot? It's for a chat bot that I'm porting over because I've found Spring Boot much easier to work with w/r/t databases and more complicated JSON objects.

I'm trying to POST an image to the GroupMe server so that it can be processed by them before being sent in the chat. I've got to the point of saving the image from the given URL in a BufferedImage object, but I'm unsure of what I need to do next. Can I just put the BufferedImage object into a POST request and expect Spring to figure it out for me, or do I need to save it as a file and reopen it like the example code below does?

code:
def uploadImage(imgUrl):
    imgRequest = requests.get(imgUrl, stream=True)
    filename = "temp.png"
    if imgRequest.status_code == 200:
        with open(filename, "wb") as image:
            for chunk in imgRequest:
                image.write(chunk)
        postUrl = "https://image.groupme.com/pictures"
        files = {"file": open(filename, "rb")}
        payload = {"access_token": "----------------------"}
        r = requests.post(postUrl, files=files, params=payload)
        processedUrl = r.json()['payload']['url']
        os.remove(filename)
        return processedUrl

Adbot
ADBOT LOVES YOU

Volguus
Mar 3, 2009

i vomit kittens posted:

Can someone help me with converting this bit of code from Python/Flask to Java/Spring Boot? It's for a chat bot that I'm porting over because I've found Spring Boot much easier to work with w/r/t databases and more complicated JSON objects.

I'm trying to POST an image to the GroupMe server so that it can be processed by them before being sent in the chat. I've got to the point of saving the image from the given URL in a BufferedImage object, but I'm unsure of what I need to do next. Can I just put the BufferedImage object into a POST request and expect Spring to figure it out for me, or do I need to save it as a file and reopen it like the example code below does?

code:
def uploadImage(imgUrl):
    imgRequest = requests.get(imgUrl, stream=True)
    filename = "temp.png"
    if imgRequest.status_code == 200:
        with open(filename, "wb") as image:
            for chunk in imgRequest:
                image.write(chunk)
        postUrl = "https://image.groupme.com/pictures"
        files = {"file": open(filename, "rb")}
        payload = {"access_token": "----------------------"}
        r = requests.post(postUrl, files=files, params=payload)
        processedUrl = r.json()['payload']['url']
        os.remove(filename)
        return processedUrl

You need a byte array to make the POST with (potentially converted to base64, but I think that the rest client API does that automatically. No sure on this, it's been a while).
Here's an article that explains it more in depth:
https://medium.com/tech-and-the-city/from-image-to-bytes-and-back-again-563abc5c1412

Significant info:

code:
BufferedImage image = ... your image ...
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
ImageIO.write(image, "png", outputStream);
byte[] bytes = outputStream.toByteArray();
//or to base64
String encodedImage = Base64.encode(outputStream.toByteArray());
And then send that as the post body.

Objective Action
Jun 10, 2007



i vomit kittens posted:

code:
        postUrl = "https://image.groupme.com/pictures"
        files = {"file": open(filename, "rb")}
        payload = {"access_token": "----------------------"}
        r = requests.post(postUrl, files=files, params=payload)

Its a little bit difficult to tell without testing it myself but looking at GroupMe's (poo poo) documentation for that endpoint just says it wants a binary payload in the body where I know requests.post(...file=blah...) usually does a multi-part form upload encoding.

Java has a million excellent web client libraries but given you are already in Spring Boot land the two quickest options are probably RestTemplate and the WebFlux WebClient. I prefer the latter's API myself but here are some examples that I believe should mimic what you have. (Note this is not the cleanest and least boiler-platy way to do this but is a complete example without any dependency injection or anything).

code:

byte[] imageBytes = //Volguus' example
String accessToken = //token

//RestTemplate style
MultiValueMap<String, Object> body = new LinkedMultiValueMap<>();
body.add("files", imageBytes);

HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.IMAGE_PNG);
headers.set("X-Access-Token", accessToken);
     
HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(body, headers);
 
String serverUrl = "https://image.groupme.com/pictures";
RestTemplate restTemplate = new RestTemplate();
ResponseEntity<String> response = restTemplate.postForEntity(serverUrl, requestEntity, String.class, accessToken);

//WebClient style
WebClient client = WebClient.builder()
        .baseUrl("https://image.groupme.com/")
        .defaultHeader(HttpHeaders.CONTENT_TYPE, MediaType.IMAGE_PNG)
	.defaultHeader("X-Access-Token", accessToken)
        .build();

client.post()
	  .uri("/pictures")
          .bodyValue(imageBytes)
          .retrieve()
//You can also just do String.class if you don't want to marshal an object or use exchange instead of retrieve to get things like response codes and have finer control over results
          .bodyToMono(GroupMeImageUploadResponse.class)
	  .subscribe(response -> //Do things with response);

Note these are from memory and might not even compile without some tweaking but should be pretty close I think.

ivantod
Mar 27, 2010

Mahalo, fuckers.

Objective Action posted:

Java has a million excellent web client libraries but given you are already in Spring Boot land the two quickest options are probably RestTemplate and the WebFlux WebClient.
Also since Java 11, there is actually a proper HttpClient included in the JDK itself, no need for external libraries.

Shy
Mar 20, 2010

Which JDK java developers use nowadays?
I see that Oracle offers an official JDK, talks something about licence change and links to OpenJDK, and then there are third party versions, so:
- is the difference meaningful to a developer?
- will your boss tell you which one to use?
- has the preference among developers/companies swung one way or the other?
- what is used by big companies and how do they deploy it?
I guess some questions may sound oblivious but I don't work with java and the op is old. Thanks.

Shy fucked around with this message at 17:03 on Feb 23, 2020

Keetron
Sep 26, 2008

Check out my enormous testicles in my TFLC log!

Shy posted:

Which JDK java developers use nowadays?
I see that Oracle offers an official JDK, talks something about licence change and links to OpenJDK, and then there are third party versions, so:
- is the difference meaningful to a developer?
- will your boss tell you which one to use?
- has the preference among developers/companies swung one way or the other?
- what is used by big companies and how do they deploy it?
I guess some questions may sound oblivious but I don't work with java and the op is old. Thanks.

- Nah, not really, they should be interchangeable in terms of code.
- sometimes yes but then this is mostly for compliance and licensing reasons
- I don't know, there must be a survey or something out there?
- whatever the devs want is what I often see.

Basically Oracle used to offer something for free that is now paid. Opensource and free alternatives are out there. I get the impression that most teams went with OpenJDK.

carry on then
Jul 10, 2010

by VideoGames

(and can't post for 10 years!)

One survey I've seen passed around shows OpenJDK on top with a 72% swing towards it from the year prior: https://snyk.io/wp-content/uploads/jvm_2020.pdf I would say right now, unless you know you have a reason (ie a license) to use Oracle you just go with OpenJDK. I'm not aware of any incompatibilities but I'm over in the J9-related ecosystem where it was already OpenJDK on top of the J9 VM so everyone was already using it.

CPColin
Sep 9, 2003

Big ol' smile.
Some of our lovely web applications require Java 7 still, so I had to switch to whatever the gently caress Zulu is in order to get some semblance of security updates. The more recent lovely apps support Java 8, so I've started moving servers to OpenJDK. At some point, I hope to have everything get some decent test coverage and crank up OpenJDK to whatever the latest version is. (lol)

adaz
Mar 7, 2009

Shy posted:

Which JDK java developers use nowadays?
I see that Oracle offers an official JDK, talks something about licence change and links to OpenJDK, and then there are third party versions, so:
- is the difference meaningful to a developer?
- will your boss tell you which one to use?
- has the preference among developers/companies swung one way or the other?
- what is used by big companies and how do they deploy it?
I guess some questions may sound oblivious but I don't work with java and the op is old. Thanks.

We switched everything to AdoptOpenJDK because Oracle is loving repulsive.

AdoptOpenJDK isnt different - it's literally the same open source code of Java that AdoptJDK uses just compiled by someone else and maintained for longer. For big companies the recent trend has been a move to AdoptOpenJDk or OpenJDK depending on their lifecycle or if you're in a cloud you might be going with one of the cloud JVMs.

Deployment and what is used are kind of seperate topics - are you meaning generic web services type Java code?

adaz fucked around with this message at 21:44 on Feb 23, 2020

Shy
Mar 20, 2010

adaz posted:

Deployment and what is used are kind of seperate topics - are you meaning generic web services type Java code?

Probably. I mean whether the same kind of choice exists wherever you deploy a hosted product to.

adaz
Mar 7, 2009

Shy posted:

Probably. I mean whether the same kind of choice exists wherever you deploy a hosted product to.

Yeah in those cases the best practice/industry practice is to use the same JVM wherever you're deploying the product to that you developed it on. You wouldn't (typically) write & test your code locally using J9 then deploy it with amazon corretto. In _theory_ it should probably work of course but in reality...

Also I should mention most of this holds true for _java_. If you're using other JVM languages there are more commonly accepted JVM choices. Graal for instance is pretty heavily optimized for Scala workloads.

Sagacity
May 2, 2003
Hopefully my epitaph will be funnier than my custom title.

adaz posted:

Graal for instance is pretty heavily optimized for Scala workloads.
I hadn't heard that before. Do you have a source for this? (Genuinely curious, don't want to sound snarky)

adaz
Mar 7, 2009

Sagacity posted:

I hadn't heard that before. Do you have a source for this? (Genuinely curious, don't want to sound snarky)

Yep, it was news to me as well.a medium blog post with numbers but I originally heard it from Chris Thalingers Chris Thalingers presentation on GraalVM use at twitter and general graal talks

Soricidus
Oct 21, 2010
freedom-hating statist shill
Graal is good, but it seems only to be released for lts versions. Which I guess is fine for prod but makes me sad as a dev because new features are also good. At least it does java 11 now!

Also graal ce is deliberately missing optimisations so that oracle can sell the ee as being faster, because gently caress you

Graal.js is now the best embedded scripting language though.

adaz
Mar 7, 2009

Soricidus posted:

Graal is good, but it seems only to be released for lts versions. Which I guess is fine for prod but makes me sad as a dev because new features are also good. At least it does java 11 now!

Also graal ce is deliberately missing optimisations so that oracle can sell the ee as being faster, because gently caress you

Graal.js is now the best embedded scripting language though.

I had somehow missed graal.js. This is roughly a million times better than Rhino if you need a jvm hosted js environment. Thanks!

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb

Shy posted:

Which JDK java developers use nowadays?
I see that Oracle offers an official JDK, talks something about licence change and links to OpenJDK, and then there are third party versions, so:
- is the difference meaningful to a developer?
- will your boss tell you which one to use?
- has the preference among developers/companies swung one way or the other?
- what is used by big companies and how do they deploy it?
I guess some questions may sound oblivious but I don't work with java and the op is old. Thanks.

We switched from Oracle JDK to Amazon Corretto recently

Splinter
Jul 4, 2003
Cowabunga!
I'm looking for some advice on how to architect the following project. It'll have a single DB (likely postgres) used by both a webapp (primarily for displaying data) and a data ingress service (primarily for inserting/updating the DB). Ideally each of these 3 pieces would be able to be deployed separately. The plan is to use Flyway to manage the DB schema, and potentially Hibernate in the data access layer. The webapp will be Spring based, the ingress service is still up in the air. I'd like both the web app and the ingress service to share the same data access code. Would the most straightforward approach be to have the ingress service also be Spring based (Spring Batch?), so Spring can be used for DAO config/injection (this is how I'm seeing a lot of Spring+Hibernate examples done)? Would it make more sense to have Flyway bundled with the DB, or also part of the Spring app? I'm pretty new to Spring, so apologies if some of this sounds nonsensical.

Sagacity
May 2, 2003
Hopefully my epitaph will be funnier than my custom title.
How are you planning to have these components be deployed separately when changes in one of them (the DB schema) will always affect the other two?

Also since the data access patterns are going to be quite different between the ingest and the serving I don't think you should be sharing too much code there either.

Splinter
Jul 4, 2003
Cowabunga!

Sagacity posted:

How are you planning to have these components be deployed separately when changes in one of them (the DB schema) will always affect the other two?

Also since the data access patterns are going to be quite different between the ingest and the serving I don't think you should be sharing too much code there either.

True that whenever a DB migration is run the import service and webapp will both need to be updated to reflect the new schema at the same time. But outside of schema changes, I'd like to be able to make updates to the import service without taking the webapp down (and vice versa). Maybe I'm thinking about this the wrong way.

In terms of shared data access, the the import service will need to fetch from the DB in similar ways as the webapp in some cases. I'm not currently expecting to need to add CUD functionality to the webapp, but were that to happen, it seems like shared DAOs would make this easier. Maybe add a service layer between the DAO and each app that exposes different DAO functionality to each app? At the bare minimum it seems like it would be good to have the DB mapped Entity classes defined in a single location, as I expect there would be a lot of duplication there otherwise.

Objective Action
Jun 10, 2007



Splinter posted:

True that whenever a DB migration is run the import service and webapp will both need to be updated to reflect the new schema at the same time. But outside of schema changes, I'd like to be able to make updates to the import service without taking the webapp down (and vice versa). Maybe I'm thinking about this the wrong way.

In terms of shared data access, the the import service will need to fetch from the DB in similar ways as the webapp in some cases. I'm not currently expecting to need to add CUD functionality to the webapp, but were that to happen, it seems like shared DAOs would make this easier. Maybe add a service layer between the DAO and each app that exposes different DAO functionality to each app? At the bare minimum it seems like it would be good to have the DB mapped Entity classes defined in a single location, as I expect there would be a lot of duplication there otherwise.

Knowing nothing else I would probably go with something like (as you already laid out):
code:
Database Access (Flyway + DAO/Hibernate)
      ^
      |
      |
|----------------|
Ingest           Webapp
But that doesn't necessarily account for if/when your webapp starts wanting to touch tables the ingest doesn't know about and vice-versa so might need to split the access up later into a few DAO packages. That being said if you haven't already look at Apache NiFi for your ingest needs. I've used it for small things and multiple PB jobs and it works like a champ. Its easy to set up and has a million pre-built ETL tools and fairly decent docs on how to write your own new ones.

adaz
Mar 7, 2009

Splinter posted:

I'm looking for some advice on how to architect the following project. It'll have a single DB (likely postgres) used by both a webapp (primarily for displaying data) and a data ingress service (primarily for inserting/updating the DB). Ideally each of these 3 pieces would be able to be deployed separately. The plan is to use Flyway to manage the DB schema, and potentially Hibernate in the data access layer. The webapp will be Spring based, the ingress service is still up in the air. I'd like both the web app and the ingress service to share the same data access code. Would the most straightforward approach be to have the ingress service also be Spring based (Spring Batch?), so Spring can be used for DAO config/injection (this is how I'm seeing a lot of Spring+Hibernate examples done)? Would it make more sense to have Flyway bundled with the DB, or also part of the Spring app? I'm pretty new to Spring, so apologies if some of this sounds nonsensical.

The most straightforward way of doing this is to use Spring boot for the web service, spring batch for the ingress and then have them share a module that contains the JPA (hibernate) code for managing the database. That gives you 4 pieces of deployable ish code that looks like this


Web App - Assume this is just a react /angular / svelte/somethingother JS app that pulls in data via an api but is otherwise static site

API - Spring Boot.

Batch - Spring Batch

JPA Library - Package contains contracts and all that for database access and is pulled in as library by API + Batch. This lets it be versioned, deployed and updated seperately. Store it in artifactory / nexus or something similar.


decent article on multi-module spring apps with a library. FWIW I really, really like Spring Batch and how they handle the JPA and data persistence. It all just sort of works and is relaly intuitive.

Splinter
Jul 4, 2003
Cowabunga!
Thanks for the feedback. I've got a better handle on things now. I'll take a look at NiFi for the ingest piece, as the details of that piece haven't been fleshed out yet, but I do see the appeal of keeping everything Spring.

abraham linksys
Sep 6, 2010

:darksouls:
I've started dipping my toe into writing web apps in Kotlin on the JVM. I'm a front-end engineer at my day job, but I occasionally poke around at the backend for fun (or when I can't pull in a backend engineer for a trivial change). We use Dropwizard at work for all our services (with a mixture of Java and Kotlin depending on the age of the service), and I've been pretty happy with writing in it, so I've started looking into using Kotlin for the API in a personal project (which was previously Express/TypeScript, which is just an absolute mess in practical usage).

One thing I'm still figuring out is what libraries I should pick and choose from the ecosystem. I picked up JDBI as my database layer, since it seems well-regarded and I don't really like traditional ORMs - we use it at work, though we've been experimenting with JOOQ in newer things (which I put aside for now purely because it seemed harder to set up and configure).

The actual web framework part is where I'm kinda lost. I've been building on this library I found called Javalin, which is one of those web frameworks that's very much One Dude's Neat Project. Like a lot of those, it's fairly minimal, but has a decent set of batteries included for things like validation and JSON serialization, as well as a lot of guides and tutorials. It's fun to write in, but before I go too much further with it, I figured I should look at the rest of the ecosystem.

Problem is, the ecosystem is huge, and while there's many things that Java does better than Node, open source marketing sites isn't one of them. I've been trying to sort through everything from Spring Boot, to Quarkus, to Micronaut, to JHipster, to Dropwizard, to Ktor, to Vertx, to like eighteen other things, trying to figure out what the best options are.

My guess, from what I've seen so far, is that Spring Boot probably is the framework with the most users and support. Mostly, I figure this from the number of times I've googled "how to do X in java" and gotten an answer that is specifically tailored for Spring Boot. On one hand, that makes me think it's something I could easily Google may way to production with; on the other, I worry that it has a lot of its own special complexities compared to other frameworks. Like, when I've started poking into what Spring actually looks like in practice, I've read about stuff like its @Transactional annotation, which requires using your DB library with a special TransactionAwareDataSourceProxy, and then somehow magically binds DB usage within service objects to a specific transaction - which simultaneously sounds awesome and terrifying. It seems like Spring also has its own DI that has some Rails-style "analyze all your poo poo and hook it up," which is kind of weird to me - I've been doing what could be charitably described as "manual DI" in my app (re: a root function that creates all of the objects in my app and passes them to each other's constructors as needed), since DI in general seems like a huge can of worms to figure out.

All that aside, one other thing I don't really get is where Spring Boot stops and where Spring itself begins. Spring Boot kind of markets itself as "pre-configured Spring," but its user guide seems to describe an entire framework unto itself, and just about every library you can use with it has a package used to configure it specially for Spring, not to mention that it has a "project initializer" with approximately 50 different checkboxes for these libraries. It's daunting in a way I thought it was specifically made to avoid being.

So I have few questions:

a) Are there other frameworks worth investigating for small to medium scale projects beyond Spring Boot? Since I've found Javalin to Suit My Needs so far, should I probably just stick with it?

b) Is Spring Boot the closest the JVM has to a recommended happy path for building new web apps? Is it still a big ecosystem, or are people moving to other frameworks, scared off by the dislike people have for Spring in general? And is it reasonably learnable for developers with no experience with Spring before?

c) I noticed that "Spring WebFlux" (which I guess you can use from Spring Boot?) seems to be one of the few web frameworks that supports Kotlin coroutines (outside of Ktor and I think Vertx?). Has anyone used it? Is it mature/supported/"production-ready," or more of an experimental thing? I don't really need to worry about handling a whole lotta connections at once in my little personal project anyways, but one thing that I liked about Node was async-by-default I/O, so you didn't need to change your programming model as you scaled. It seems like that's still very much not the case in most JVM frameworks (though I guess having an I/O thread pool means a lot of devs never have to think about it?) so I'm curious if WebFlux is anywhere near being a "default" recommendation yet.

adaz
Mar 7, 2009

Spring Boot, Quarkus, Vert.x and Micronaut are the most popular "full featured" frameworks for building random apps I've seen in recent years. Each has something to recommend for it. As you've discovered with Spring it has by far the largest ecosystem and help available. It _also_ has a lot of cruft and legacy decisions. Like stack traces for Spring boot will be hundreds of lines deep by the time it gets to your code. Quarkus and Micronaut are much newer frameworks that are more built for small containerized apps and cloud native style deploys. Vert.x is somewhat of a compromise between Boot & Quarkus/Micronaut. In general all 4 have something to go for them and it probably somewhat depends on - in your case - how good their Kotlin support is and maybe where you're deploying it?

All of those 4 though are really tailored around providing web services and letting the front ends consume them via ajax or w/e not actually building server side rendered apps. If that's what you want I'm honestly not sure anymore what's decent. The last real java framework I used for that was the stuff built into Adobe experience manager maintained by the apache foundatin.

Objective Action
Jun 10, 2007



I think the problem in my mind is in trying to disambiguate what we are talking about when we talk web apps. You mention front end but then all the projects listed are geared towards service applications serving REST endpoints. To be fair I don't think that's your fault at all since searching for Java + Web anything is going to flood out the results with those these days. Of the ones listed I would say stick with Boot and only open the Spring can of worms one piece at a time when you want to add a new feature they already have into your code. Don't try to eat the whale whole.

I'm using WebFlux and its quite robust but its also designed to be entirely non-blocking, and highly concurrent, so many of the follow-on decisions on how the API works can occasionally make debugging it and reasoning about problems a little more difficult than normal. If you are comfortable using parallel map/reduce semantics its pretty good though.

Now as for web applications actually written in Java that landscape is pretty narrow. Most of the old projects in that space are really old and decrepit. To my knowledge the three biggest real boy projects still kicking around, maintained, documented, and with active user communities are Vaadin, Play, and Struts. All three of these are totally usable but keep in mind the newest of these was first released in 2007 so even though they all are still actively releasing the API isn't going to be whatever the new hotness is today. Also I have no idea how robust their Kotlin support is.

Mostly these days when I want a web app I write it in Typescript and then deploy it with Boot or JBoss WildFly/Thorntail (which is basically JHipster but by hand).

Hippie Hedgehog
Feb 19, 2007

Ever cuddled a hedgehog?
For what it's worth, we're just wrapping up version 1.0 of a project in Javalin, using JOOQ. I think they're both "production ready" but there have been a few times where I had to request clarification of some feature from the Javalin designer. He did respond very helpfully to Github tickets. For a solo project, I wouldn't hesitate to use those libraries.

We didn't find that Jooq needed all that much effort to set up, but one of our guys did spend a couple of days just writing the Gradle script that did code generation just the way he wanted it. Not sure how much of that was strictly necessary.

Sagacity
May 2, 2003
Hopefully my epitaph will be funnier than my custom title.
At my day job we have hundreds of services all running on top of Spring Boot. If you don't care about details you don't need to, but if you're interested in tweaking there are a ton of customization options. The defaults are really decent though, so they're an excellent starting point.

Additionally, the community is huge and they also version manage basically all dependencies you'll want to use so you don't need to manually chase updates.

abraham linksys
Sep 6, 2010

:darksouls:

Objective Action posted:

I think the problem in my mind is in trying to disambiguate what we are talking about when we talk web apps. You mention front end but then all the projects listed are geared towards service applications serving REST endpoints. To be fair I don't think that's your fault at all since searching for Java + Web anything is going to flood out the results with those these days. Of the ones listed I would say stick with Boot and only open the Spring can of worms one piece at a time when you want to add a new feature they already have into your code. Don't try to eat the whale whole.


Sorry for the lack of clarity of here - my project's frontend is a Vue app that consumes a REST API, so I'm looking for an HTTP API framework specifically. I don't need, e.g., server side templating.

I know some frameworks are focused more on the "internal services communicating between each other" use case instead of the "API consumed by a web app" use case, so I wanted to mention this is in the context of a web app just to filter out anything that is, say, GRPC-first.

adaz
Mar 7, 2009

abraham linksys posted:

Sorry for the lack of clarity of here - my project's frontend is a Vue app that consumes a REST API, so I'm looking for an HTTP API framework specifically. I don't need, e.g., server side templating.

I know some frameworks are focused more on the "internal services communicating between each other" use case instead of the "API consumed by a web app" use case, so I wanted to mention this is in the context of a web app just to filter out anything that is, say, GRPC-first.

I took another look @ micronauts and you might want to check it out based on your use case. They added some support for Kotlin coroutines and all their documentation has kotlin examples too. I've personally never used it in production only playing around with it on the cloud but found it remarkbly quick and lightweight compared to like, spring.

carry on then
Jul 10, 2010

by VideoGames

(and can't post for 10 years!)

adaz posted:

I took another look @ micronauts and you might want to check it out based on your use case. They added some support for Kotlin coroutines and all their documentation has kotlin examples too. I've personally never used it in production only playing around with it on the cloud but found it remarkbly quick and lightweight compared to like, spring.

How does it compare to something like Quarkus with just JAX-RS loaded? Don't know if the native Graal stuff is yet but I do know several of the microprofile implementations are used in production and can be minified down to just the needed libraries, but then my experience is mostly with larger Java EE based apps that tend to need the world anyway.

adaz
Mar 7, 2009

carry on then posted:

How does it compare to something like Quarkus with just JAX-RS loaded? Don't know if the native Graal stuff is yet but I do know several of the microprofile implementations are used in production and can be minified down to just the needed libraries, but then my experience is mostly with larger Java EE based apps that tend to need the world anyway.

Quarkus is the other one I played around with and in our testing they are extremely similar in that respect. Both designed ot be minimal loading on the JVM, low memory footprint and fast startup times. I believe both use bean annotations to avoid heavy use of reflection in most cases although I think the implementations are a little bit different.

Love Stole the Day
Nov 4, 2012
Please give me free quality professional advice so I can be a baby about it and insult you
Spring Maven/Gradle question:

When we add a new dependency to a project, where can we see what new editable configurations are exposed to us in the project's application properties file?

For example, adding Spring Boot Data MongoDb as a dependency exposes spring.data.mongodb with a bunch of child things... but where can we see the reference for all of those things?

At the moment, my only option seems to be to just look up a tutorial example of someone else using it and then following their example.

Objective Action
Jun 10, 2007



Love Stole the Day posted:

Spring Maven/Gradle question:

When we add a new dependency to a project, where can we see what new editable configurations are exposed to us in the project's application properties file?

For example, adding Spring Boot Data MongoDb as a dependency exposes spring.data.mongodb with a bunch of child things... but where can we see the reference for all of those things?

At the moment, my only option seems to be to just look up a tutorial example of someone else using it and then following their example.

There are a bunch of ways to do this at different levels. Most jars are supposed to include a configuration metadata file in src/main/resources but that can be hit or miss. If you really need to get at that from Maven/Gradle you can unpack resources and get at least some info that way.

A simpler way to debug quickly is just plunk in a class to log out the properties ala this snippet.

My favorite way though is to use Spring Actuator to turn on the /env endpoint dynamically since I can do that and other stuff on the test servers dynamically over JMX. It also gets you some nice log level switching features (please dev only!) and some health and metrics poking if you really need it and don't already have something like Flight Recorder or Grafana/Prometheus set up.

i vomit kittens
Apr 25, 2019


Does anyone have advice on how to get Spring Boot to properly store lists in a Postgres table?

I am working on an attendance tracking tool. Each User object has a list property that stores the ID of every event they've been to, which I've annotated as an element collection:

code:
public class User {

    //other properties...

    @ElementCollection
    private List<Integer> eventsAttended;
}

When someone signs in to an event, that event's ID is supposed to get appended to this list and then their User object is saved to the database. However, the lists for some reason aren't being stored in an array column of the user table, but rather in a separate table like this:



When a User object is later instantiated by pulling it from the database, the eventsAttended attribute only comes up as a one item list with the first event ID that the query finds instead of all of them. So, using the above picture as an example, when I find user 10 from the database their eventsAttended is a list that only contains 79, when it should also contain 64, 73, and 50.

The Users are grabbed from the database using a normal repository, so I'm not sure if there's anything I can fix there. I feel like it has to do with the @ElementCollection annotation but I'm not sure what I should change it to in order for things to work the way I want them to.

Ither
Jan 30, 2010

If I'm understanding correctly, there's a many to many relationship between users and events. Is there a reason why you don't want them to be in a separate table?

Sagacity
May 2, 2003
Hopefully my epitaph will be funnier than my custom title.

i vomit kittens posted:

Does anyone have advice on how to get Spring Boot to properly store lists in a Postgres table?
You say Spring Boot but your question is about a JPA annotation. Do you mean you're using Hibernate? That doesn't seem to support Postgres arrays afaik.

i vomit kittens
Apr 25, 2019


Ither posted:

If I'm understanding correctly, there's a many to many relationship between users and events. Is there a reason why you don't want them to be in a separate table?

I guess it's not necessarily an issue that they are, it's just not what I was expecting to happen (possibly because Hibernate doesn't support it?). If there's a way I can get it working as is that would do just as well

Sagacity posted:

You say Spring Boot but your question is about a JPA annotation. Do you mean you're using Hibernate? That doesn't seem to support Postgres arrays afaik.

Oh yeah, sorry, it's Hibernate. My mind just merges then together.

Splinter
Jul 4, 2003
Cowabunga!
It would be more straightforward to set that up as a standard JPA ManyToMany (or OneToMany/ManyToOne etc, whatever makes sense) relationship. That is the classic way to model that situation in SQL as well. That said, you probably can extend Hibernate to support this (I've done something like this to support Postgres Enum Types). A quick search brings up this. It looks like this wraps some of the implementation into a library, but there's a link that describes what that library is doing. Again though, you probably should just use a join table for this.

DELETE CASCADE
Oct 25, 2017

i haven't washed my penis since i jerked it to a phtotograph of george w. bush in 2003
just use a native sql query because hql is trash

Adbot
ADBOT LOVES YOU

Splinter
Jul 4, 2003
Cowabunga!

DELETE CASCADE: a feature available to you if you go with the relational approach

  • 1
  • 2
  • 3
  • 4
  • 5
  • Post
  • Reply