Ticket #11651: strip.patch

File strip.patch, 15.6 KB (added by shinigami, 10 years ago)

patch

  • src/org/openstreetmap/josm/tools/Utils.java

    ### Eclipse Workspace Patch 1.0
    #P JOSM
     
    3939import java.util.Arrays;
    4040import java.util.Collection;
    4141import java.util.Collections;
    42 import java.util.HashSet;
    4342import java.util.Iterator;
    4443import java.util.List;
    4544import java.util.Locale;
    46 import java.util.Set;
    4745import java.util.concurrent.ExecutorService;
    4846import java.util.concurrent.Executors;
    4947import java.util.regex.Matcher;
     
    149147     * Filter a collection by (sub)class.
    150148     * This is an efficient read-only implementation.
    151149     */
    152     public static <S, T extends S> SubclassFilteredCollection<S, T> filteredCollection(Collection<S> collection, final Class<T> klass) {
     150    public static <S, T extends S> SubclassFilteredCollection<S, T> filteredCollection(Collection<S> collection,
     151            final Class<T> klass) {
    153152        return new SubclassFilteredCollection<>(collection, new Predicate<S>() {
    154153            @Override
    155154            public boolean evaluate(S o) {
     
    210209     * @param data Message parameters, optional
    211210     * @throws AssertionError if the condition is not met
    212211     */
    213     public static void ensure(boolean condition, String message, Object...data) {
     212    public static void ensure(boolean condition, String message, Object... data) {
    214213        if (!condition)
    215             throw new AssertionError(
    216                     MessageFormat.format(message, data)
    217             );
     214            throw new AssertionError(MessageFormat.format(message, data));
    218215    }
    219216
    220217    /**
     
    222219     */
    223220    public static int mod(int a, int n) {
    224221        if (n <= 0)
    225             throw new IllegalArgumentException("n must be <= 0 but is "+n);
     222            throw new IllegalArgumentException("n must be <= 0 but is " + n);
    226223        int res = a % n;
    227224        if (res < 0) {
    228225            res += n;
     
    380377        CheckParameterUtil.ensureParameterNotNull(in, "in");
    381378        CheckParameterUtil.ensureParameterNotNull(out, "out");
    382379        if (!out.exists() && !out.mkdirs()) {
    383             Main.warn("Unable to create directory "+out.getPath());
     380            Main.warn("Unable to create directory " + out.getPath());
    384381        }
    385382        File[] files = in.listFiles();
    386383        if (files != null) {
     
    427424                    if (file.isDirectory()) {
    428425                        deleteDirectory(file);
    429426                    } else if (!file.delete()) {
    430                         Main.warn("Unable to delete file: "+file.getPath());
     427                        Main.warn("Unable to delete file: " + file.getPath());
    431428                    }
    432429                }
    433430            }
     
    441438     * @param c the closeable object. May be null.
    442439     */
    443440    public static void close(Closeable c) {
    444         if (c == null) return;
     441        if (c == null)
     442            return;
    445443        try {
    446444            c.close();
    447445        } catch (IOException e) {
     
    455453     * @param zip the zip file. May be null.
    456454     */
    457455    public static void close(ZipFile zip) {
    458         if (zip == null) return;
     456        if (zip == null)
     457            return;
    459458        try {
    460459            zip.close();
    461460        } catch (IOException e) {
     
    529528                try {
    530529                    Thread.sleep(1);
    531530                } catch (InterruptedException ex) {
    532                     Main.warn("InterruptedException in "+Utils.class.getSimpleName()+" while getting clipboard content");
     531                    Main.warn("InterruptedException in " + Utils.class.getSimpleName()
     532                            + " while getting clipboard content");
    533533                }
    534534            } catch (NullPointerException e) {
    535535                // JDK-6322854: On Linux/X11, NPE can happen for unknown reasons, on all versions of Java
     
    573573        return toHexString(byteDigest);
    574574    }
    575575
    576     private static final char[] HEX_ARRAY = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
     576    private static final char[] HEX_ARRAY = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd',
     577            'e', 'f' };
    577578
    578579    /**
    579580     * Converts a byte array to a string of hexadecimal characters.
     
    630631                    break;
    631632                }
    632633            }
    633             if (parentless == null) throw new RuntimeException();
     634            if (parentless == null)
     635                throw new RuntimeException();
    634636            sorted.add(parentless);
    635637            deps.remove(parentless);
    636638            for (T key : deps.keySet()) {
     
    637639                deps.remove(key, parentless);
    638640            }
    639641        }
    640         if (sorted.size() != size) throw new RuntimeException();
     642        if (sorted.size() != size)
     643            throw new RuntimeException();
    641644        return sorted;
    642645    }
    643646
     
    737740            throw new IllegalArgumentException("Invalid HTTP url");
    738741        }
    739742        if (Main.isDebugEnabled()) {
    740             Main.debug("Opening HTTP connection to "+httpURL.toExternalForm());
     743            Main.debug("Opening HTTP connection to " + httpURL.toExternalForm());
    741744        }
    742745        HttpURLConnection connection = (HttpURLConnection) httpURL.openConnection();
    743746        connection.setRequestProperty("User-Agent", Version.getInstance().getFullAgentString());
     
    792795        if (in == null) {
    793796            return null;
    794797        }
    795         return new BZip2CompressorInputStream(in, /* see #9537 */ true);
     798        return new BZip2CompressorInputStream(in, /* see #9537 */true);
    796799    }
    797800
    798801    /**
     
    824827        // Positions the stream at the beginning of first entry
    825828        ZipEntry ze = zis.getNextEntry();
    826829        if (ze != null && Main.isDebugEnabled()) {
    827             Main.debug("Zip entry: "+ze.getName());
     830            Main.debug("Zip entry: " + ze.getName());
    828831        }
    829832        return zis;
    830833    }
     
    838841    public static URLConnection setupURLConnection(URLConnection connection) {
    839842        if (connection != null) {
    840843            connection.setRequestProperty("User-Agent", Version.getInstance().getFullAgentString());
    841             connection.setConnectTimeout(Main.pref.getInteger("socket.timeout.connect", 15)*1000);
    842             connection.setReadTimeout(Main.pref.getInteger("socket.timeout.read", 30)*1000);
     844            connection.setConnectTimeout(Main.pref.getInteger("socket.timeout.connect", 15) * 1000);
     845            connection.setReadTimeout(Main.pref.getInteger("socket.timeout.read", 30) * 1000);
    843846        }
    844847        return connection;
    845848    }
     
    883886        }
    884887        if (Main.isDebugEnabled()) {
    885888            try {
    886                 Main.debug("REQUEST: "+ connection.getRequestProperties());
     889                Main.debug("REQUEST: " + connection.getRequestProperties());
    887890            } catch (IllegalStateException e) {
    888891                Main.warn(e);
    889892            }
     
    891894        return connection;
    892895    }
    893896
     897    private static char[] DEFAULT_STRIP = { '\u200B', '\uFEFF' };
     898
     899
    894900    /**
    895901     * An alternative to {@link String#trim()} to effectively remove all leading and trailing white characters, including Unicode ones.
    896902     * @param str The string to strip
     
    901907     * @since 5772
    902908     */
    903909    public static String strip(final String str) {
    904         return strip(str, null);
     910        if (str == null || str.isEmpty()) {
     911            return str;
     912        }
     913        return strip(str, DEFAULT_STRIP);
    905914    }
    906915
    907916    /**
     
    913922     * @since 8435
    914923     */
    915924    public static String strip(final String str, final String skipChars) {
     925
    916926        if (str == null || str.isEmpty()) {
    917927            return str;
    918928        }
    919         // create set with chars to skip
    920         Set<Character> skipSet = new HashSet<>();
    921         // '\u200B' (ZERO WIDTH SPACE character) needs to be handled manually because of change in Unicode 6.0 (Java 7, see #8918)
    922         skipSet.add('\u200B');
    923         // same for '\uFEFF' (ZERO WIDTH NO-BREAK SPACE)
    924         skipSet.add('\uFEFF');
    925         if (skipChars != null) {
    926             for (char c : skipChars.toCharArray()) {
    927                 skipSet.add(c);
    928             }
    929         }
     929
     930        return strip(str, stripChars(skipChars));
     931    }
     932
     933    private static String strip(final String str, final char[] skipChars) {
     934
    930935        int start = 0;
    931936        int end = str.length();
    932937        boolean leadingSkipChar = true;
    933938        while (leadingSkipChar && start < end) {
    934939            char c = str.charAt(start);
    935             leadingSkipChar = Character.isWhitespace(c) || Character.isSpaceChar(c) || skipSet.contains(c);
     940            leadingSkipChar = Character.isWhitespace(c) || Character.isSpaceChar(c) || stripChar(skipChars, c);
    936941            if (leadingSkipChar) {
    937942                start++;
    938943            }
    939944        }
    940945        boolean trailingSkipChar = true;
    941         while (trailingSkipChar && end > start+1) {
    942             char c = str.charAt(end-1);
    943             trailingSkipChar = Character.isWhitespace(c) || Character.isSpaceChar(c) || skipSet.contains(c);
     946        while (trailingSkipChar && end > start + 1) {
     947            char c = str.charAt(end - 1);
     948            trailingSkipChar = Character.isWhitespace(c) || Character.isSpaceChar(c) || stripChar(skipChars, c);
    944949            if (trailingSkipChar) {
    945950                end--;
    946951            }
    947952        }
     953
    948954        return str.substring(start, end);
    949955    }
    950956
     957    private static char[] stripChars(final String skipChars) {
     958        if (skipChars == null || skipChars.isEmpty()) {
     959            return DEFAULT_STRIP;
     960        }
     961
     962        char[] chars = new char[skipChars.length() + 2];
     963        chars[0] = '\u200B';
     964        chars[1] = '\uFEFF';
     965        skipChars.getChars(0, skipChars.length(), chars, 2);
     966
     967        return chars;
     968    }
     969
     970    private static boolean stripChar(final char[] strip, char c) {
     971
     972        for (char s : strip) {
     973            if (c == s) {
     974                return true;
     975            }
     976        }
     977
     978        return false;
     979    }
     980
    951981    /**
    952982     * Runs an external command and returns the standard output.
    953983     *
     
    962992            Main.debug(join(" ", command));
    963993        }
    964994        Process p = new ProcessBuilder(command).start();
    965         try (BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream(), StandardCharsets.UTF_8))) {
     995        try (BufferedReader input = new BufferedReader(
     996                new InputStreamReader(p.getInputStream(), StandardCharsets.UTF_8))) {
    966997            StringBuilder all = null;
    967998            String line;
    968999            while ((line = input.readLine()) != null) {
     
    9891020        }
    9901021        File josmTmpDir = new File(tmpDir, "JOSM");
    9911022        if (!josmTmpDir.exists() && !josmTmpDir.mkdirs()) {
    992             Main.warn("Unable to create temp directory "+josmTmpDir);
     1023            Main.warn("Unable to create temp directory " + josmTmpDir);
    9931024        }
    9941025        return josmTmpDir;
    9951026    }
     
    10161047        // Is it less than 1 hour ?
    10171048        if (elapsedTime < MILLIS_OF_HOUR) {
    10181049            final long min = elapsedTime / MILLIS_OF_MINUTE;
    1019             return String.format("%d %s %d %s", min, tr("min"), (elapsedTime - min * MILLIS_OF_MINUTE) / MILLIS_OF_SECOND, tr("s"));
     1050            return String.format("%d %s %d %s", min, tr("min"), (elapsedTime - min * MILLIS_OF_MINUTE)
     1051                    / MILLIS_OF_SECOND, tr("s"));
    10201052        }
    10211053        // Is it less than 1 day ?
    10221054        if (elapsedTime < MILLIS_OF_DAY) {
    10231055            final long hour = elapsedTime / MILLIS_OF_HOUR;
    1024             return String.format("%d %s %d %s", hour, tr("h"), (elapsedTime - hour * MILLIS_OF_HOUR) / MILLIS_OF_MINUTE, tr("min"));
     1056            return String.format("%d %s %d %s", hour, tr("h"),
     1057                    (elapsedTime - hour * MILLIS_OF_HOUR) / MILLIS_OF_MINUTE, tr("min"));
    10251058        }
    10261059        long days = elapsedTime / MILLIS_OF_DAY;
    1027         return String.format("%d %s %d %s", days, trn("day", "days", days), (elapsedTime - days * MILLIS_OF_DAY) / MILLIS_OF_HOUR, tr("h"));
     1060        return String.format("%d %s %d %s", days, trn("day", "days", days), (elapsedTime - days * MILLIS_OF_DAY)
     1061                / MILLIS_OF_HOUR, tr("h"));
    10281062    }
    10291063
    10301064    /**
     
    10341068     * @param positionList a list of positions
    10351069     * @return a human readable representation
    10361070     */
    1037     public static String getPositionListString(List<Integer> positionList)  {
     1071    public static String getPositionListString(List<Integer> positionList) {
    10381072        Collections.sort(positionList);
    10391073        final StringBuilder sb = new StringBuilder(32);
    10401074        sb.append(positionList.get(0));
     
    10591093        return sb.toString();
    10601094    }
    10611095
    1062 
    10631096    /**
    10641097     * Returns a list of capture groups if {@link Matcher#matches()}, or {@code null}.
    10651098     * The first element (index 0) is the complete match.
     
    11581191        StringBuilder sb = new StringBuilder(url.substring(0, url.indexOf('?') + 1));
    11591192
    11601193        for (int i = 0; i < query.length(); i++) {
    1161             String c = query.substring(i, i+1);
     1194            String c = query.substring(i, i + 1);
    11621195            if (URL_CHARS.contains(c)) {
    11631196                sb.append(c);
    11641197            } else {
     
    12451278        if (value != null) {
    12461279            String old = System.setProperty(key, value);
    12471280            if (!key.toLowerCase(Locale.ENGLISH).contains("password")) {
    1248                 Main.debug("System property '"+key+"' set to '"+value+"'. Old value was '"+old+"'");
     1281                Main.debug("System property '" + key + "' set to '" + value + "'. Old value was '" + old + "'");
    12491282            } else {
    1250                 Main.debug("System property '"+key+"' changed.");
     1283                Main.debug("System property '" + key + "' changed.");
    12511284            }
    12521285            return old;
    12531286        }
     
    12791312     * @throws IOException if any IO errors occur.
    12801313     * @since 8347
    12811314     */
    1282     public static void parseSafeSAX(InputSource is, DefaultHandler dh) throws ParserConfigurationException, SAXException, IOException {
     1315    public static void parseSafeSAX(InputSource is, DefaultHandler dh) throws ParserConfigurationException,
     1316            SAXException, IOException {
    12831317        long start = System.currentTimeMillis();
    12841318        if (Main.isDebugEnabled()) {
    1285             Main.debug("Starting SAX parsing of "+is+" using "+dh);
     1319            Main.debug("Starting SAX parsing of " + is + " using " + dh);
    12861320        }
    12871321        newSafeSAXParser().parse(is, dh);
    12881322        if (Main.isDebugEnabled()) {
    1289             Main.debug("SAX parsing done in " + getDurationString(System.currentTimeMillis()-start));
     1323            Main.debug("SAX parsing done in " + getDurationString(System.currentTimeMillis() - start));
    12901324        }
    12911325    }
    12921326
     
    12981332     * @return {@code true} if the filename has one of the given extensions
    12991333     * @since 8404
    13001334     */
    1301     public static boolean hasExtension(String filename, String ... extensions) {
     1335    public static boolean hasExtension(String filename, String... extensions) {
    13021336        String name = filename.toLowerCase(Locale.ENGLISH);
    13031337        for (String ext : extensions) {
    1304             if (name.endsWith("."+ext.toLowerCase(Locale.ENGLISH)))
     1338            if (name.endsWith("." + ext.toLowerCase(Locale.ENGLISH)))
    13051339                return true;
    13061340        }
    13071341        return false;
     
    13151349     * @return {@code true} if the file's name has one of the given extensions
    13161350     * @since 8404
    13171351     */
    1318     public static boolean hasExtension(File file, String ... extensions) {
     1352    public static boolean hasExtension(File file, String... extensions) {
    13191353        return hasExtension(file.getName(), extensions);
    13201354    }
    13211355}