Doorgaan naar hoofdcontent

Posts

Optional and continuing

 So, some thing I've bothered myself with. We have a common idiom where we do something like: var result = doSometThing(); if(result == null) {   return handleEmptyCase(); } // continue logic with result     With Optional, that has changed, somewhat... var result = doSometThing(); if(result.isEmpty()) {   return handleEmptyCase(); } var actualResult = result.get(); // continue logic with actualResult   But this is... messy.   We could go functional on it:   return doSomeThing()   .map(result -> doWithActualResult(result))   .orElse( () -> return handleEmptyCase();)   But this isn't it either. We now have the else clause handling our special exit, which is not what we prefer, we prefer to exit early.  So, sometimes an optional is... not as nice...    Something interesting is: https://stackoverflow.com/questions/73248935/using-optionals-is-it-possible-to-return-early-on-ifpresent-without-adding-a     ...

On SSL certificate generation

 So, more stuff I always forget... how to properly generate SSL certs. Well, easiest is with openssl (of course) Something like: openssl req -new -newkey rsa:2048 -nodes  -sha256 -subj "/C=NL/ST=Utrecht/L=Utrecht/O=Cooperatieve Rabobank U.A./OU=RASS Groep ICT/CN=my-common-name.host.nl" -keyout somename-prod.key -out somename-prod.csr   That can get you a certificate sign request (csr) and the appropriate key.   Of course, you want to then import those keys into a keystore. The trick to doing that is to convert it to a pkcs12 format where it can have the certificate and the key combined.   openssl pkcs12 -export -inkey somename-prod.key -in somename-prod.rabobank.nl.crt -out somename-prod.p12  Note that the crt is the signed certificate, acquired through getting the csr generated above approved..   This p12 file you can import using something like KeyStore Explorer.   After that, you can also append the root certificates of the original cert, to en...

Junit 5 never runs in maven

We've had it so, so often. Junit 5 is a bitch to run in maven. First there were issues with the surefire plugin. Make sure that is updated. Then there were issues with the versions you need to use together. Whelp, that was all set up right. And of course... still no junit 5 A fun thing was seeing this: [INFO] --- maven-surefire-plugin:3.1.2:test (default-test) @ my-project --- [INFO] Using auto detected provider org.apache.maven.surefire.junit4.JUnit4Provider   Yeah, that's not how it should go. This forces the junit 4 provider... Which is not the junit 5 generic one. After a lot of digging, it turns out that surefire determines which provider to use... through some magic from the classpath. Of course, nowhere is there a junit4 dependency. They're all gone. Well... Except... Except... The platform dependency   < dependency > < groupId >org.junit.platform</ groupId > < artifactId >junit-platform-launcher</ artifactId > < version ...

Windows batch scripting god ( java runtime switch)

 I am a batch scripting god. After a lot of pain, I managed to create a script which allows me to switch jvm's easily. For posterity, and my own flex skills, the script: @echo off rem set your local path to all the JVM's here. set jvmdir=c:\code\apps\jvms if NOT EXIST %jvmdir% goto invaliddir rem a little bit of manipulation rem first we remove everything before the jvms dir call set __temp=%%path:*%jvmdir%\=%% rem then we determine everything that follows after the next slash set __lastbit=%__temp:*\=% rem then we remove that lastbit, leaving only the entire directory and a \ at the end. call set __currentpath=%%__temp:%__lastbit%=%% rem then we remove the \ at the end set __currentjvm=%__currentpath:\=% if "%~1"=="" goto missingarg if NOT EXIST %jvmdir%\%1 goto unknowndir set __currentpath=%jvmdir%\%__currentjvm% set __replacement=%jvmdir%\%1 call SET path=%%path:%__currentpath%=%__replacement%%% CALL SET JAVA_HOME=%%JAVA_HOME:%__currentpath%=%__replacemen...

Java sux with regexes

 Java supports regexes right? Nothing to it! that is so nice about it Only after 15 years, I find out that it does have performance problems. https://bugs.java.com/bugdatabase/view_bug.do?bug_id=5050507  Is a bug for regexes in java. Of course, they're rare. But how did I hit it? Well, doing stuff you shouldn't of course. In this case, parsing Json, by searching for a value of a certain key. That's straightforward, right? "key"\s:\s"([^"]+)" Well, it would be nice like that, but there's this tiny exception... the value can contain quotes as well. Okay, so we exclude them. Numerous posts tell you how to do it. The trick is to use an or, in essence saying: 'the string \" OR any character which is not a "`  We can see that in action  here All languages support it.   but.... not java. No, it has problems with these groups. It gives stack overflows. And it's a known fact. So, is this the end? I thought so. But then, I started diggi...

