Optional Path Variables in Spring Web MVC

With a Spring Web MVC controller endpoint in Java you cannot have an optional @PathVariable, so you have to do things old school. In my code I wanted a default sorting mechanism, if the caller of my endpoint didn’t put in any sort parameters. The sort (orderBy) parameters are the fields, and the direction of the sort is specified in an already provided Spring enumeration that I pass a string value to.

The whole *secret* — just pass the HttpServletRequest object into the controller method.  That’s it.

Note my setup is Spring core libraries (and MVC) 3.2.4, Spring Data JPA 1.4.1, and Hibernate for the dialect version 4.2.1 with JPA Api 1.0.1.

Endpoint in the Controller:

@ApiOperation(value=“look for list by sorting”,

     notes= ” two optional parameters: orderBy = {fieldA, fieldB, fieldC} “

          + “direction = {ASC,DESC}”)

@RequestMapping(method = RequestMethod.GET, value = “/look”)

public
@ResponseBody

List<ObjectDto> findSorted(HttpServletRequest request) {

    return dataService.findSorted (request.getParameter(“orderBy”), request.getParameter(“direction”));

}

This calls the service, which builds a Pageable object. I haven’t had a need to refactor the method so I just left the code in the service method for now. There are a few ternaries to check for nulls (note: PMD has a base rule to not reuse method parms as well).

Method in the Service:

private
final
static String DEFAULT_ORDER = “fieldA”;

private
final
static String DEFAULT_DIRECTION =
ASC;

public List<Object> getEntities(Pageable pageable) {

    return objectRepository.findAll(pageable).getContent();

}

public List<ObjectDto> getDTOs(Pageable pageable) {

    return objectMapper.toDTOs(getEntities(pageable), ObjectDto.class);

}

public List< ObjectDto > findSorted (String orderBy, String direction) {

String order = orderBy == null ? DEFAULT_ORDER : orderBy;

String dir = direction == null ? DEFAULT_DIRECTION : direction;


final PageRequest pageable = new PageRequest(

     0, Paging.PAGING_SIZE, new Sort(

     new Order(Direction.fromString(dir), order)));

return objectService.getDTOs (pageable);

}

The mapper code is simple, using commons BeanUtils:

    BeanUtils.copyProperties(fromEntity, toDto);

And the repository code extends JPARepository, so there is already a findAll(pageable) function in the canned interface.

Content Is King

I was looking at the WORLD the other day.  🙂  And thinking about these groups that want a really cool site.  And I realized (after a few retail gigs) that these sites need copywriters — content makers — not more development.

You ever run into one of these kind of sites — the start of a good idea with a post or two and that’s it?

You and I BOTH know we don’t mess around with WYSIWYG when coding;  baaaaad idea.  Bad bad bad.  (Although we do code generation for instance scaffolding — which is in a sense kind of WYSIWYG for developers.  Hmmmmm . . . )

But.  A church, a political group, a neighborhood group here all asked me for help.  I looked and thought . . well christ there’s no effin content.

I mean even the most non-tech person could do the technical piece Web 0.5 beta site like this:

http://maddox.xmission.com/

Or this:

http://www.waynesthisandthat.com/

But not everyone could do all that awesome content.

Content is King.

So I am always looking for tools to make life easier for people, or build them myself.  Like this guy here for instance – http://www.spacejock.com/Software.html.   How awesome.  So what if some are coded in VB6, he made cool stuff people use.

———————————–

Role of Developers?

Think about it.  Why would I ask a business user to learn CSS?  That would be like asking them which spanner to use during a head gasket rebuild.

Extending this idea a bit, I always get into arguments with an architect I know — about something like this topic.    He’s always saying “we need to make things easier” and we talk about Node.js or such.  Yes these are making things like rest api’s more like building content.

But . . .  someone had to develop Node in C language.  That’s where the developer comes in, laying out those rules in a language so that the derivative becomes the palette for the next content creator.  I’ve had the same arguments with “new school” developers — python and etc. — arguing that service busses etc. are from days gone by and then move on to build them . . .in python.  Well, a rewrite of anything works better (my theory of “set in stone” — when you pick your libraries that’s it, it’s over for good for that software).    But to say service busses are old, well, that’s like saying writing is old.  The client activities are not the same as development . . .

Implementors Are The Astronauts

cosmonaut

Hail the Implementor

So it’s down to the wire.  It’s launch day, your managers were barely able to control the unforeseen circumstances but got a launch window.  The operations crew has all of the release notes and their process, and you the developer are sitting there on site or on the phone, VPN’d in to execute the software that you wrote.

You are the implementor, and you are the astronaut of the software world.  Your ass is on the line, you lead the execution of the most important asset your company probably owns.  You got the specs from management, business and the architects and then you went built it and got it ready, and not when the launch comes only *you* can pilot the software.  If there’s a database problem, you fix it.  If there’s a software bug, you patch it and make it go.

