Ticket #24446: 24446-2.patch

File 24446-2.patch, 2.0 KB (added by GerdP, 12 days ago)

new method to truncate a string to a given maximum of grapheme clusters

  • src/org/openstreetmap/josm/actions/upload/ApiPreconditionCheckerHook.java

     
    7373                                        Long.toString(osmPrimitive.getId())
    7474                                )
    7575                        );
    76                         osmPrimitive.put(key, Utils.shortenString(value, Tagged.MAX_TAG_LENGTH));
     76                        osmPrimitive.put(key, Utils.reduceCodePoints(value, Tagged.MAX_TAG_LENGTH));
    7777                        continue;
    7878                    }
    7979                    JOptionPane.showMessageDialog(MainApplication.getMainFrame(),
     
    106106        }
    107107        return true;
    108108    }
     109
    109110}
  • src/org/openstreetmap/josm/tools/Utils.java

     
    20492049    public static boolean checkCodePointCount(String s, int maxLen) {
    20502050        return getCodePointCount(s) <= maxLen;
    20512051    }
     2052
     2053    /**
     2054     * Truncate a string to the given maximum number of code points.
     2055     * @param s the string
     2056     * @param num the maximum number of code points
     2057     * @return s if it is null or the number of code points is within the given limit, else a string with the first {@code num}
     2058     * code points
     2059     * @since xxx
     2060     */
     2061    public static String reduceCodePoints(String s, int num) {
     2062        if (checkCodePointCount(s, num))
     2063            return s;
     2064        String[] parts = s.split("\\b{g}"); // split along grapheme cluster boundaries
     2065        StringBuilder shorter = new StringBuilder();
     2066        for (int i = 0; i < num; i++) {
     2067            shorter.append(parts[i]);
     2068        }
     2069        return shorter.toString();
     2070    }
     2071
    20522072}