Thread binding data

In an application we work with threads, but for ease of usage, we may not want to pass around the same objects all the time. It helps in our method signature, signifying the objects we perfrom our function on, but sometimes, it feels rather unnecessary. For example, let's assume we have a request-id which we recieve, and want to pass to all outgoing requests. Or we want to prevent a certain query being performed multiple times by caching the result. These are request-scoped data items. Since every request runs in it's own thread, we can use threadlocals. In spring, we can do a bit better, by using a ThreadLocalTargetSource https://dzone.com/articles/an-alternative-approach-to-threadlocal-using-sprin-1 This allows us to get a thread-instance per request, which can be injected into our services without any knowledge of caching occuring. In essence, we create some sort of thread-tied global object. This is, of course, something which can be easily abused, and can lead...

Spring overriding beans

So we have a bean of type FunkyClass and we want to override it. How? Well, we have the @Ordered annotation, which allows us to define the order when there are multiple beans of the same type. However, what happens when we only want one? Spring does not automatically take the highest order. To override a bean, you can use the @Primary annotation :)

git partial revert

So, apparently I removed an entire directory. A long time ago in the history. But I want it back. I want it back for good. git checkout <commit id> -- <path-to-directory> Will checkout the directory nicely, thus restoring it. Also for files, etc.

And along comes a visitor

Every time I look at a visitor pattern, I wonder, why. What is the use of this thing? Especially, when I consider modularity, I just don't understand. Let's say I have different objects: Door Engine Wheel Blinker Trunk Chair (all of them are CarParts , of course) When there's a cross-cutting concern which needs to be handled, the discussion arises: do you modify all the objects (say, they need a getCustomerValue, getBuildValue, getProductionTime, getSupplier, getRequiredComponents , for example, since we're using these parts in a factory and we need those), or maybe do you want all Supplier code to be in the same spot (since else knowledge of all suppliers gets scattered around, and you'd want it in a single spot) For the last, the code would get pretty messy. it would look something like Suppliers.getSupplierOf(Carpart part) { if(part instanceOf Door) {   return "supplierOne"; } if( part instanceOf Engine) {    if(((...

xml modification

So I wanted to modify some xml. And yes, that might mean xslt. However, the modification wasn't nice... in Java, it was fine, but to do that in xslt... rather not. So, I ventured into the world of 'how do you call java from xslt'. Of course, you can. Of course, you need to use Saxon. Of course, then you need a PAYED version of Saxon ... Sigh. I guess I'll stick to flat xslt and a lot of work then. Just to remember how it *can* be done: <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:imro="http://www.geonovum.nl/imro/2012/1.1" xmlns:gml="http://www.opengis.net/gml/3.2"  xmlns:java="http://xml.apache.org/xalan/java" exclude-result-prefixes="java" >     <xsl:output method="xml" encoding="utf-8" indent="yes"/>     <!-- Identity template : copy all text nodes, elements and attributes -->       <xsl:template match=...

Your own security annotation

So, I'm on a small project which has some multi-tenancy. Simply put; user A can see the bananas on his trees, and user B can see the bananas on his own trees... but they can't see each others. But it's restfull, so ideally, you'd call something like /tree/{tree-id}/bananas And since we know who's executing the call (since it's authenticated), we can verify that it's user A calling us, and then check which trees he can see. If he's trying to be sneaky, and does a restcall with a treeId of B, a security violation should occur. Okay, so how do we do that? Well, the application has a controller for that, and we'd want to secure it there. So, assume we have the following code: public List<Banana> getBananasOfTree(String tree) Since it's supposed to be annotated, we'd use something like this: @RequestMapping("/tree/{tree-id}/bananas") @Secured // or some other requirement  public List<Banana> getBananasOfTree(@Pat...

OSGI insights without sonar