In the control room you have your managers, architects, testers and business crew.  They sit in Mission Control.  But the implementors — mostly developers, some DBAs and other tech savy airmen, are the people with the know-how, and the ones that suffer when things break.

Corporations are missing a whole career path

I don’t know why it is that everyone thinks the next step after developer is architect.  It’s not.  The next step after being an artist is not art critic or art gallery owner, its just to become a better artist.

This year at a gig I heard a very narrow minded conversation about the hierarchy of a company — they had different levels of “architect.”  Usually as a developer in a corporate stack you can go two paths – architect or management.    The actual act of developing is considered a lesser quality.  Anyway, the conversation went on about “after lead developer you become junior architect, then, mid-level architect and finally senior architect.  After that is CIO level4 . . .” blah blah.  Bobcat Scout to Wolf Scout to Bear Scout to Junior Birdman.  Pay grades are not skill competency.  This team was also majorly subject to the Peter Principle we all know so well.

Being  Lead Developer — or a developer of any sort — means you make architectural decisions as well.  It is perhaps the most important step — the execution.  There are great architects out there; they look at the big direction of the company and say something like “Alfresco plus J2EE plus Guice plus Postgre SQL  plus Cassandra equals our future” or things like that.  Then comes the nasty little details.

For instance, we had set up a build server and ran into a brick wall with Mercurial versioning and 64 vs 32 bit plugin handling of Sonar.  Developers handled that.  On another project we had to write Hibernate overrides because the persistence libraries didn’t work so well with our database choice.  This didn’t come into notice until after we had deployed, due to another dependency on the servers.  I lost sleep that night (and I am a huge proponent of  having dev environments = production, but many have fought against that idea in the past).    On another project some architect mixed the newest Struts, PrimeFaces, JQuery and a really bad choice of Spring together.  Developers had to deal with that.

Corporations lose a ton of knowledge when they promote and do not reward the people who know how to do something, looking at management of that know how as more important.  Well, these day with PMing a separate career path, the management can’t manage development at all.

A Guy I Knew

I worked with a guy who had a PhD in Chemical Engineering and had massive command of the Java language.  He wrote beautifully designed libraries, and sat at a small desk in our developer area.  My feeling was, compared to the fast talking architect (one of the 10% hands on- paper types) he provided four times as much value, yet was paid less.  A manager lamented “too bad this guy doesn’t present well, he could move up.”  In the meantime he wrote the data libraries and sharding code that supported 100’s of developers, and led a small team to handle it.    They should have just gave him the title “architect” to pay him more and let him be one of the venerated hands-on architects, but they never did. I always will think of this guy as the model lead implementor.

When coaches coach, you still have to have quarterbacks, pitchers, goalies, and shortstops.   And it’s like that in software.  No one in pro sports wants to become a coach, they’d rather keep playing for as long as they can.  True developers and true implementors are like that: the challenge of creativity and giving to the world never dies in them.

The implementor is the astronaut, the brave one, the creative one.  I guess as implementors we all architect, manage, and requirement drill — we do it all no matter how they try to divide the labor.  The industry can try to get around this with labels and pay grads, but the reality sits true: implementors are the astronauts.

IP Agreements

Modern Intellectual Property Agreements just seem to be a waste of time.  In fact, I’ve seen some doozies in my lifetime I’ve refused to sign.

The worst, by far, was for a consulting company that wanted to own ALL THE SOCIAL CONTACTS I made during a contract.  Phone numbers, Facebook listings, LinkedIn acceptances, Twitter watchings.  Since I am a developer and not a salesperson — and I am not sure how sales handles this since contacts are everything — contacts allow me to improve my programming and make me a better asset on the market.  The result of trying to own a developer’s networking is an attempt at stopping them from improving, in fact, its saying “end your career now because you can’t meet anyone without telling us.”

So say you are onsite.  You go to a general meeting about company business, and someone you aren’t working with is interested in your Groovy Group outside of work.  But since you met them *there* — that IP company would want your connection.  But it’s BS.  YOu might not even be doing Groovy there, or maybe you both kayak and that’s how you met and the company didn’t teach you to kayak.  Or maybe it is work related, but your contract is up, and that connection can get you another gig but you have to turn over his information to this IP company.  It’s bad all around.

I feel the same about most general IP agreements.  Certainly, I understand that a company wants to protect its technology.  I will do my darndest to protect their business if they’ve asked me to work for them, and I’ll sign an agreement to protect it.  But, I’m not selling out my intellectual freedom for a buck.  It’s career death.

