001/*
002 * IzPack - Copyright 2001-2005 Julien Ponge, All Rights Reserved.
003 * 
004 * http://www.izforge.com/izpack/
005 * http://developer.berlios.de/projects/izpack/
006 * 
007 * Copyright 2003 Marc Eppelmann
008 * 
009 * Licensed under the Apache License, Version 2.0 (the "License");
010 * you may not use this file except in compliance with the License.
011 * You may obtain a copy of the License at
012 * 
013 *     http://www.apache.org/licenses/LICENSE-2.0
014 *     
015 * Unless required by applicable law or agreed to in writing, software
016 * distributed under the License is distributed on an "AS IS" BASIS,
017 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
018 * See the License for the specific language governing permissions and
019 * limitations under the License.
020 */
021
022package com.izforge.izpack.util;
023
024import java.io.File;
025import java.util.ArrayList;
026
027/**
028 * A extended Java Implementation of Pythons string.replace()
029 * 
030 * @author marc.eppelmann@gmx.de
031 */
032public class StringTool
033{
034
035    // ~ Constructors
036    // *********************************************************************************
037
038    /**
039     * Default Constructor
040     */
041    public StringTool()
042    {
043        super();
044    }
045
046    // ~ Methods
047    // **************************************************************************************
048
049    /**
050     * Standalone callable Test method
051     * 
052     * @param args Commandline Args
053     */
054    public static void main(String[] args)
055    {
056        System.out.println("Test: string.replace(abc$defg,$de ,null ):"
057                + StringTool.replace("abc$defg", "$de", null, true));
058    }
059
060    /**
061     * Replaces <b>from</b> with <b>to</b> in given String: <b>value</b>
062     * 
063     * @param value original String
064     * @param from Search Pattern
065     * @param to Replace with this
066     * 
067     * @return the replaced String
068     */
069    public static String replace(String value, String from, String to)
070    {
071        return replace(value, from, to, true);
072    }
073
074    /**
075     * Replaces <b>from</b> with <b>to</b> in given String: <b>value</b>
076     * 
077     * @param value original String
078     * @param from Search Pattern
079     * @param to Replace with this
080     * @param aCaseSensitiveFlag set to true be case sensitive.
081     * 
082     * @return the replaced String
083     */
084    public static String replace(String value, String from, String to, boolean aCaseSensitiveFlag)
085    {
086        if ((value == null) || (value.length() == 0) || (from == null) || (from.length() == 0)) { return value; }
087
088        if (to == null)
089        {
090            to = "";
091        }
092
093        if (!aCaseSensitiveFlag)
094        {
095            from = from.toLowerCase();
096        }
097
098        String result = value;
099        int lastIndex = 0;
100        int index = value.indexOf(from);
101
102        if (index != -1)
103        {
104            StringBuffer buffer = new StringBuffer();
105
106            while (index != -1)
107            {
108                buffer.append(value.substring(lastIndex, index)).append(to);
109                lastIndex = index + from.length();
110                index = value.indexOf(from, lastIndex);
111            }
112
113            buffer.append(value.substring(lastIndex));
114            result = buffer.toString();
115        }
116
117        return result;
118    }
119
120    /**
121     * Normalizes a Windows or Unix Path.
122     * 
123     * Reason: Javas File accepts / or \ for Pathes. Batches or ShellScripts does it not!
124     * 
125     * TODO: implement support for MAC < MacOSX
126     * 
127     * @param destination
128     * @param fileSeparator a target-system fileseparator
129     * 
130     * @return the normalized path
131     */
132    public static String normalizePath(String destination, String fileSeparator)
133    {
134        String FILESEP = (fileSeparator == null) ? File.separator : fileSeparator;
135
136        destination = StringTool.replace(destination, "\\", "/");
137
138        // all occs of "//" by "/"
139        destination = StringTool.replace(destination, "//", "/");
140
141        destination = StringTool.replace(destination, ":", ";");
142        destination = StringTool.replace(destination, ";", ":");
143
144        destination = StringTool.replace(destination, "/", FILESEP);
145
146        if ("\\".equals(FILESEP))
147        {
148            destination = StringTool.replace(destination, ":", ";");
149
150            // results in "C;\" instead of "C:\"
151            // so correct it:
152            destination = StringTool.replace(destination, ";\\", ":\\");
153        }
154
155        // Convert the file separator characters
156        return (destination);
157    }
158
159    /**
160     * Normalizes a mixed Windows/Unix Path. Does Only work for Windows or Unix Pathes Reason:
161     * Java.File accepts / or \ for Pathes. Batches or ShellScripts does it not!
162     * 
163     * @param destination accepted mixed form by java.File like "C:/a/mixed\path\accepted/by\Java"
164     * 
165     * @return the normalized Path
166     */
167    public static String normalizePath(String destination)
168    {
169        return (normalizePath(destination, null));
170    }
171    
172    /**
173     * Converts an String Array to a space separated String w/o any check 
174     * @param args The StringArray
175     * @return the space separated result.
176     */
177    public static String stringArrayToSpaceSeparatedString( String[] args )
178    {
179      String result = "";
180        for( int idx = 0; idx < args.length; idx++ )
181        {
182          result += args[ idx ]+ " ";
183        }
184      return result;
185    }
186
187    public static String getPlatformEncoding()
188    {
189        // TODO Auto-generated method stub
190        return System.getProperty( "file.encoding" );
191    }
192    public static String UTF16()
193    {
194        return "UTF-16";
195    }
196
197    /**
198     * Transforms a (Array)List of Strings into a printable Stringlist
199     * 
200     * @param aStringList
201     * 
202     * @return a printable list
203     */
204    public static String stringArrayListToString(ArrayList aStringList)
205    {
206        StringBuffer temp = new StringBuffer();
207    
208        for (int idx = 0; idx < aStringList.size(); idx++)
209        {
210            temp.append(aStringList.get(idx) + "\n");
211        }
212    
213        return temp.toString();
214    }
215
216    /**
217     * True if a given string starts with the another given String
218     * 
219     * @param str The String to search in
220     * @param prefix The string to search for
221     * 
222     * @return True if str starts with prefix
223     */
224    public static boolean startsWith(String str, String prefix)
225    {
226        return (str != null) && str.startsWith(prefix);
227    }
228
229    /**
230     * The same as startsWith but ignores the case.
231     * 
232     * @param str The String to search in
233     * @param prefix The string to search for
234     * 
235     * @return rue if str starts with prefix
236     */
237    public static boolean startsWithIgnoreCase(String str, String prefix)
238    {
239        return (str != null) && (prefix!=null) && str.toUpperCase().startsWith(prefix.toUpperCase());
240    }
241    
242}