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