So I was on a project without sonar. Oh my. Well, it was an OSGI project, so the problems couldn't be that bad, right? But how good were they (and what things were bad?) I found Stan4j , a code analysis tool for eclipse, which draws nice graphs and can handle osgi pretty well it seems. Now I can see that dependencies/bundle names aren't properly aligned (even though OSGI doesn't complain), etc.

So that security thing

Well, web security is tricky. However, Mozilla can go to the rescue! They have the observatory ( https://observatory.mozilla.org/) It can scan a webpage for you and give it a bit of a rating. Its just a static check, on headers, etc. But it shows how far you've narrowed down your attack surface. Of course, it doesn't say anything against actual attacks (get ZAP for that)

Data sharding and handling it in code

So I was at a project where data was somewhat sharded. We had a customer, which was part of a customer database (accessible by webservice calls), however, we had some additional customer data. This led to the (I think somewhat unfortunate) situation where the application reasoned from their own business object, and, when necessary, retrieved data from the relation system. I feel this is flawed, ideally the entirety of the customer data should be invisible to the business logic of the application. Where I normally would like to have an anemic domain model, this data sharding makes it hard. Let's say you have relation R, and our extended data S. In our application, we want to reason about RS (or at least, not have to make that distinction). So maybe S has some additional attribute which may (or may not) be filled, depending on whether R is available or not. That sounds like a nice idea, but everywhere when R is necessary (and S is available), R needs to be retrieved. And that is ...

Articles flash: subclassing builders, method/class/package sizes

A quickie: When you have a class with a builder, and you want to subclass that class, you also want to subclass the builder. But things get nasty quickly, as your subtypes' builder doesn't work nicely. A good solution from Stackoverflow: http://stackoverflow.com/questions/17164375/subclassing-a-java-builder-class Also, a thingie on sizes. When is a class too big, when is a method too big, when is a package kinda big: https://www.javacodegeeks.com/ 2012/12/rule-of-30-when-is-a- method-class-or-subsystem-too- big.html Although I don't agree on the rule of thirty (I think it's too big. Maybe 30/10/10 is more appropriate), it's a good start, and has some nice references.

Learing good Code styles

Yesterday I had one of those days where all of a sudden I'm shown my code isn't as good as it should be. Oh dear. So, something to learn, because they were right . Two things: Static methods Static methods are 'horrible'. After discussing about the why, finally a good argument came up: They inhibit extension! You cannot override them, and usually it is a sign of functional programming style. That may not be bad per se, but being able to override functions is a good thing. So: BE CAREFUL TO MARK METHODS STATIC. USUALLY, IT CAN BE DONE BETTER. Strategies Strategies are cool. However, I tend to push into that direction. That my not be necessarily bad, but strategies are only for compile-time decisions. Ther is a difference between implementing classes which are injected, and thereby selected at 'compile time', and actual runtime by using, say an abstract factory to determine which strategy to use for the current run. So, note to self: only name an i...

Stateless session beans - an oxymoron

So I had a discussion about stateless session beans and them containing state. Coming from spring, I expected stateless to mean no state what so ever. This is because the default scope for beans in spring is Singleton. This allows beans to be shared (and wired) on application startup, ensuring that no real bean pool management is necessary. The container decides to use separate beans for injection, or all the same, since there is no real 'pool' to speak of. Compare this to EJB, which has a stateless session bean. This compares with a stateful session bean. A stateful session bean contains the state through the entire session. A stateless session bean does not. However, a stateless session bean can contain state. Stateless session beans are request scoped , meaning that any state they have they can access within the request. This, of course, comes from EJB's Stateful and Stateless EJB's of old, where it was made that way. Spring made sure that stateless = no ...

JPA and transactions

So I was working with JPA and transactions. Consider the following: In bean 1, with implicit TX 1, managed entities are loaded/created,and returned in bean 2, with implicit TX 2, entities are modified in bean 3, with NO TX, bean 1 is called, and the results are passed to bean 2. and bean 4 is similar to bean 3, but with it's own transaction, TX3 What happens when bean 3 finishes: are the entities updated? What happens when bean 4 finishes, are the entities updated? The answer to this is simple; entities are managed through a persistance context. That context is tied to the transaction. So in bean 2, there is a difference. When called from bean 3, it runs in a different transaction then bean 1, and thus a different persistance context, and thus the entities are not managed 'by this transaction'.When called from bean 4, it all runs in the same transaction, TX3, and the results are persisted.

Minify javascript, etc.

Well, I've always felt that minify was useless if you had gzip on. Turns out, I'm not the only one saying that, and people have put their money where their mouth is. So there's actually quite a bit of reserach on it. http://stackoverflow.com/questions/807119/gzip-versus-minify https://css-tricks.com/the-difference-between-minification-and-gzipping/ Long story short: gzip is better then minify. gzip AND minify is even better. advantages of minify are that it can create a big ball of javascript, requiring only one GET reqeust