From b75c77d2699b971e7b44a46d52b5696fee3efd31 Mon Sep 17 00:00:00 2001 From: BobHanson Date: Thu, 28 May 2020 15:56:38 -0500 Subject: [PATCH] JAL-3636 ColorUtils cleaner test for hex color --- src/jalview/util/ColorUtils.java | 17 ++++++++++++----- src/jalview/util/StringUtils.java | 25 +++++++++++++++++++++++++ 2 files changed, 37 insertions(+), 5 deletions(-) diff --git a/src/jalview/util/ColorUtils.java b/src/jalview/util/ColorUtils.java index 60129fb..c1feeee 100644 --- a/src/jalview/util/ColorUtils.java +++ b/src/jalview/util/ColorUtils.java @@ -219,12 +219,15 @@ public class ColorUtils colour = colour.trim(); Color col = null; - try - { - int value = Integer.parseInt(colour, 16); - col = new Color(value); - } catch (NumberFormatException ex) + if (colour.length() == 6 && StringUtils.isHexString(colour)) { + try + { + int value = Integer.parseInt(colour, 16); + col = new Color(value); + } catch (NumberFormatException ex) + { + } } if (col == null) @@ -252,6 +255,10 @@ public class ColorUtils return col; } + + public static boolean couldBeHexColor(String n) { + return (n.length() > 0 && "abcdefABCDEF".indexOf(n.charAt(0)) >= 0); + } /** * Constructs a colour from a text string. The hashcode of the whole string is diff --git a/src/jalview/util/StringUtils.java b/src/jalview/util/StringUtils.java index 1f114a8..c6af7f0 100644 --- a/src/jalview/util/StringUtils.java +++ b/src/jalview/util/StringUtils.java @@ -568,4 +568,29 @@ public class StringUtils } return enc; } + + /** + * Answers true if the string is not empty and consists only of digits, or + * characters 'a'-'f' or 'A'-'F', else false + * + * @param s + * @return + */ + public static boolean isHexString(String s) + { + int j = s.length(); + if (j == 0) + { + return false; + } + for (int i = 0; i < j; i++) + { + int c = s.charAt(i); + if (!(c >= '0' && c <= '9' || c >= 'a' && c <= 'f' || c >= 'A' && c <= 'F')) + { + return false; + } + } + return true; + } } -- 1.7.10.2