Even some Consulting companies, that *only* have headhunters and salespeople (the “contact” episode was like this) want you to sign a general agreement like this.  Let’s see — a company that does no technology at all except placement wants to own all my rights to compilers, algorithms, and inventions I work during a gig they arranged to a real tech company?  And these agreements are written so grayly that if I learned HTML5 on the contract they arranged, then after that at a non-related gig created a widget with it they would want to own it “because I had obtained the knowledge on their watch.”  I am totally serial about this.

The Spice, Will Not Flow (Consequences)

Great companies, or maybe used to be great, encouraged innovation and break-offs of employees.  For instance, HP used to have a great policy of letting employees go to pursue new inventions and may have even backed them with capital.  A spin-off of Medtronic, Guidant, was due to an invention of a lithium battery for a pacemaker.

We aren’t talking about idea theft, we are talking about the combination of a special person, with special experiences, in special circumstance — the right time and person and place — who then invents something great.  I do not know how a company can own this.

As I perused on particular agreement recently, I thought — gosh I’d have to give up my meetup group I started because anything contemporary I talk about on a current contract is an idea owned by this new company.  If I saw an improvement at work, that I could ask the manager “you mind if we add this to the open source plugin?”  If that was stopped, then any new ideas and use cases for improvement, heck, even free labor on the problem would stop.

And what about just personal improvement?  I do mostly Java.  I use Java at home.  How do we separate all that?

What Constitutes Something Owned By A Company?

In my opinion, the final product is what is a company’s property.  If you string together Alfresco, some J2EE libraries, Spring, a bunch of CSS branding particular to that company, some algorithms and workflows — well you can’t copy them unless they agree to it.  Data domains of course, for the most part, are proprietary.  Of course, since we are all facing the same problems and something like a Rails framework comes along, well then, that’s not the company’s property.

But interesting things happen.  One thing is — the Jenkins/Hudson fork.  Hudson used to be open source, Oracle bought it; an open source  Jenkins fork was created and everyone moved to it.   So how was it we didn’t see a huge lawsuit on that one?  of course I suspect there have been lawsuits somewhere.

In a small list of things I’ve worked on, include a free market health care application, product information sites for electronics, power failure monitoring software, health care record processing, law library software, clinical examination room software, toxic substances databases, retail sites city licensing and regulatory systems, medical device information systems; just for starters.   those whole systems belong to those companies.  Maybe there is a particular algorithm, like a Monte Carlo implementation, that they own.

But what about all the content repositories, databases, class upon class of millions of lines of code, annotations, implementations, automation scripts — all those techniques across all business I figured out or fixed or worked on . . . standard Ant implementations, java upgrades, operating system debugs, domain processing languages.  And some company comes along and says it owns all that accumulated information, knowledge, and techniques I developed over the years but just the stuff during their particular contract.

If companies want to stop competition, then, they will try to force these out of control, generalized IP agreements.  They will also stop innovation.

I don’t know what can give a business the edge.  It could be a piece of timely technology implementation.  But, I remember a company that was using Node to do concurrent, real time updates — and they thought that they had done this made the idea theirs.  No, just the implementation is theirs.  A lot of  other companies are doing this too because that’s what the tool does.    If an employee working on the same project moves from one company to another, should they just not bring in their experience?  If not, where is progress, and what makes a developer more salable over time?

A book I often quote is Plato’s Theatetus.  The lesson in that was, the parts do not equal the whole.  I would say, the developer owns the parts, but the company owns the whole.

Linux Tip: List Directories by Size – du

Use the du comand to list your directories by size:

user@ubuntu:/boot$ du -hs *
632K abi-2.6.32-21-generic
120K config-2.6.32-21-generic
1.5M grub
7.7M initrd.img-2.6.32-21-generic
164K memtest86+.bin
1.7M System.map-2.6.32-21-generic
4.0K vmcoreinfo-2.6.32-21-generic
3.9M vmlinuz-2.6.32-21-generic

In this, ‘grub’ is a directory in the location. This command has a lot of options but usually I am just interested in this.

Why Java Developers Don’t Have Pretty Portfolios

Searching around on some of the Job Boards sites, I noticed that the more JavaScript that gets posted, the more the call out to see if people have projects or code posted out in GitHub.  I do, just a little, out in BitBucket and have thought of doing this often but as a mainly java developer I run into  problemstrying to keep a public face with enterprise developmentThe content you are trying to access is only available to members. Sorry.

Mobile Tethering

Recently I just switched cell phone companies to get a lot more talk, text and data at a much reduced cost which is something I need right now.  (Side note: I was with the other provider maybe 15 years and they were *quite* curt with me on my departure.   Cringe . . . )

