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
Pedestrian Xing
Jul 19, 2007

Anyone have experience with event sourcing in Java? Looking at using it as the data model for a new project. Biggest draw is the built-in audit functionality since the data is legal stuff.

Adbot
ADBOT LOVES YOU

Sagacity
May 2, 2003
Hopefully my epitaph will be funnier than my custom title.
I've done some work with it, the main difficulty I found is that nobody will be defining decent commands and events and your UI will almost definitely will not be designed to take advantage of it (e.g. probably no explicit "I have moved and want to change my address" button so you can only capture a generic ChangeAddressCommand instead of more explicit ClientMovedHouseCommand that could give you valuable business insights).

Also good luck if you want to change the design of your commands, if replaying them starts taking too long, etc etc. It's just a lot of hassle for very little gain imo. There's a reason event sourcing is still a niche thing to do.

If you're interested in it for auditing purposes just add a bunch of triggers to your regular database. It will be infinitely easier to work with.

Tony Danza
Dec 21, 2004
And How!

Pedestrian Xing posted:

Anyone have experience with event sourcing in Java? Looking at using it as the data model for a new project. Biggest draw is the built-in audit functionality since the data is legal stuff.

I just finished up a project using Axon framework. The reason we were using it was not for the auditing benefits but the letting our project listen to events happening in other projects and then reason out an understanding of it's own. It was nice to do something different.

Pedestrian Xing
Jul 19, 2007

Tony Danza posted:

I just finished up a project using Axon framework. The reason we were using it was not for the auditing benefits but the letting our project listen to events happening in other projects and then reason out an understanding of it's own. It was nice to do something different.

Thanks for the recommendation! After evaluating a few options, I think I've decided to write my own simple framework. Realistically, we don't need full-blown event sourcing so much as snapshot functionality. Took some inspiration from Axon's Spring integration about how to do the API.

PierreTheMime
Dec 9, 2004

Hero of hormagaunts everywhere!
Buglord
I'm having a weird problem with SFTP file streaming using the JSch library which I have not encountered before and I was hoping someone might be able to point me in the right direction. I use this code to access and download files from SFTP to an AWS S3 bucket and it's worked fine for multiple different target SFTP servers until this one. Something in the way the host is communicating appears to be causing JSch to just go into a wait loop and I have no idea why.

Here's the stoppage in question:


My code is waiting for the read from the filestream.


JSch looping, waiting for host.

I can let this sit for a very long time without any connection failure or other error, it just loops. Any ideas or should I reach out to the vendor and see if they see anything in their logs? Like I said, this has worked for every other server I've hit and I get files larger than 100GB at a time, so it's fairly stable as far as I've seen up to now.

Kilson
Jan 16, 2003

I EAT LITTLE CHILDREN FOR BREAKFAST !!11!!1!!!!111!

PierreTheMime posted:

I'm having a weird problem with SFTP file streaming using the JSch library which I have not encountered before and I was hoping someone might be able to point me in the right direction.

I remember running into something similar before (but I don't remember if it was exactly this). A quick look at the code suggests this is happening when it tries to negotiate a cipher or something like that (it's looping in_kex). If you can get a full packet trace, you might be able to tell exactly what's going wrong. I seem to remember having to fix at least one SFTP library we used because it didn't handle the cipher exchange properly in weird circumstances.

Paul MaudDib
May 3, 2006

TEAM NVIDIA:
FORUM POLICE
In Java web programming, you have HttpSession for managing data spanning multiple requests. Is there any framework for sharing that session between multiple front-end servers (obviously would have to be exclusive, etc), for load-balancing? It obviously would not be that hard to write such a thing, just wondering if there's anything already extant.

You can load balance in the front end of course, just share users between multiple servers and then use the standard session mechanism, but then if you have to shut down any single server you lose all the sessions that were on that server.

Kilson
Jan 16, 2003

I EAT LITTLE CHILDREN FOR BREAKFAST !!11!!1!!!!111!

Paul MaudDib posted:

