]> gerrit.simantics Code Review - simantics/platform.git/blob - bundles/org.simantics.utils/src/org/simantics/utils/strings/StringUtils.java
Migrated source code from Simantics SVN
[simantics/platform.git] / bundles / org.simantics.utils / src / org / simantics / utils / strings / StringUtils.java
1 /*******************************************************************************\r
2  * Copyright (c) 2007, 2010 Association for Decentralized Information Management\r
3  * in Industry THTH ry.\r
4  * All rights reserved. This program and the accompanying materials\r
5  * are made available under the terms of the Eclipse Public License v1.0\r
6  * which accompanies this distribution, and is available at\r
7  * http://www.eclipse.org/legal/epl-v10.html\r
8  *\r
9  * Contributors:\r
10  *     VTT Technical Research Centre of Finland - initial API and implementation\r
11  *******************************************************************************/\r
12 package org.simantics.utils.strings;\r
13 \r
14 import java.text.DecimalFormat;\r
15 import java.text.NumberFormat;\r
16 import java.text.ParseException;\r
17 import java.util.Locale;\r
18 \r
19 public class StringUtils {\r
20 \r
21     private static NumberFormat usFormat = DecimalFormat.getInstance(Locale.US);\r
22     public final static String ZERO_LENGTH_STRING = ""; //$NON-NLS-1$\r
23 \r
24     /**\r
25      * Ensures that a string is not null. Converts null strings into empty\r
26      * strings, and leaves any other string unmodified. Use this to help\r
27      * wrap calls to methods that return null instead of the empty string.\r
28      * Can also help protect against implementation errors in methods that\r
29      * are not supposed to return null. \r
30      * \r
31      * @param input input string (may be null)\r
32      * @return input if not null, or the empty string if input is null\r
33      */\r
34     public static String safeString(String input) {\r
35         if (input != null) {\r
36             return input;\r
37         }\r
38 \r
39         return ZERO_LENGTH_STRING;\r
40     }\r
41     \r
42 \r
43     public static double safeDouble(String input) {\r
44 \r
45         if(input == null) return Double.NaN;\r
46         \r
47         try {\r
48 \r
49             String usafied = input.replace(",", ".");\r
50             Number number = usFormat.parse(usafied);\r
51             return number.doubleValue();\r
52             \r
53         } catch (ParseException e) {\r
54             \r
55             return Double.NaN;\r
56             \r
57         }\r
58         \r
59     }\r
60     \r
61     public static String repeat(String pattern, int repeatCount)\r
62     {\r
63         StringBuilder sb = new StringBuilder(pattern.length() * repeatCount);\r
64         for (int i=0; i<repeatCount; i++)\r
65             sb.append(pattern);\r
66         return sb.toString();\r
67     }\r
68     \r
69 }\r