From 6afddf3d85ac103b25c699f2a894ec87c5fea971 Mon Sep 17 00:00:00 2001
From: Joseph Marrero <jmarrero@users.noreply.github.com>
Date: Tue, 23 Aug 2016 15:44:26 -0400
Subject: [PATCH] add check to make sure the license is present (#297)

---
 .../util/license_management.rb                |  8 ++++-
 spec/fixtures/license2.html                   |  1 +
 .../container/liberty_spec.rb                 | 30 +++++++++++++++++++
 3 files changed, 38 insertions(+), 1 deletion(-)
 create mode 100644 spec/fixtures/license2.html

diff --git a/lib/liberty_buildpack/util/license_management.rb b/lib/liberty_buildpack/util/license_management.rb
index 0bd99d388..d368b0898 100644
--- a/lib/liberty_buildpack/util/license_management.rb
+++ b/lib/liberty_buildpack/util/license_management.rb
@@ -30,7 +30,13 @@ def self.check_license(license_uri, license_id)
 
     # The below regex ignores white space and grabs anything between the first occurrence of "D/N:" and "<".
     LibertyBuildpack::Util::Cache::ApplicationCache.new.get(license_uri) do |file|
-      license = file.read.force_encoding('ISO-8859-1').scan(/D\/N:\s*(.*?)\s*\</m).last.first
+      scanned_license = file.read.force_encoding('ISO-8859-1').scan(/D\/N:\s*(.*?)\s*\</m)
+      if scanned_license.empty?
+        raise 'No D/N code found in the license file'
+      else
+        license = scanned_license.first.last
+      end
+
       return license_id == license
     end
   end
diff --git a/spec/fixtures/license2.html b/spec/fixtures/license2.html
new file mode 100644
index 000000000..6bae49303
--- /dev/null
+++ b/spec/fixtures/license2.html
@@ -0,0 +1 @@
+<html><body>Nothing Here<br></body></html>
diff --git a/spec/liberty_buildpack/container/liberty_spec.rb b/spec/liberty_buildpack/container/liberty_spec.rb
index fd6626e04..53276aad6 100644
--- a/spec/liberty_buildpack/container/liberty_spec.rb
+++ b/spec/liberty_buildpack/container/liberty_spec.rb
@@ -2004,5 +2004,35 @@ def run(root, configuration = default_configuration)
 
     end
 
+    describe 'Expect license error if not in license html' do
+
+      def run(root, env = {})
+        set_liberty_fixture('spec/fixtures/wlp-stub.tar.gz')
+
+        Liberty.new(
+          app_dir: root,
+          lib_directory: '',
+          configuration: default_configuration,
+          environment: env,
+          license_ids: { 'IBM_LIBERTY_LICENSE' => '1234-ABCD' }
+        ).compile
+      end
+
+      before do
+        # return license file by default
+        application_cache.stub(:get).and_yield(File.open('spec/fixtures/license2.html'))
+      end
+
+      it 'should raise error' do
+        Dir.mktmpdir do |root|
+          FileUtils.cp_r('spec/fixtures/container_liberty/.', root)
+          env = { 'JBP_CONFIG_LIBERTY' => '[features: blah, app_archive: {feature: [jsp-2.2]}]' }
+          expect { run(root, env) }.to raise_error(/No\ D\/N\ code\ found\ in\ the\ license\ file/)
+
+        end
+      end
+
+    end
+
   end
 end