In Java web programming, you have HttpSession for managing data spanning multiple requests. Is there any framework for sharing that session between multiple front-end servers (obviously would have to be exclusive, etc), for load-balancing? It obviously would not be that hard to write such a thing, just wondering if there's anything already extant.

You can load balance in the front end of course, just share users between multiple servers and then use the standard session mechanism, but then if you have to shut down any single server you lose all the sessions that were on that server.

I thought JBoss(?) had some notion that you could run a cluster of them and they would share/distribute session state. Not sure if that's actually true, as it's been quite some time since I looked at it, or if it's helpful even if true.

CPColin
Sep 9, 2003

Big ol' smile.
Tomcat does session clustering, too

Volguus
Mar 3, 2009
Or the session state can be saved in a database, so everyone can access it anytime. I think jboss can be configured to do that as well.

Pedestrian Xing
Jul 19, 2007

I know Spring supports it through JDBC/Redis but it wouldn't be terribly hard to do yourself.

Objective Action
Jun 10, 2007



As long as you don't want to store a tremendous amount of state a Session EJB in Java EE terms would possibly do what you need. This is old documentation for Weblogic (gag!) but the diagrams are still relevant: https://docs.oracle.com/cd/E11035_01/wls100/ejb/session.html. Comes with some rudimentary support for various kinds of clustering and redundancy if you scrounge around the various docs.

Generally anything compliant with Java EE 6 (er, Jakarta now I guess) which is fairly old and well supported would do it. Tomcat, JBoss (Wildfly, Thorntail, whateverthefuck-they-renamed-it-this-week). If you already are running in a web container it would be fairly easy to drop in and test and it would remain implementation independent. Depending on the size and scope of your need though something like Redis or plain old Postgres wouldn't be all that much more work these days honestly.

carry on then
Jul 10, 2010

by VideoGames

