Monthly Archives: June 2014

Pre-emptive HTTP Basic Authentication with JQuery

In a previous post we looked at setting up basic auth with Spring, and how to call it with a Spring RestTemplate. In this post we will look at how to make an ajax call with JQuery using basic auth. This is a common enough scenario to warrant a popular StackOverflow question, so I thought it warranted a blog post.

The basic code is simple enough: add the appropriate request headers to pre-emptively send the auth information to the jquery request object without waiting for an initial response. In this snippet, request is an object that can be passed to $.ajax().


   request.headers = {
     "Authorization": "Basic " + btoa(credentials.username + ":" + credentials.password)
   };

Next, we can also use an additional function that creates request objects that can be passed to $.ajax().


// this function creates request objects that can be passed to $.ajax()
var ajaxObjectMaker = function(httpMethod, url, requestBody, successCallback, failureCallback) {
   if(typeof(requestBody) !== 'string') {
      requestBody = JSON.stringify(requestBody);
   }
   return {
      'contentType': 'application/json',
      'dataType': 'json',
      'type': httpMethod,
      'url': url,
      'data': requestBody,
      'success': successCallback,
      'error': failureCallback
   };
};
var postJson = ajaxObjectMaker.curry('POST');
var putJson = ajaxObjectMaker.curry('PUT');
var getJson = ajaxObjectMaker.curry('GET');
var deleteJson = ajaxObjectMaker.curry('DELETE');

var addBasicAuth = function(request, username, password) {
   request.headers = {
     "Authorization": "Basic " + btoa(username + ":" + password)
   };
   return request;
 };

This allows us to compose functions as needed to more cleanly include the basic auth header or not. This is a bit cleaner than, say, using a flag to determine whether to add the auth information.


$.ajax(addBasicAuth(putJson(someObjectUrl, someJsonString, onPutObjectSuccess, onPutObjectFailure), username, password));

Happy Authenticating!

Advertisements

1 Comment

Filed under Software Engineering

Migrating Certificates between Java installations

Sometimes you want to upgrade your Java installation from one version to the next, and one thing you need to consider is whether you have imported any custom certificates into the local keystore that you’ll need to migrate. Maybe you are really diligent and keep track, or maybe you import certs as needed and you’re not sure what’s in there (shame on you)! You can’t just copy the cacerts file (where the certs are stored) over because different versions of Java have different certs distributed with them. This post will help you determine what certs you’ve added.

You’ll need to do steps like so:

    1) download a fresh copy of Java
    2) list the certs from its keystore
    3) list the certs in your current keystore
    4) compare the list of certs
    5) for certs you’ve added, extract to a .cert file and import to the new Java

The critical command for listing certs is easy if you’re in Linux. From the JDK installation’s jre/lib/security folder use the keytool:

keytool -list -keystore cacerts | grep "," | sort | awk -F, {'print $1'}

Once you have done this for a fresh copy of Java and your own installation of Java, you can diff these lists with the tool of your choice to find out what you’ve added over the years. The list is by alias, of course.

From there, it’s easy to migrate each cert to the new installation:

keytool -keystore <OldJDK>/jre/lib/security/cacerts -alias myalias -export -file <NewJDK>/jre/lib/security/myalias.cert
keytool -keystore <NewJDK>/jre/lib/security/cacerts -alias myalias -import -file <NewJDK>/jre/lib/security/myalias.cert
rm <NewJDK>/jre/lib/security/myalias.cert

Leave a comment

Filed under Software Engineering

Your job is to code, right? Or is it?

There was a recent back-and forth recently on hacker news: The topic was “your job is not to code” vs the response “your job is to code.” (I recommend reading both of these before continuing. Don’t worry, I’ll wait)

So your job is to code, right? Or is it? As with so many things in life, I think the answer is “It depends.”

The person who says that your job is to do things other code, is probably coming from a consulting shop – notice the mention of convincing customers. A consultant’s job is to look out for the customer, and that means offering coding and non-coding solutions as needed as well as being able to communicate those solutions meaningfully. One might argue that this is a project manager’s job, but the project manager might not be on-site with the customer and does not have the continuous flow of information about the project and the context that the engineer does. In this context I would say that yes, It is very much the engineer’s job to evaluate situations and communicate as needed, and coding could be very much less than 99% of their time. This is also true for a small company or startup where each individual can easily play multiple roles. Guess what: not every software shop is big enough to have a dedicated project manager. In fact, at a startup of two people (say, a CEO and a CTO – not an uncommon situation), then indeed the engineer will be the engineer and the product manager and possibly the salesman. You betcha there is more to that position than coding.