Anyway, I had to look into using my cell as a mobile “hotspot.”  I prefer carriers that can use GSM phones (you can now deduce my move) so I can buy unlocked phones to get new features, or replace broken ones for cheaper than the insurance cost.    My current phone is a Huawei u8800 and its a cheap 4G phone I bought for $150 last year and runs for about $114 via Amazon prime today.  Its a great backup.  It runs a lower version of Andriod, Froyo or something, but I don’t care.  It replaced an slick Motorola that I had consistent problems with (I loved the Motorola but it was sooo undependable).

Anyway, back to these hotspots.  In the old days I could hook a USB line to my phone and use it as a modem.  Same thing here.  I am currently looking at two pices of software –

  • FoxFi
  • Tether

Both are comparable for my uses, both have free licenses with limited (like 1/2 hour use then shuts off).  FoxFi is a bit cheaper, Tether makes a few more support gurantees.

Setup

Setup is easy.  There’s an app for your Android (or whatever OS) phone, and an app for your computer (I use Windows 7).  Install was painless.

Use Cases

My network somehow blocks me from using an unlocked phone as a WiFi or Bluetooth hotpot, but it works with a USB tether.  But  it works fine.

Something to keep in mind though:  if you are doing this, are you really going to need to be streaming tons of data the whole time?  Probably not .

For me, I can start it up, do some emails and a Dropbox sync, and then stop.  Unless I am on vacation in a remote area I cannot see a use for me to need this all the time.  Also, most places have WiFi so you won’t need to use it.

Also, even a 4G LTE network is a lot slower than most WiFi.  So do you really want to live like that?  I can almost hear the modem noises going off.

———————————————–

Still, this fits the bill quite nicely for my needs of occasional mobility.  A salesperson might need it a bit more, in which case throw these companies some cash (which I may do soon once I decide on which software I like).

Last to note, one of the software sites said they could not guarantee your cell provider wouldn’t find a way to shut off this type of tethering/hotspot solution.  I understand, and also think its too bad.  We can’t find new use cases without blowing away the old barriers.  I mean, just now some of the older providers are coming up with features like “get a new phone once a year instead of every two.”  I have no idea why they think that is a feature or a revelation, we’ve all been talking about it for 20 years.  I guess — why does a dog lick his balls?

Workhorse Developers

A workhorse developer is someone who is an exemplary coworker and a dependable coder.   They are the ones who may not get into the design fray because they find it too stressing, they may not have the talent to design, or they may just look on their work as JAJ (just a just).  The content you are trying to access is only available to members. Sorry.

Oh Those Interesting Developers

Good Artists Copy, Great Artists Steal.  -Pablo Picasso

I’m a developer and I can say, first hand, the most difficult thing for a developer to learn is to be open minded and questioning.  I know, a lot of companies are always looking for developers who will “push the envelope” or “think outside the box” but the reality is there are very few people who do that.  The content you are trying to access is only available to members. Sorry.

Fibonacci Memoization

In this age its important for developers to understand  the use of  caching tools and no-sql databases to performance scale your applications.

One such technique is a simple little idea called “memoization” — which is a heuristic of  remembering the result of a previous calculation in a recursive methodology so the calculation doesn’t have to be executed again.

Here’s little recursive Fibonacci algorithm that doesn’t use memoization (in my case the strategy is a simple HashMap cache). I ran the sequence to 40 levels.

Non-cached

Run time: 88.60717 seconds


public BigInteger fibCalc(int calcLevel) {
     if (calcLevel%10 == 0) {System.out.println("Calculation Level: " + calcLevel);}
     if (calcLevel == 1) {
          return bi(0);
     } else if (calcLevel == 2 || calcLevel == 3) {;
          return bi(1);
     } else {
          BigInteger rtrn = fibCalc(calcLevel-1).add(fibCalc(calcLevel - 2));
          return rtrn;
     }
}

Cached-Memoization

Run time: 0.00204 seconds


public HashMap<Integer,BigInteger> memoization = new HashMap<Integer,BigInteger>();

public BigInteger fibCalc(int calcLevel) {
      if(null != memoization.get(calcLevel)) {
           return memoization.get(calcLevel);
      } else {
      if (calcLevel%10 == 0) {System.out.println("Calculation Level: " + calcLevel);}
      if (calcLevel == 1) {
           memoization.put(calcLevel,bi(0));
           return bi(0);
      } else if (calcLevel == 2 || calcLevel == 3) {
           memoization.put(calcLevel,bi(1));
           return bi(1);
      } else {
           BigInteger rtrn = fibCalc(calcLevel-1).add(fibCalc(calcLevel - 2));
           memoization.put(calcLevel,rtrn);
           return rtrn;
      }
 }

Wow! What a difference. From about 89 seconds to *almost nothing*!!!

On different job sites the architects have always investigated larger caching strategies, but this goes to show you a little ole developer can take a programming idea and leverage it for good.  Of course, it should be a reasonable application . . . .