(and can't post for 10 years!)

There’s the JCache API https://www.baeldung.com/jcache which is implemented by a bunch of different providers(I know of Infinispan, Hazelcast, and Apache Ignite but there are many others.) some of the newer EE runtimes have features that integrate with that as well (for example https://openliberty.io/docs/ref/feature/#sessionCache-1.0.html)

chippy
Aug 16, 2006

OK I DON'T GET IT
So, in our code base we have a simple POJO that's basically a data transfer object. It has a lot of properties, so it has a nested static builder class that has lots of methods for settings its properties with 'return this' at the end, so you can just chain on all these property setters and then call build() at the end to build the POJO. build() basically just passes the builder itself into the constructor of a new instance of the POJO.

I had to create a subclass of the POJO with two additional fields + setters and getters. The whole thing seemed a bit unecessary to me, but I thought I'd follow the existing pattern for consistency. So I also created a subclass of the builder class, adding the two extra setters and overriding the build method.

Then I tried to use it. At first, I copied and pasted some existing code making use of the builder, changed the builder class to the new subclass, and added calls to my two new setters at the end, but Eclipse told me the two methods didn't exist. After thinking about it I thought, maybe that's because the setters I'm calling first are in the superclass, so when they 'return this', that means an instance of the superclass, which doesn't have the two new setters. So I'll have to make my two new setters the first ones I call. So I tried this:

code:
return new FooBuilder.newSetterA(x).newSetterB(y) ... etc. etc. .build();
Eclipse is happy with me calling newSetterA() but not newSetterB(), says it doesn't exist.

So I try this:

code:
return new FooBuilder.newSetterB(y).newSetterA(x) ... etc. etc. .build();
Now Eclipse is happy with the call to newSetterB(), but not newSetterA(), says it doesn't exist.

Both the setters are in the subclass (FooBuilder) and both 'return this' at the end. So what's going on here? My assumption is that it's some subtlety of Java which is related to it being a static class, and I'm about to make the class non-static and put it in its own file to test this theory, but I wonder if someone could fill me in? I did several years of C# work before starting my current Java role so I'm a bit less familiar with some of the nuances of it.

Hopefully this makes sense, if not I can knock up a sanitised example.

chippy fucked around with this message at 18:07 on Jul 9, 2020

Volguus
Mar 3, 2009
Both setters return FooBuilder right? If they do then it should work. However, if you're calling in that chain a method from BarBuilder (from which I presume FooBuilder extends) then you will need to cast things. Basically, should do something like this (can be made better, of course):
code:
FooBuilder builder = (FooBuilder)(new FooBuilder().setSetterOfBar1(x).setSetterOfBar2(y)...);
Foo f = builder.setSetterOfFoo(z).build();
Then Foo which extends Bar should have all Bar's properties and Foo's properties.

chippy
Aug 16, 2006

OK I DON'T GET IT

Volguus posted:

Both setters return FooBuilder right? If they do then it should work. However, if you're calling in that chain a method from BarBuilder (from which I presume FooBuilder extends) then you will need to cast things. Basically, should do something like this (can be made better, of course):
code:
FooBuilder builder = (FooBuilder)(new FooBuilder().setSetterOfBar1(x).setSetterOfBar2(y)...);
Foo f = builder.setSetterOfFoo(z).build();
Then Foo which extends Bar should have all Bar's properties and Foo's properties.

Both setters return 'this', and are in FooBuilder, which extends BarBuilder. Even if my method chain has only calls to setters that exist in FooBuilder, only the first one works, the second I'm told doesn't exist.

At this point I'm wondering if it's just Eclipse freaking out and maybe I need to clean and rebuild everything.

baka kaba
Jul 19, 2003

PLEASE ASK ME, THE SELF-PROFESSED NO #1 PAUL CATTERMOLE FAN IN THE SOMETHING AWFUL S-CLUB 7 MEGATHREAD, TO NAME A SINGLE SONG BY HIS EXCELLENT NU-METAL SIDE PROJECT, SKUA, AND IF I CAN'T PLEASE TELL ME TO
EAT SHIT

What type are the setters actually returning in the method signature? FooBuilder or BarBuilder?

1337JiveTurkey
Feb 17, 2005

I'm a little rusty since I haven't used this pattern in a while but I'd make the type of the FooBuilder become FooBuilder<F extends Foo, FB extends FooBuilder<F, FB>>. The first parameter is the type that you're building while the second parameter is the concrete type of the builder, so BarBuilder. If this seems weird, just think about how enumerations are defined as Enum<E extends Enum<E>>.

Every method that can be chained now should return the type FB. I usually made a method called self() that returns this cast to FB. Naturally the build() method returns B instead.

With these changes every method returns the declared type of the builder even if they were declared on a parent object.

Guildenstern Mother
Mar 31, 2010

Why walk when you can ride?
Is there a lazier way to search object arrays for a particular match? (I'm doing a phonebook project in bootcamp and want to search by first name etc) than copy pasting a search for each individual variable? This feels really inefficient, which might be because its arrays instead of arraylists which we aren't allowed to use on this project, but I can't shake the feeling I'm doing too much typing.

I've essentially got one of these for each variable:
code:
	public static Records[] searchByPhoneNum(Records[]phonebook, String phoneNum) {
		Records[] matches = new Records[0];
		for(int i = 0; i < phonebook.length; i++) {
			if (phonebook[i].getPhoneNum() == phoneNum) {
				matches= expandArray(matches, phonebook[i]);
			}
		}
		return matches;

Guildenstern Mother fucked around with this message at 22:07 on Jul 9, 2020

Jock Seppuku
Apr 16, 2008
code:
public static Records[] searchByPhoneNum(Records[] phonebook, String phoneNum) {
    return Stream.of(phonebook).filter(it -> phoneNum.equals(it.getPhoneNum())).toArray(Records[]::new);
}
Assuming you're using at least Java 8, this is how I'd do it. If you're not allowed to use ArrayLists, then this definitely wouldn't be allowed for your project, lmao

Jock Seppuku fucked around with this message at 00:03 on Jul 10, 2020

Guildenstern Mother
Mar 31, 2010

Why walk when you can ride?
We're not allowed to use arraylists on this project sadly. He wants us to suffer through arrays first.

Pedestrian Xing
Jul 19, 2007

Guildenstern Mother posted:

code:
			if (phonebook[i].getPhoneNum() == phoneNum) {

You probably don't want to use == on Strings (or Objects in general).

Guildenstern Mother
Mar 31, 2010

Why walk when you can ride?
good to know, I haven't actually test run it yet, but it wasn't giving me any red squiggles. Is there a better choice I should be looking at?

carry on then
Jul 10, 2010

by VideoGames

(and can't post for 10 years!)

Guildenstern Mother posted:

good to know, I haven't actually test run it yet, but it wasn't giving me any red squiggles. Is there a better choice I should be looking at?

In the case of any non-primitive variables, == only confirms that two operands refer to the same reference, i.e. that they refer to the same object in memory. For content equality, Object has a method equals() that just about every class should override to intelligently decide if the passed-in argument is equivalent to the instance of the class equals is called on.

So with String instances, == asks "are these the same object in memory?" where as .equals() asks "do these strings have the same characters in the same order?" Both are valid Java, it's just that you mean the latter but are asking the former, and the answers will differ.

If and when you go to override equals() in classes you write, also make sure you take care of hashCode(). https://www.geeksforgeeks.org/equals-hashcode-methods-java/

Kilson
Jan 16, 2003

I EAT LITTLE CHILDREN FOR BREAKFAST !!11!!1!!!!111!

carry on then posted:

In the case of any non-primitive variables, == only confirms that two operands refer to the same reference, i.e. that they refer to the same object in memory. For content equality, Object has a method equals() that just about every class should override to intelligently decide if the passed-in argument is equivalent to the instance of the class equals is called on.

So with String instances, == asks "are these the same object in memory?" where as .equals() asks "do these strings have the same characters in the same order?" Both are valid Java, it's just that you mean the latter but are asking the former, and the answers will differ.

If and when you go to override equals() in classes you write, also make sure you take care of hashCode(). https://www.geeksforgeeks.org/equals-hashcode-methods-java/

You also have to be careful, because with strings, == will *usually* work, because of string interning. So you might use == and think, "great, it's working", but then sometime it will fail and you might be really confused as to why.

Also, == works the same for Integer objects as int primitives, up to a value of 128 (this may vary by jvm implementation). I really hate this behavior, because why would anyone ever care about the difference between two Integer objects representing the same number?

Anyway, for any kind of Object, just use .equals() and be safe and happy.

Guildenstern Mother
Mar 31, 2010

Why walk when you can ride?
Thanks, I'll go through and change that first thing. While I'm on the subject, one of the functions I need to build in is one to delete objects in an array. I don't think I *have* to but would it be proper practice to try to set up a loop in that method to make the array one size smaller kind of in the same way you make an array bigger by making a new array to replace the first one? (sorting so the null value is at the back before making a new array one slot shorter obviously) One one hand it clears out some useless space but is that more or less memory efficient than creating new arrays all the time?

Paul MaudDib
May 3, 2006

TEAM NVIDIA:
FORUM POLICE
Arrays are a fixed size thing and the only way to resize them is to allocate a new one and copy everything over. Obviously that is not something you really want to do every time you add or remove an element.

The List interface is the canonical interface for a variable-sized array, and the various implementations will handle the bookkeeping of this for you. Obviously if you use an ArrayList then allocations are happening under the hood anyway but you don’t have to implement it yourself. The default behavior is that it will over allocate and once it hits the array size it will switch to a new array that is double the size. If you remove elements that memory is not reclaimed. Obviously this can lead to performance degradation in some circumstances if there is a big mismatch between the allocated size and the actual size, and you can specify an initial capacity if you want.

https://dzone.com/articles/performance-evaluation-of-java-arraylist

There are other implementations like a linked list if you want but obviously they come with the other tradeoffs you learned in your data structures courses. There's no free lunch in algorithms.

Paul MaudDib fucked around with this message at 06:39 on Jul 10, 2020

chippy
Aug 16, 2006

OK I DON'T GET IT

baka kaba posted:

What type are the setters actually returning in the method signature? FooBuilder or BarBuilder?

Oh my god, I'm a loving penis. :doh:

Yeah so in the cold light of the next day I realise what happened. The original builder was just called Builder, and so I just called the new one Builder too and had Foo.Builder and Bar.Builder, but our linter didn't like it so renamed the subclass to FooBuilder, but didn't update the setters, so yeah, they were still returning Builder.

This is a good demonstration of why I should just leave all problems encountered after about 4pm to the next day.

baka kaba
Jul 19, 2003

PLEASE ASK ME, THE SELF-PROFESSED NO #1 PAUL CATTERMOLE FAN IN THE SOMETHING AWFUL S-CLUB 7 MEGATHREAD, TO NAME A SINGLE SONG BY HIS EXCELLENT NU-METAL SIDE PROJECT, SKUA, AND IF I CAN'T PLEASE TELL ME TO
EAT SHIT

:cheerdoge:

Guildenstern Mother
Mar 31, 2010

Why walk when you can ride?
Anyone know any good tutorials for getting started with servlets? We started on them yesterday and while I'm fairly certain most of the lecture was in the english language and made up of real words none of it managed to penetrate my big dumb head.

Paul MaudDib
May 3, 2006

TEAM NVIDIA:
FORUM POLICE

Guildenstern Mother posted:

Anyone know any good tutorials for getting started with servlets? We started on them yesterday and while I'm fairly certain most of the lecture was in the english language and made up of real words none of it managed to penetrate my big dumb head.

The short and long of it is that servlets are handlers for web requests. It's a place for you to stick some java logic that processes some input and either returns a response directly (eg often used for sending a file) or redirects to a view (templating engine) to generate html.

It's kind of an older API and nowadays you probably would not be writing servlets directly but rather through something like spring web mvc.

It's a part of the Java EE API and today EE is basically viewed to have been massively overengineered and only a few parts of it are directly relevant to modern webdev. Servlets are one of them. Sometimes.

Guildenstern Mother
Mar 31, 2010

Why walk when you can ride?
Oh I'm so glad to hear I'm not going to be doing this crap in eclipse forever. Spring/boot is more automated I assume? As far as not having to override doGet or doPost every time

Paul MaudDib
May 3, 2006

TEAM NVIDIA:
FORUM POLICE

Guildenstern Mother posted:

Oh I'm so glad to hear I'm not going to be doing this crap in eclipse forever. Spring/boot is more automated I assume? As far as not having to override doGet or doPost every time

exactly, this is more idiomatic nowadays, then you send it to a templating engine like thymeleaf.

(there were similar frameworks at the time too, like Apache/Jakarta Struts, I think Servlets were explicitly meant to be a low level thing, I'm not sure that building web content on them directly would ever have been considered a super efficient way to make a website. But Spring is so much more straightforward than Struts, Struts is from the days when everyone thought it was a great idea to spread configuration across five different xml files in case you wanted to dynamically plug something or whatever idk)

Guildenstern Mother
Mar 31, 2010

Why walk when you can ride?
Yeah I think we're in the "learn the archaic long way before we give you the easymode version" stage of this. Glad to hear that I shouldn't be freaking out about it quite as much as I was.

Pedestrian Xing
Jul 19, 2007

Yeah, Spring and Micronaut and similar frameworks abstract REST stuff away to nothing. Had to refactor some legacy Servlet code recently and it was painful.

Twerk from Home
Jan 17, 2009

This avatar brought to you by the 'save our dead gay forums' foundation.
I've got a set of AWS lambdas that I'm wanting to fold into an existing Spring Boot application. However, they're deployed in a way right now where the hostname is basically what's being used for routing. Is there any sane way to accomplish hostname-based routing in what is intentionally a very vanilla Spring Boot setup?

Existing API as deployed with many API Gateway instances and lambdas:

cat.api.mycompany.com/doSomething
dog.api.mycompany.com/doSomething

I'm wanting to use the hostnames to be able to route cat and dog to different Controllers. I could stick a proxy in there to do hostname based routing like:

cat.api.mycompany.com/doSomething -> unified.api.mycompany.com/cat/doSomething
dog.api.mycompany.com/doSomething -> unified.api.mycompany.com/dog/doSomething

but I havent dug into if I can configure the existing ALB to do that, which is the only proxy in the system right now, or if I should be sticking a sidecar container to the spring boot container. I could whip up an nginx config in no time flat, but I'm sure that Envoy or Zuul could handle that as well. I'd prefer if I could do host-based routing in Spring Boot itself in addition to path-based, so that calls to either end up in the same controller.

Edit: It looks pretty easy to make the ALB do that, but I'm still curious if anybody could manage to do it inside of the application itself.

Twerk from Home fucked around with this message at 05:14 on Jul 24, 2020

Volguus
Mar 3, 2009

Guildenstern Mother posted:

Yeah I think we're in the "learn the archaic long way before we give you the easymode version" stage of this. Glad to hear that I shouldn't be freaking out about it quite as much as I was.

A bit late to the question, but servlets are not archaic at all. They are used today by ... everything really. Spring itself (or any other framework) still has a dispatcher servlet that listens to the request, looks at the parameters and headers and HTTP verb and then decides what class to call, what method with what params. JSPs themselves become servlets, then compiled into bytecode. While it is true that most developers nowadays do not write servlets anymore and do not have to deal with its awful "servletOutputStream.println" peppered everywhere (or templated, but same poo poo really), it is still extremely important for a developer to know what goes on underneath all that magic. Do your homework, learn how to write them and don't forget all of that when you move to greener pastures.

There are times (very rarely thankfully) when I need to accept an (Http)ServletRequest as a parameter to a method or write to an (Http)ServletResponse. They come from the servlet that called me which got them from the application server. I don't think they'll ever be completely gone, for as long as Java will stick around at least.

Twerk from Home
Jan 17, 2009

This avatar brought to you by the 'save our dead gay forums' foundation.
For greenfield Spring development, is it pretty much always worthwhile to start off with WebFlux nowadays, or is going with the much simpler imperative + JPA still fine in the long run? Usage case is calling out to external http services in parallel, which I can do with WebClient from either reactive or non-reactive just fine, and using Postgres as persistence.

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

Paul MaudDib posted:

In Java web programming, you have HttpSession for managing data spanning multiple requests. Is there any framework for sharing that session between multiple front-end servers (obviously would have to be exclusive, etc), for load-balancing? It obviously would not be that hard to write such a thing, just wondering if there's anything already extant.

You can load balance in the front end of course, just share users between multiple servers and then use the standard session mechanism, but then if you have to shut down any single server you lose all the sessions that were on that server.

https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-cache

If you use a Redis server, then all of your front-ends can call out to that and get session data that way.

edit-- oh jeez, I didn't realize I was replying to a post from a month ago

Love Stole the Day fucked around with this message at 03:09 on Jul 28, 2020

Adbot
ADBOT LOVES YOU

Guildenstern Mother
Mar 31, 2010

Why walk when you can ride?

Volguus posted:

A bit late to the question, but servlets are not archaic at all. They are used today by ... everything really. Spring itself (or any other framework) still has a dispatcher servlet that listens to the request, looks at the parameters and headers and HTTP verb and then decides what class to call, what method with what params. JSPs themselves become servlets, then compiled into bytecode. While it is true that most developers nowadays do not write servlets anymore and do not have to deal with its awful "servletOutputStream.println" peppered everywhere (or templated, but same poo poo really), it is still extremely important for a developer to know what goes on underneath all that magic. Do your homework, learn how to write them and don't forget all of that when you move to greener pastures.

There are times (very rarely thankfully) when I need to accept an (Http)ServletRequest as a parameter to a method or write to an (Http)ServletResponse. They come from the servlet that called me which got them from the application server. I don't think they'll ever be completely gone, for as long as Java will stick around at least.

Its getting much easier as I keep writing them and messing around with them. I think its just the nature of the beast that you can explain it 900 times and it won't make sense until you're elbow deep in the code itself. I don't want to give the impression that I don't think I should have to learn the core/basic stuff before jumping into the shortcuts, I just reserve the right to whine a bit when we have to do everything with arrays for two weeks and arraylists are banned. That said I'm amazing at arrays now and grateful for the ease of arraylists.

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