Now, the person who says that your job is to code has a point too, but I think in a different context. In an enterprise software shop (or any software product shop with enough people, eventually) then there IS a project manager, and there is a sales team there is a support and services team, etc. In that context, yes I would say that there is enough specialization given to enough other people that it would be highly ineffective and inefficient for the engineer to do much other than code. If an engineer was constantly reaching out to customers and trying to do the job that dedicated sales and support teams were doing, that engineer would probably get a stern talking to. At least. That’s nice that they want to help, or that they want to learn about the business. But that is not a good use of their time, and in this context their job is to code.

I would finish by saying: Your job is to code if that’s your job. And your job is to do more than code if that’s your job. It all depends on where you work and what the context requires of you.

Leave a comment

Filed under Software Engineering

How To Be A Great Software Developer

This is more of a “link of the week.” I recently read this post called how to be a great software developer. It doesn’t advocate studying the latest hot technologies or trying to become a rock star. Let’s get back to basics and start with things like proper naming, communicating with the team, thinking through a few basic questions as we design our software, and so forth.

Be Great!

Leave a comment

Filed under Software Engineering

Running Spring Boot, Part II

This post will step through setting up a startup script for a spring boot application on Linux. This has been done before, but I think this script is an improvement.

In the previous post we saw how to use boot’s ApplicationPidListener to manage a pid file. Now we will use a script in conjunction with this pid file to manage the running of our application.

There’s not much to see here, it’s just a bash script that uses the pid file to check for the process running or to stop the process. Possible command line options include start, stop, restart, debug, and status. So for example, we could use “app.sh start” and “app.sh stop” to stop the program. A possible future enhancement could be to pass the jar file as an argument, then the specific file name is not tied to this script and it could more easily be used from, say, a gradle build script. I’m not a script master, so any thoughts or suggestions would be welcome!

Here is the script, enjoy!

#!/bin/bash
JARFile="build/libs/boot-0.0.1-SNAPSHOT.jar"
PIDFile="app.pid"
PID="-1"
NOPID="-1"

function print_process {
  echo $(<"$PIDFile")
}

function check_pid_file {
  if [ -f $PIDFile ]
  then
    PID=$(print_process)
    return 0;
  else
    PID="-1"
    return 1;
  fi
}

function check_pid_running {
  check_pid_file
  if [ "$PID" == "$NOPID" ]
  then
    return 1    
  fi
  if ps -p $PID > /dev/null
  then
    return 0
  else
    return 1
  fi
}

case "$1" in

status)
  if check_pid_running
  then
    echo "Process is running (" $PID ")"
  else
    echo "Process not running"
  fi
;;

stop)

if check_pid_running
then
  kill -TERM $PID
  echo -ne "Stopping Process"
  NOT_KILLED=1
  for i in {1..30}; do
    if check_pid_running
    then
      echo -ne "."
      sleep 1
    else
      NOT_KILLED=0
    fi
  done
  echo
  if [ $NOT_KILLED = 1 ]
  then
    echo "Cannot kill process " $PID
    exit 1
  fi
  echo "Process stopped"
else
   echo "Process already stopped"
fi
;;

start)
  if check_pid_running
  then
    echo "Process already running"
    exit 1
  fi
  nohup java -jar $JARFile >/dev/null 2>&1 &
  echo "Process started"
;;

debug)
  if check_pid_running
  then
    echo "Process already running"
    exit 0
  fi
  nohup java -Xdebug -Xrunjdwp:server=y,transport=dt_socket,address=5005,suspend=n -jar $JARFile >/dev/null 2>&1 &

  echo "Process started"
;;

restart)
  $0 stop
  if [ $? = 1 ]
  then
    exit 1
  fi
  $0 start
;;

*)
  echo "Usage: $0 {start|stop|restart|debug|status}"
  exit 1

esac

exit 0


Leave a comment

Filed under Software Engineering