And seeing this post in preview mode reminds me of my Todo to fix my WordPress layout….
Java8 Lambda Functions – anti-side effect programming
In some coding recently, I thought I saw an opportunity to explore Java8’s support for lambda expressions. I basically had a function I needed to call, once with one set of data, and once with another. I could repeat the logic (hey, it’s only 2 calls), I could write a method, or, maybe this is a candidate for a lambda expression.
In the below code, pre method or lambdas, the basic logic is that I’m examining a string to see if it’s wrapped in ‘/*’ ‘*/’. If it is, I’m stripping those off and returning that it was wrapped.
boolean isWrapped1 = false, isWrapped2 = false; // first, strip off any comment wrappers, so we can appropriately parse if (response2.endsWith("*/")) { response2 = response2.substring(0, response2.length() - 2); if (response2.startsWith("/*")) { response2 = response2.substring(2); } isWrapped2 = true; } if (response1.endsWith("*/")) { response1 = response1.substring(0, response1.length() - 2); if (response1.startsWith("/*")) { response1 = response1.substring(2); } isWrapped1 = true; }
Written in lambda style…
boolean isWrapped1 = false, isWrapped2 = false; Function<String, Boolean> isWrapped = s -> { if (s.endsWith("*/")) { s = s.substring(0, s.length() - 2); if (s.startsWith("/*")) { s = s.substring(2); return true; } } return false; }; isWrapped1 = isWrapped.apply(response1); isWrapped2 = isWrapped.apply(response2);
Now, the rub… and one which I realize would bite me in a method implementation, as well… I’m relying in my first implementation on the side effect that the string gets stripped of the ‘/*’. There’s no side-effects for strings when dealt with in a function. The original string goes in, you can muck with it all you want inside, and the original string is _still_ the one there on the outside.
Thinking it through, what I need to do is consider writing a 2nd lambda, so the code would look something more like this:
Function isWrapped {.. }; Function unwrap {.. }; isWrapped1 = isWrapped.apply(response1); if (isWrapped1) { response1 = unwrap(response1); } isWrapped2 = isWrapped.apply(response2); if (isWrapped2) { response2 = unwrap(response2); }
Using strings clearly helped enforce no side-effect programming here… which, practically, makes for a better functional approach, at least per my understanding. Since I don’t intend to make those functions visible in any other place than within the invoking method, it appears to be a decently good pattern for DRY, without necessarily adding to the interface footprint of my class. Almost creates an approach of something even more private than private…
DropWizard, Jersey, and /* */
Occasionally I write posts just to let me hold onto a thought process, moreso than to help someone else find a solution. The below fits that profile – feel free to ignore, unless you’re really interested in poking around DropWizard.
Goal: wrap JSON responses with /* */. This is to support a hacky version of CSRF. Bleah.
Starting point: DropWizard 0.7.1, which used Jersey 1.18
Attempts:
- JacksonMessageBodyProvider: just couldn’t get it to hook in correctly
- Jersey ContainerResponseFilter: Hook in via DropWizard’s environment.jersey().getResourceConfig().getContainerResponseFilters().add( … do guice injection here ). No ready way to rewrite response. Can append headers. Could apparently adjust request information going in. But not JSON formatted result coming out
- Servlet Filter: can append /* foo */ (haven’t yet grabbed JSON), but that’s added to { “foo”: “bar”, “bar”: “foo”}/* foo */, rather than wrapping. Did have to turn off gzip in DropWizard, else the stream was already closed. (Couldn’t figure out a way to inject my filter in ahead of the Gzip actions…) In this case, though, httpResponse.resetBuffer() doesn’t succeed, as the stream is already committed.
Final solution: use WriteInterceptor: https://jersey.java.net/documentation/latest/filters-and-interceptors.html#d0e9712 – but those exist in Jersey 2, which isn’t supported until DropWizard 0.8.0… Note: Jersey 2 changes its dependency injection approach to use HK2 instead of its previous own approach, which meant that my nifty wiring in of Spring security had to be redone / reworked.
Outcome: Whoever decided to protect from JSON execution through wrapping the JSON with comment blocks, you threw me a number of curve balls. But I did in fact prevail, and now have an interceptor which wraps my responses appropriately, _if_ there’s not a certain flag and the user making the request isn’t a privileged user. Ugh. All nicely unit-tested, using Mockito to let me cover the conditions for the request, etc. This is code I need to hang onto….
Accomplishment for the night – kudos to WordPress!
Accomplishment for the night: a WordPress update from 3.5.1 to 4.1.1. In most systems, that’s a well-planned out affair. The combination of a ‘what the heck’ attitude this evening by me, and a push-button upgrade by WordPress means that I made a major upgrade with nothing more than an XML export without suffering any (at least thusfar noticed) undue effects. Well done, WordPress! No login to my hosting environment to rescue my database, no even import from the afore-mentioned XML export. My theme came over successfully, even though I’ve hacked it up… Again, well done! May my development efforts handle software upgrades as successfully as you have!
Doh! TDD to the rescue
TDD to the rescue. Stupid error of the day debugged, after a bit of head scratching…
Three things go into a collection, but only two come out and hit the final log file. I can see them go in, so the comparison logic itself is working just fine…
Just running through the debugger wouldn’t have made me notice. It took figuring out why my Mockito verify set wasn’t satisfied. Aha! Poor choice of map key. Issue resolved. But it still took me 1/2 an hour of poking through. The insertion was happening as part of a Consumer action for an Iterable.forEach, which was a new construct for me. Because it was new, I of course assumed I didn’t “get” how it worked. Nuh-uh – that part worked just fine. Once I actually paid attention to where I was stashing my info, I realized when putting in a second item for key ‘foo’, the first item disappears, if you’re stashing in a Map. Just a ‘doh!’ moment. But certain I wouldn’t have noticed it for quite a while if I hadn’t written out those verify() invocation checks.
If I won $5 million dollars…
A business blog recently described a list of interview questions HR might ask you to try to get inside your head. Some of them I’ve actually used on interviews with candidates. I’m not an HR person, but hey, seeing if someone can describe the technical projects they’re most proud of helps me to see that they take pride in their work, as well as what they consider to be something worth bragging about.
The question I’d never asked anything near is what someone would do if they won $5 million dollars. I’m certain: I’d be done working for anyone in particular. I’d keep doing technical work, but I’d only do that which particularly interested me. That’s not a very reasonable scenario for working for someone else… there is this thing about keeping the customers happy and paying the bills that is worthy and valuable. But without the need of an ongoing paycheck, I could definitely see geeking out on open source projects, working as a technical contributor for a non-profit, etc…
I’d actually be interested were someone to ask me the $5 mil question… their response to _my_ response would help me understand how big they think their impact on my life ought to be overall… So, a highly useful question if it helps us each winnow the other out.
Password cracking
Apparently I’ve been inadvertently running a password cracker library while trying to test out building my VirtualBox image. Couldn’t figure out why I was getting files with extensions of .hwm, .pwd, and .pwi, rather than getting some sort of console output when I ran ‘packer build packer.json’ Now I know . And I hope that the new alias added for packer in my .bashrc helps me explain, if and when the security team visits.
Serendipity in information and ideas
Just realized a theme key for me in how I browse the internet, with my ten Chrome tabs open. Twitter is like Pinterest is like Facebook, in that in each case I’m getting a stream of ideas or images or information that are related to my interests or people I’m interested in. No one theme or person fills that pipeline overwhelmingly, which is how I enjoy it.
Instagram is like LinkedIn is like reading a particular RSS feed: they have their uses, but are not among my preferred areas to spend a lot of time. Too much is coming from the same authors or points of view. I don’t get that ah hah! moment of the choice of many rabbit trails.
In both worlds (creative chaos vs. stuck on point), they’re merely an entry point to see if I’d like to figure out more, either through the links on that site or through my own hunts off to the side.
Douglas Adams
I’ve been on a Douglas Adams kick lately. His birthday celebration recently caused me to look up a bit of his quotable stuff… a few below.
A learning experience is one of those things that says, ‘You know that thing you just did? Don’t do that.
We are stuck with technology when what we really want is just stuff that works.
You’re paid a lot and you’re not happy, so the first thing you do is buy stuff that you don’t want or need—for which you need more money.
These are all from a book called ‘The Salmon of Doubt‘, which was published posthumously. To discover a new Douglas Adams book with such quotable items in it – pure delight.
Digging around, I further found that Douglas Adams was once a writer for Dr. Who, and that apparently the 3rd book (‘Life, the Universe and Everything’) of ‘The Hitchhiker’s Guide to the Galaxy’ was originally intended to be a Dr. Who story. MORE delight.
I now quote the prologue to ‘The Salmon of Doubt’, from the words of Douglas Adams describing himself: “I wanted to be a writer-performer like the Pythons. In fact I wanted to be John Cleese and it took me some time to realise that the job was in fact taken.” I wish I had known this gentleman.
TLS, OpenSSL, and Go – oh my
The Go programming language has the distinct advantage of compiling into a binary, which means I can compile for a particular target OS, bring my compiled binary onto my machine and it “just works”. Except when it doesn’t. In this case, it didn’t as we made HTTPS calls. The handshake between the two servers was failing, with the obtuse statement of ‘remote error: handshake failure‘. To the Go team’s credit, apparently all they get back from the server is that the handshake failed. No further detail, nothing to help track down root cause. I’ve spent two days in curl and openssl, trying to figure out why a GET which worked in curl didn’t work from either our Go code or via an openssl invocation.
Takeaways:
* openssl gives much more information about the SSL handshake than does curl, even with -v
* I have a greater appreciation of Java’s ability to work in enterprise (i.e. legacy) systems. Never really had to worry about this in Java.
* Go finally did the job, when given enough information about TLS settings. We got to stay away from ciphers, thankfully, though did a brief exposure to the number of cyphers in existence, as we investigated that potential path.
I’ll end up posting a snippet somewhere in our corporate environment about how to make 2-way SSL handshake actually work there, given what we discovered. Turns out, Go makes some assumptions that just don’t hold true in certain environments. Thankfully, I broke the case before ending up in Wireshark land. openssl s_client did the job… Corporate doesn’t really like sniffers being deployed on the network….