Ticket #8902: patterns.diff

File patterns.diff, 67.0 KB (added by shinigami, 11 years ago)

precompiled patterns

  • src/org/openstreetmap/josm/actions/PasteTagsAction.java

     
    1212import java.util.HashMap;
    1313import java.util.List;
    1414import java.util.Map;
     15import java.util.regex.Pattern;
    1516
    1617import org.openstreetmap.josm.Main;
    1718import org.openstreetmap.josm.command.ChangePropertyCommand;
     
    6061
    6162        /**
    6263         * Replies true if the source for tag pasting is heterogeneous, i.e. if it doesn't consist of
    63          * {@link OsmPrimitive}s of exactly one type
     64         * {@link org.openstreetmap.josm.data.osm.OsmPrimitive}s of exactly one type
    6465         */
    6566        protected boolean isHeteogeneousSource() {
    6667            int count = 0;
     
    135136        }
    136137
    137138        /**
    138          * Pastes the tags from a homogeneous source (the {@link Main#pasteBuffer}s selection consisting
    139          * of one type of {@link OsmPrimitive}s only).
     139         * Pastes the tags from a homogeneous source (the {@link org.openstreetmap.josm.Main#pasteBuffer}s selection consisting
     140         * of one type of {@link org.openstreetmap.josm.data.osm.OsmPrimitive}s only).
    140141         *
    141142         * Tags from a homogeneous source can be pasted to a heterogeneous target. All target primitives,
    142143         * regardless of their type, receive the same tags.
     
    241242
    242243    }
    243244
     245    private static final Pattern ACTION_PERFORMED_PATTERN = Pattern.compile("(\\d+,)*\\d+");
     246
    244247    @Override
    245248    public void actionPerformed(ActionEvent e) {
    246249        Collection<OsmPrimitive> selection = getCurrentDataSet().getSelected();
     
    249252            return;
    250253
    251254        String buf = Utils.getClipboardContent();
    252         if (buf == null || buf.isEmpty() || buf.matches("(\\d+,)*\\d+")) {
     255        if (buf == null || buf.isEmpty() || ACTION_PERFORMED_PATTERN.matcher(buf).matches()) {
    253256            pasteTagsFromJOSMBuffer(selection);
    254257        } else {
    255258            // Paste tags from arbitrary text
     
    285288        List<PrimitiveData> directlyAdded = Main.pasteBuffer.getDirectlyAdded();
    286289        if (directlyAdded==null || directlyAdded.isEmpty()) return false;
    287290
    288         PasteTagsAction.TagPaster tagPaster = new PasteTagsAction.TagPaster(directlyAdded, selection);
     291        TagPaster tagPaster = new TagPaster(directlyAdded, selection);
    289292        List<Command> commands = new ArrayList<Command>();
    290293        for (Tag tag : tagPaster.execute()) {
    291294            commands.add(new ChangePropertyCommand(selection, tag.getKey(), "".equals(tag.getValue()) ? null : tag.getValue()));
  • src/org/openstreetmap/josm/actions/downloadtasks/DownloadOsmChangeCompressedTask.java

     
    22package org.openstreetmap.josm.actions.downloadtasks;
    33
    44import java.util.concurrent.Future;
     5import java.util.regex.Pattern;
    56
    67import static org.openstreetmap.josm.tools.I18n.tr;
    78
     
    1718 */
    1819public class DownloadOsmChangeCompressedTask extends DownloadOsmChangeTask {
    1920
     21
    2022    @Override
    2123    public String[] getPatterns() {
    2224        return new String[]{"https?://.*/.*\\.osc.(gz|bz2?)"};
     
    2628    public String getTitle() {
    2729        return tr("Download Compressed OSM Change");
    2830    }
    29    
     31
     32    private static final Pattern LOAD_URL_PATTERN = Pattern.compile("https?://.*/.*\\.osc.bz2?");
     33
    3034    /**
    3135     * Loads a given URL
    3236     * @param new_layer {@code true} if the data should be saved to a new layer
     
    3943            @Override
    4044            protected DataSet parseDataSet() throws OsmTransferException {
    4145                ProgressMonitor subTaskMonitor = progressMonitor.createSubTaskMonitor(ProgressMonitor.ALL_TICKS, false);
    42                 if (url.matches("https?://.*/.*\\.osc.bz2?")) {
     46                if (LOAD_URL_PATTERN.matcher(url).matches()) {
    4347                    return reader.parseOsmChangeBzip2(subTaskMonitor);
    4448                } else {
    4549                    return reader.parseOsmChangeGzip(subTaskMonitor);
  • src/org/openstreetmap/josm/actions/downloadtasks/DownloadOsmCompressedTask.java

     
    22package org.openstreetmap.josm.actions.downloadtasks;
    33
    44import java.util.concurrent.Future;
     5import java.util.regex.Pattern;
    56
    67import static org.openstreetmap.josm.tools.I18n.tr;
    78
     
    3839            ProgressMonitor progressMonitor) {
    3940        return null;
    4041    }
    41    
     42
     43    private static final Pattern LOAD_URL_PATTERN = Pattern.compile("https?://.*/.*\\.osm.bz2?");
     44
    4245    /**
    4346     * Loads a given URL
    4447     * @param new_layer {@code true} if the data should be saved to a new layer
     
    5154            @Override
    5255            protected DataSet parseDataSet() throws OsmTransferException {
    5356                ProgressMonitor subTaskMonitor = progressMonitor.createSubTaskMonitor(ProgressMonitor.ALL_TICKS, false);
    54                 if (url.matches("https?://.*/.*\\.osm.bz2?")) {
     57                if (LOAD_URL_PATTERN.matcher(url).matches()) {
    5558                    return reader.parseOsmBzip2(subTaskMonitor);
    5659                } else {
    5760                    return reader.parseOsmGzip(subTaskMonitor);
  • src/org/openstreetmap/josm/actions/downloadtasks/DownloadOsmTask.java

     
    2121import org.openstreetmap.josm.gui.PleaseWaitRunnable;
    2222import org.openstreetmap.josm.gui.layer.Layer;
    2323import org.openstreetmap.josm.gui.layer.OsmDataLayer;
    24 import org.openstreetmap.josm.gui.progress.NullProgressMonitor;
    2524import org.openstreetmap.josm.gui.progress.ProgressMonitor;
    2625import org.openstreetmap.josm.io.BoundingBoxDownloader;
    2726import org.openstreetmap.josm.io.OsmServerLocationReader;
     
    4140    private static final String PATTERN_OVERPASS_API_XAPI_URL = "http://.*/xapi\\?.*\\[@meta\\].*";
    4241    private static final String PATTERN_EXTERNAL_OSM_FILE     = "https?://.*/.*\\.osm";
    4342
     43    private static final Pattern PATTERN_OVERPASS_API_URL_COMPILED = Pattern.compile(PATTERN_OVERPASS_API_URL);
     44    private static final Pattern PATTERN_OVERPASS_API_XAPI_URL_COMPILED = Pattern.compile(PATTERN_OVERPASS_API_XAPI_URL);
     45    private static final Pattern PATTERN_OSM_API_URL_COMPILED = Pattern.compile(PATTERN_OSM_API_URL);
     46
    4447    protected Bounds currentBounds;
    4548    protected DataSet downloadedData;
    4649    protected DownloadTask downloadTask;
     
    7376    }
    7477
    7578    /**
    76      * Replies the {@link DataSet} containing the downloaded OSM data.
    77      * @return The {@link DataSet} containing the downloaded OSM data.
     79     * Replies the {@link org.openstreetmap.josm.data.osm.DataSet} containing the downloaded OSM data.
     80     * @return The {@link org.openstreetmap.josm.data.osm.DataSet} containing the downloaded OSM data.
    7881     */
    7982    public DataSet getDownloadedData() {
    8083        return downloadedData;
     
    8992     * Asynchronously launches the download task for a given bounding box.
    9093     *
    9194     * Set <code>progressMonitor</code> to null, if the task should create, open, and close a progress monitor.
    92      * Set progressMonitor to {@link NullProgressMonitor#INSTANCE} if progress information is to
     95     * Set progressMonitor to {@link org.openstreetmap.josm.gui.progress.NullProgressMonitor#INSTANCE} if progress information is to
    9396     * be discarded.
    9497     *
    9598     * You can wait for the asynchronous download task to finish by synchronizing on the returned
    96      * {@link Future}, but make sure not to freeze up JOSM. Example:
     99     * {@link java.util.concurrent.Future}, but make sure not to freeze up JOSM. Example:
    97100     * <pre>
    98101     *    Future<?> future = task.download(...);
    99102     *    // DON'T run this on the Swing EDT or JOSM will freeze
     
    115118     *    }
    116119     *    Main.worker.submit(runAfterTask);
    117120     * </pre>
    118      * @param reader the reader used to parse OSM data (see {@link OsmServerReader#parseOsm})
     121     * @param reader the reader used to parse OSM data (see {@link org.openstreetmap.josm.io.OsmServerReader#parseOsm})
    119122     * @param newLayer true, if the data is to be downloaded into a new layer. If false, the task
    120123     *                 selects one of the existing layers as download layer, preferably the active layer.
    121124     * @param downloadArea the area to download
     
    156159     */
    157160    @Override
    158161    public Future<?> loadUrl(boolean new_layer, String url, ProgressMonitor progressMonitor) {
    159         if (url.matches(PATTERN_OVERPASS_API_URL)) {
     162        if (PATTERN_OVERPASS_API_URL_COMPILED.matcher(url).matches()) {
    160163            url = encodePartialUrl(url, "/interpreter?data="); // encode only the part after the = sign
    161164
    162         } else if (url.matches(PATTERN_OVERPASS_API_XAPI_URL)) {
     165        } else if (PATTERN_OVERPASS_API_XAPI_URL_COMPILED.matcher(url).matches()) {
    163166            url = encodePartialUrl(url, "/xapi?"); // encode only the part after the ? sign
    164167        }
    165168        downloadTask = new DownloadTask(new_layer,
     
    315318        }
    316319    }
    317320
     321    private static final Pattern CLEAR_URL_PATTERN = Pattern.compile(",\\s*");
     322
    318323    @Override
    319324    public String getConfirmationMessage(URL url) {
    320325        if (url != null) {
    321326            String urlString = url.toExternalForm();
    322             if (urlString.matches(PATTERN_OSM_API_URL)) {
     327            if (PATTERN_OSM_API_URL_COMPILED.matcher(urlString).matches()) {
    323328                // TODO: proper i18n after stabilization
    324329                String message = "<ul><li>"+tr("OSM Server URL:") + " " + url.getHost() + "</li><li>" +
    325330                        tr("Command")+": "+url.getPath()+"</li>";
    326331                if (url.getQuery() != null) {
    327                     message += "<li>" + tr("Request details: {0}", url.getQuery().replaceAll(",\\s*", ", ")) + "</li>";
     332                    message += "<li>" + tr("Request details: {0}", CLEAR_URL_PATTERN.matcher(url.getQuery()).replaceAll(", ")) + "</li>";
    328333                }
    329334                message += "</ul>";
    330335                return message;
  • src/org/openstreetmap/josm/data/AutosaveTask.java

     
    271271        changedDatasets.add(event.getDataset());
    272272    }
    273273
     274    private static final Pattern REPLACE_FIRST_PATTERN = Pattern.compile("[.][^.]+$");
     275
    274276    private final File getPidFile(File osmFile) {
    275         return new File(autosaveDir, osmFile.getName().replaceFirst("[.][^.]+$", ".pid"));
     277        return new File(autosaveDir, REPLACE_FIRST_PATTERN.matcher(osmFile.getName()).replaceFirst(".pid"));
    276278    }
    277279
    278280    /**
  • src/org/openstreetmap/josm/data/imagery/ImageryInfo.java

     
    402402        termsOfUseURL = text;
    403403    }
    404404
     405    private static final Pattern EXTENDED_URL_PATTERN = Pattern.compile(".*\\{PROJ\\(([^)}]+)\\)\\}.*");
     406
    405407    public void setExtendedUrl(String url) {
    406408        CheckParameterUtil.ensureParameterNotNull(url);
    407409
     
    429431        if(serverProjections == null || serverProjections.isEmpty()) {
    430432            try {
    431433                serverProjections = new ArrayList<String>();
    432                 Matcher m = Pattern.compile(".*\\{PROJ\\(([^)}]+)\\)\\}.*").matcher(url.toUpperCase());
     434                Matcher m = EXTENDED_URL_PATTERN.matcher(url.toUpperCase());
    433435                if(m.matches()) {
    434436                    for(String p : m.group(1).split(","))
    435437                        serverProjections.add(p);
  • src/org/openstreetmap/josm/data/osm/TagCollection.java

     
    1515import java.util.Map;
    1616import java.util.Map.Entry;
    1717import java.util.Set;
     18import java.util.regex.Pattern;
     19
    1820import org.openstreetmap.josm.tools.Utils;
    1921
    2022/**
    2123 * TagCollection is a collection of tags which can be used to manipulate
    22  * tags managed by {@link OsmPrimitive}s.
     24 * tags managed by {@link org.openstreetmap.josm.data.osm.OsmPrimitive}s.
    2325 *
    2426 * A TagCollection can be created:
    2527 * <ul>
    26  *  <li>from the tags managed by a specific {@link OsmPrimitive} with {@link #from(Tagged)}</li>
    27  *  <li>from the union of all tags managed by a collection of {@link OsmPrimitive}s with {@link #unionOfAllPrimitives(Collection)}</li>
    28  *  <li>from the union of all tags managed by a {@link DataSet} with {@link #unionOfAllPrimitives(DataSet)}</li>
    29  *  <li>from the intersection of all tags managed by a collection of primitives with {@link #commonToAllPrimitives(Collection)}</li>
     28 *  <li>from the tags managed by a specific {@link org.openstreetmap.josm.data.osm.OsmPrimitive} with {@link #from(org.openstreetmap.josm.data.osm.Tagged)}</li>
     29 *  <li>from the union of all tags managed by a collection of {@link org.openstreetmap.josm.data.osm.OsmPrimitive}s with {@link #unionOfAllPrimitives(java.util.Collection)}</li>
     30 *  <li>from the union of all tags managed by a {@link org.openstreetmap.josm.data.osm.DataSet} with {@link #unionOfAllPrimitives(org.openstreetmap.josm.data.osm.DataSet)}</li>
     31 *  <li>from the intersection of all tags managed by a collection of primitives with {@link #commonToAllPrimitives(java.util.Collection)}</li>
    3032 * </ul>
    3133 *
    3234 * It  provides methods to query the collection, like {@link #size()}, {@link #hasTagsFor(String)}, etc.
    3335 *
    3436 * Basic set operations allow to create the union, the intersection and  the difference
    35  * of tag collections, see {@link #union(TagCollection)}, {@link #intersect(TagCollection)},
    36  * and {@link #minus(TagCollection)}.
     37 * of tag collections, see {@link #union(org.openstreetmap.josm.data.osm.TagCollection)}, {@link #intersect(org.openstreetmap.josm.data.osm.TagCollection)},
     38 * and {@link #minus(org.openstreetmap.josm.data.osm.TagCollection)}.
    3739 *
    3840 *
    3941 */
     
    4143
    4244    /**
    4345     * Creates a tag collection from the tags managed by a specific
    44      * {@link OsmPrimitive}. If <code>primitive</code> is null, replies
     46     * {@link org.openstreetmap.josm.data.osm.OsmPrimitive}. If <code>primitive</code> is null, replies
    4547     * an empty tag collection.
    4648     *
    4749     * @param primitive  the primitive
    4850     * @return a tag collection with the tags managed by a specific
    49      * {@link OsmPrimitive}
     51     * {@link org.openstreetmap.josm.data.osm.OsmPrimitive}
    5052     */
    5153    public static TagCollection from(Tagged primitive) {
    5254        TagCollection tags = new TagCollection();
     
    589591    }
    590592
    591593    /**
    592      * Applies this tag collection to an {@link OsmPrimitive}. Does nothing if
     594     * Applies this tag collection to an {@link org.openstreetmap.josm.data.osm.OsmPrimitive}. Does nothing if
    593595     * primitive is null
    594596     *
    595597     * @param primitive  the primitive
     
    610612    }
    611613
    612614    /**
    613      * Applies this tag collection to a collection of {@link OsmPrimitive}s. Does nothing if
     615     * Applies this tag collection to a collection of {@link org.openstreetmap.josm.data.osm.OsmPrimitive}s. Does nothing if
    614616     * primitives is null
    615617     *
    616618     * @param primitives  the collection of primitives
     
    627629    }
    628630
    629631    /**
    630      * Replaces the tags of an {@link OsmPrimitive} by the tags in this collection . Does nothing if
     632     * Replaces the tags of an {@link org.openstreetmap.josm.data.osm.OsmPrimitive} by the tags in this collection . Does nothing if
    631633     * primitive is null
    632634     *
    633635     * @param primitive  the primitive
     
    645647    }
    646648
    647649    /**
    648      * Replaces the tags of a collection of{@link OsmPrimitive}s by the tags in this collection.
     650     * Replaces the tags of a collection of{@link org.openstreetmap.josm.data.osm.OsmPrimitive}s by the tags in this collection.
    649651     * Does nothing if primitives is null
    650652     *
    651653     * @param primitives the collection of primitives
     
    715717        return ret;
    716718    }
    717719
     720    private static final Pattern SPLIT_VALUES_PATTERN = Pattern.compile(";\\s*");
     721
    718722    /**
    719723     * Replies the concatenation of all tag values (concatenated by a semicolon)
    720724     *
     
    731735        Set<String> values = new LinkedHashSet<String>();
    732736        Map<String, Collection<String>> originalSplitValues = new LinkedHashMap<String, Collection<String>>();
    733737        for (String v : originalValues) {
    734             List<String> vs = Arrays.asList(v.split(";\\s*"));
     738            List<String> vs = Arrays.asList(SPLIT_VALUES_PATTERN.split(v));
    735739            originalSplitValues.put(v, vs);
    736740            values.addAll(vs);
    737741        }
  • src/org/openstreetmap/josm/data/preferences/ColorProperty.java

     
    22package org.openstreetmap.josm.data.preferences;
    33
    44import java.awt.Color;
     5import java.util.regex.Pattern;
    56
    67import org.openstreetmap.josm.Main;
    78import org.openstreetmap.josm.data.Preferences.ColorKey;
    89
    910/**
    10  * A property containing a {@link Color} value.
     11 * A property containing a {@link java.awt.Color} value.
    1112 * @since 5464
    1213 */
    1314public class ColorProperty extends AbstractProperty<Color> implements ColorKey {
     
    3334    public boolean put(Color value) {
    3435        return Main.pref.putColor(getColorKey(name), value);
    3536    }
    36    
     37
     38    private static final Pattern COLOR_KEY_PATTERN = Pattern.compile("[^a-z0-9]+");
     39
    3740    /**
    3841     * Replies the color key used in JOSM preferences for this property.
    3942     * @param colName The color name
    4043     * @return The color key for this property
    4144     */
    4245    public static String getColorKey(String colName) {
    43         return colName == null ? null : colName.toLowerCase().replaceAll("[^a-z0-9]+",".");
     46        return colName == null ? null : COLOR_KEY_PATTERN.matcher(colName.toLowerCase()).replaceAll(".");
    4447    }
    4548
    4649    @Override
  • src/org/openstreetmap/josm/data/projection/CustomProjection.java

     
    155155
    156156    private Map<String, String> parseParameterList(String pref) throws ProjectionConfigurationException {
    157157        Map<String, String> parameters = new HashMap<String, String>();
    158         String[] parts = pref.trim().split("\\s+");
     158        String[] parts = Utils.WHITE_SPACES_PATTERN.split(pref.trim());
    159159        if (pref.trim().isEmpty()) {
    160160            parts = new String[0];
    161161        }
  • src/org/openstreetmap/josm/data/validation/tests/NameMismatch.java

     
    66import java.util.Collection;
    77import java.util.HashSet;
    88import java.util.Map.Entry;
     9import java.util.regex.Pattern;
    910
    1011import org.openstreetmap.josm.data.osm.OsmPrimitive;
    1112import org.openstreetmap.josm.data.validation.Severity;
     
    3132public class NameMismatch extends Test {
    3233    protected static final int NAME_MISSING = 1501;
    3334    protected static final int NAME_TRANSLATION_MISSING = 1502;
     35    private static final Pattern NAME_SPLIT_PATTERN = Pattern.compile(" - ");
    3436
    3537    public NameMismatch() {
    3638        super(tr("Missing name:* translation"),
     
    8183        composition of some (not necessarily all) name:* labels.
    8284        Check if this is the case. */
    8385
    84         String[] split_names = name.split(" - ");
     86        String[] split_names = NAME_SPLIT_PATTERN.split(name);
    8587        if (split_names.length == 1) {
    8688            /* The name is not composed of multiple parts. Complain. */
    8789            missingTranslation(p);
  • src/org/openstreetmap/josm/data/validation/tests/TagChecker.java

     
    823823            }
    824824        };
    825825
    826         public String getData(String str) {
    827             Matcher m = Pattern.compile(" *# *([^#]+) *$").matcher(str);
    828             str = m.replaceFirst("").trim();
     826        private static final Pattern CLEAN_STR_PATTERN = Pattern.compile(" *# *([^#]+) *$");
     827        private static final Pattern SPLIT_TRIMMED_PATTERN = Pattern.compile(" *: *");
     828        private static final Pattern SPLIT_ELEMENTS_PATTERN = Pattern.compile(" *&& *");
     829
     830        public String getData(final String str) {
     831            Matcher m = CLEAN_STR_PATTERN.matcher(str);
     832            String trimmed = m.replaceFirst("").trim();
    829833            try {
    830834                description = m.group(1);
    831835                if (description != null && description.length() == 0) {
     
    834838            } catch (IllegalStateException e) {
    835839                description = null;
    836840            }
    837             String[] n = str.split(" *: *", 3);
     841            String[] n = SPLIT_TRIMMED_PATTERN.split(trimmed, 3);
    838842            if (n[0].equals("way")) {
    839843                type = OsmPrimitiveType.WAY;
    840844            } else if (n[0].equals("node")) {
     
    859863                code = TAG_CHECK_INFO;
    860864            } else
    861865                return tr("Could not find warning level");
    862             for (String exp: n[2].split(" *&& *")) {
     866            for (String exp: SPLIT_ELEMENTS_PATTERN.split(n[2])) {
    863867                try {
    864868                    data.add(new CheckerElement(exp));
    865869                } catch (IllegalStateException e) {
  • src/org/openstreetmap/josm/gui/dialogs/LatLonDialog.java

     
    5555    private static final char E_TR = LatLon.EAST.charAt(0);
    5656    private static final char W_TR = LatLon.WEST.charAt(0);
    5757
    58     private static final Pattern p = Pattern.compile(
     58    private static final Pattern LAT_LNG_PATTERN = Pattern.compile(
    5959            "([+|-]?\\d+[.,]\\d+)|"             // (1)
    6060            + "([+|-]?\\d+)|"                   // (2)
    6161            + "("+DEG+"|o|deg)|"                // (3)
     
    6666            + "\\s+|"
    6767            + "(.+)");
    6868
     69    private static final Pattern TYPE1_PATTERN = Pattern.compile("Ro?,?Ro?");
     70    private static final Pattern TYPE2_PATTERN = Pattern.compile("xRo?,?xRo?");
     71    private static final Pattern TYPE3_PATTERN = Pattern.compile("Ro?x,?Ro?x");
     72    private static final Pattern TYPE4_PATTERN = Pattern.compile("Zo[RZ]'?,?Zo[RZ]'?|Z[RZ],?Z[RZ]");
     73    private static final Pattern TYPE5_PATTERN = Pattern.compile("xZo[RZ]'?,?xZo[RZ]'?|xZo?[RZ],?xZo?[RZ]");
     74    private static final Pattern TYPE6_PATTERN = Pattern.compile("Zo[RZ]'?x,?Zo[RZ]'?x|Zo?[RZ]x,?Zo?[RZ]x");
     75    private static final Pattern TYPE7_PATTERN = Pattern.compile("ZoZ'[RZ]\"?x,?ZoZ'[RZ]\"?x|ZZ[RZ]x,?ZZ[RZ]x");
     76    private static final Pattern TYPE8_PATTERN = Pattern.compile("xZoZ'[RZ]\"?,?xZoZ'[RZ]\"?|xZZ[RZ],?xZZ[RZ]");
     77    private static final Pattern TYPE9_PATTERN = Pattern.compile("ZZ[RZ],?ZZ[RZ]");
     78
    6979    protected JPanel buildLatLon() {
    7080        JPanel pnl = new JPanel(new GridBagLayout());
    7181        pnl.setBorder(BorderFactory.createEmptyBorder(5,5,5,5));
     
    341351    }
    342352
    343353    private static LatLon parseLatLon(final String coord) {
    344         final Matcher m = p.matcher(coord);
     354        final Matcher m = LAT_LNG_PATTERN.matcher(coord);
    345355
    346356        final StringBuilder sb = new StringBuilder();
    347357        final List<Object> list = new ArrayList<Object>();
     
    380390        final Object[] params = list.toArray();
    381391        final LatLonHolder latLon = new LatLonHolder();
    382392
    383         if (pattern.matches("Ro?,?Ro?")) {
     393        if (TYPE1_PATTERN.matcher(pattern).matches()) {
    384394            setLatLonObj(latLon,
    385395                    params[0], ZERO, ZERO, "N",
    386396                    params[1], ZERO, ZERO, "E");
    387         } else if (pattern.matches("xRo?,?xRo?")) {
     397        } else if (TYPE2_PATTERN.matcher(pattern).matches()) {
    388398            setLatLonObj(latLon,
    389399                    params[1], ZERO, ZERO, params[0],
    390400                    params[3], ZERO, ZERO, params[2]);
    391         } else if (pattern.matches("Ro?x,?Ro?x")) {
     401        } else if (TYPE3_PATTERN.matcher(pattern).matches()) {
    392402            setLatLonObj(latLon,
    393403                    params[0], ZERO, ZERO, params[1],
    394404                    params[2], ZERO, ZERO, params[3]);
    395         } else if (pattern.matches("Zo[RZ]'?,?Zo[RZ]'?|Z[RZ],?Z[RZ]")) {
     405        } else if (TYPE4_PATTERN.matcher(pattern).matches()) {
    396406            setLatLonObj(latLon,
    397407                    params[0], params[1], ZERO, "N",
    398408                    params[2], params[3], ZERO, "E");
    399         } else if (pattern.matches("xZo[RZ]'?,?xZo[RZ]'?|xZo?[RZ],?xZo?[RZ]")) {
     409        } else if (TYPE5_PATTERN.matcher(pattern).matches()) {
    400410            setLatLonObj(latLon,
    401411                    params[1], params[2], ZERO, params[0],
    402412                    params[4], params[5], ZERO, params[3]);
    403         } else if (pattern.matches("Zo[RZ]'?x,?Zo[RZ]'?x|Zo?[RZ]x,?Zo?[RZ]x")) {
     413        } else if (TYPE6_PATTERN.matcher(pattern).matches()) {
    404414            setLatLonObj(latLon,
    405415                    params[0], params[1], ZERO, params[2],
    406416                    params[3], params[4], ZERO, params[5]);
    407         } else if (pattern.matches("ZoZ'[RZ]\"?x,?ZoZ'[RZ]\"?x|ZZ[RZ]x,?ZZ[RZ]x")) {
     417        } else if (TYPE7_PATTERN.matcher(pattern).matches()) {
    408418            setLatLonObj(latLon,
    409419                    params[0], params[1], params[2], params[3],
    410420                    params[4], params[5], params[6], params[7]);
    411         } else if (pattern.matches("xZoZ'[RZ]\"?,?xZoZ'[RZ]\"?|xZZ[RZ],?xZZ[RZ]")) {
     421        } else if (TYPE8_PATTERN.matcher(pattern).matches()) {
    412422            setLatLonObj(latLon,
    413423                    params[1], params[2], params[3], params[0],
    414424                    params[5], params[6], params[7], params[4]);
    415         } else if (pattern.matches("ZZ[RZ],?ZZ[RZ]")) {
     425        } else if (TYPE9_PATTERN.matcher(pattern).matches()) {
    416426            setLatLonObj(latLon,
    417427                    params[0], params[1], params[2], "N",
    418428                    params[3], params[4], params[5], "E");
     
    423433        return new LatLon(latLon.lat, latLon.lon);
    424434    }
    425435
     436    private static final Pattern SPLIT_EN_PATTERN = Pattern.compile("[;, ]+");
     437
    426438    private static EastNorth parseEastNorth(String s) {
    427         String[] en = s.split("[;, ]+");
     439        String[] en = SPLIT_EN_PATTERN.split(s);
    428440        if (en.length != 2) return null;
    429441        try {
    430442            double east = Double.parseDouble(en[0]);
  • src/org/openstreetmap/josm/gui/dialogs/relation/sort/RelationSorter.java

     
    99import java.util.LinkedList;
    1010import java.util.List;
    1111import java.util.Map;
     12import java.util.regex.Pattern;
    1213
    1314import org.openstreetmap.josm.data.osm.RelationMember;
     15import org.openstreetmap.josm.tools.Utils;
    1416
    1517public class RelationSorter {
    1618
     
    4749                    String addrB = b.getMember().get("addr:housenumber").trim();
    4850                    if (addrA.equals(addrB)) return 0;
    4951                    // Strip non-digits (from "1B" addresses for example)
    50                     String addrAnum = addrA.replaceAll("\\D+", "");
    51                     String addrBnum = addrB.replaceAll("\\D+", "");
     52                    String addrAnum = Utils.DIGITS_PATTERN.matcher(addrA).replaceAll("");
     53                    String addrBnum = Utils.DIGITS_PATTERN.matcher(addrB).replaceAll("");
     54
    5255                    // Compare only numbers
    5356                    try {
    5457                        Integer res = Integer.parseInt(addrAnum) - Integer.parseInt(addrBnum);
  • src/org/openstreetmap/josm/gui/help/HelpBrowser.java

     
    1818import java.util.Locale;
    1919import java.util.Observable;
    2020import java.util.Observer;
     21import java.util.regex.Pattern;
    2122
    2223import javax.swing.AbstractAction;
    2324import javax.swing.JButton;
     
    3839import javax.swing.text.Document;
    3940import javax.swing.text.Element;
    4041import javax.swing.text.SimpleAttributeSet;
     42import javax.swing.text.html.HTML;
    4143import javax.swing.text.html.HTML.Tag;
    4244import javax.swing.text.html.HTMLDocument;
    4345import javax.swing.text.html.StyleSheet;
     
    5557import org.openstreetmap.josm.tools.WindowGeometry;
    5658
    5759public class HelpBrowser extends JDialog {
     60
    5861    /** the unique instance */
    5962    private static HelpBrowser instance;
    6063
     
    435438        }
    436439    }
    437440
     441    private static final Pattern CLEAN_URL_PATTERN = Pattern.compile("#[^#]*$");
     442
    438443    class EditAction extends AbstractAction {
     444
    439445        public EditAction() {
    440446            // putValue(NAME, tr("Edit"));
    441447            putValue(SHORT_DESCRIPTION, tr("Edit the current help page"));
     
    463469                );
    464470                return;
    465471            }
    466             url = url.replaceAll("#[^#]*$", "");
     472            url = CLEAN_URL_PATTERN.matcher(url).replaceAll("");
    467473            OpenBrowser.displayUrl(url+"?action=edit");
    468474        }
    469475    }
     
    537543        }
    538544    }
    539545
     546    private static final Pattern HYPERLINK_URL_PATTERN = Pattern.compile("#.*");
     547
    540548    class HyperlinkHandler implements HyperlinkListener {
    541549
    542550        /**
     
    582590            Object value = set.getAttribute(Tag.A);
    583591            if (value == null || ! (value instanceof SimpleAttributeSet)) return null;
    584592            SimpleAttributeSet atts = (SimpleAttributeSet)value;
    585             value = atts.getAttribute(javax.swing.text.html.HTML.Attribute.HREF);
     593            value = atts.getAttribute(HTML.Attribute.HREF);
    586594            if (value == null) return null;
    587595            String s = (String)value;
    588             if (s.matches("#.*"))
     596            if (HYPERLINK_URL_PATTERN.matcher(s).matches())
    589597                return s.substring(1);
    590598            return null;
    591599        }
  • src/org/openstreetmap/josm/gui/preferences/imagery/AddImageryPanel.java

     
    55import java.awt.LayoutManager;
    66import java.util.ArrayList;
    77import java.util.Collection;
     8import java.util.regex.Pattern;
    89
    910import javax.swing.AbstractButton;
    1011import javax.swing.JPanel;
     
    2021
    2122/**
    2223 * An abstract imagery panel used to add WMS/TMS imagery sources. See implementations.
    23  * @see AddTMSLayerPanel
    24  * @see AddWMSLayerPanel
     24 * @see org.openstreetmap.josm.gui.preferences.imagery.AddTMSLayerPanel
     25 * @see org.openstreetmap.josm.gui.preferences.imagery.AddWMSLayerPanel
    2526 * @since 5617
    2627 */
    2728public abstract class AddImageryPanel extends JPanel {
     
    6768
    6869    protected abstract ImageryInfo getImageryInfo();
    6970
     71    private static final Pattern SANITIZE_PATTERN = Pattern.compile("[\r\n]+");
     72
    7073    protected static String sanitize(String s) {
    71         return s.replaceAll("[\r\n]+", "").trim();
     74        return SANITIZE_PATTERN.matcher(s).replaceAll("").trim();
    7275    }
    7376
    7477    protected final String getImageryName() {
  • src/org/openstreetmap/josm/gui/preferences/shortcut/PrefJPanel.java

     
    11// License: GPL. For details, see LICENSE file.
    22package org.openstreetmap.josm.gui.preferences.shortcut;
    33
    4 import java.awt.Color;
    5 import java.awt.Component;
    6 import java.awt.Dimension;
    7 import java.awt.GridBagConstraints;
    8 import java.awt.GridBagLayout;
    9 import java.awt.Insets;
    10 import java.awt.Toolkit;
     4import java.awt.*;
    115
    126import static org.openstreetmap.josm.tools.I18n.marktr;
    137import static org.openstreetmap.josm.tools.I18n.tr;
    148
     9import java.awt.event.ActionEvent;
    1510import java.awt.event.KeyEvent;
    1611import java.lang.reflect.Field;
    1712import java.util.ArrayList;
    1813import java.util.LinkedHashMap;
    1914import java.util.Map;
    2015
     16import java.util.regex.Pattern;
    2117import java.util.regex.PatternSyntaxException;
    2218import javax.swing.AbstractAction;
    2319import javax.swing.BorderFactory;
     
    4743import org.openstreetmap.josm.gui.widgets.SelectAllOnFocusGainedDecorator;
    4844import org.openstreetmap.josm.tools.Shortcut;
    4945import org.openstreetmap.josm.gui.widgets.JosmTextField;
     46import org.openstreetmap.josm.tools.Utils;
    5047
    5148/**
    5249 * This is the keyboard preferences content.
     
    194191        CbAction action = new CbAction(this);
    195192        setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
    196193        add(buildFilterPanel());
    197         listPane.setLayout(new java.awt.GridLayout());
     194        listPane.setLayout(new GridLayout());
    198195
    199196        // This is the list of shortcuts:
    200197        shortcutTable.setModel(model);
     
    212209        add(listPane);
    213210
    214211        // and here follows the edit area. I won't object to someone re-designing it, it looks, um, "minimalistic" ;)
    215         shortcutEditPane.setLayout(new java.awt.GridLayout(5, 2));
     212        shortcutEditPane.setLayout(new GridLayout(5, 2));
    216213
    217214        cbDefault.setAction(action);
    218215        cbDefault.setText(tr("Use default"));
     
    321318            }
    322319        }
    323320        @Override
    324         public void actionPerformed(java.awt.event.ActionEvent e) {
     321        public void actionPerformed(ActionEvent e) {
    325322            ListSelectionModel lsm = panel.shortcutTable.getSelectionModel();
    326323            if (lsm != null && !lsm.isSelectionEmpty()) {
    327324                if (e != null) { // only if we've been called by a user action
     
    375372                    expr = expr.replace("+", "\\+");
    376373                    // split search string on whitespace, do case-insensitive AND search
    377374                    ArrayList<RowFilter<Object, Object>> andFilters = new ArrayList<RowFilter<Object, Object>>();
    378                     for (String word : expr.split("\\s+")) {
     375                    for (String word : Utils.WHITE_SPACES_PATTERN.split(expr)) {
    379376                        andFilters.add(RowFilter.regexFilter("(?i)" + word));
    380377                    }
    381378                    sorter.setRowFilter(RowFilter.andFilter(andFilters));
  • src/org/openstreetmap/josm/gui/tagging/TaggingPresetItems.java

     
    2323import java.util.List;
    2424import java.util.Map;
    2525import java.util.TreeSet;
     26import java.util.regex.Pattern;
    2627import javax.swing.ButtonGroup;
    2728import javax.swing.ImageIcon;
    2829import javax.swing.JButton;
     
    145146                            : short_description;
    146147        }
    147148
     149        private static final Pattern REMOVE_MARKUP_PATTERN = Pattern.compile("<.*>");
    148150        // toString is mainly used to initialize the Editor
    149151        @Override
    150152        public String toString() {
    151153            if (value.equals(DIFFERENT))
    152154                return DIFFERENT;
    153             return getDisplayValue(true).replaceAll("<.*>", ""); // remove additional markup, e.g. <br>
     155            return REMOVE_MARKUP_PATTERN.matcher(getDisplayValue(true)).replaceAll(""); // remove additional markup, e.g. <br>
    154156        }
    155157    }
    156158
  • src/org/openstreetmap/josm/gui/util/GuiHelper.java

     
    2121import java.lang.reflect.InvocationTargetException;
    2222import java.util.Arrays;
    2323import java.util.List;
     24import java.util.regex.Pattern;
    2425
    2526import javax.swing.GrayFilter;
    2627import javax.swing.Icon;
     
    3738 * basic gui utils
    3839 */
    3940public class GuiHelper {
     41
    4042    /**
    4143     * disable / enable a component and all its child components
    4244     */
     
    171173        return timer;
    172174    }
    173175
     176    private static final Pattern CUSTOMIZED_STROKE_PATTERN = Pattern.compile("[^\\.0-9]+");
     177
    174178    /**
    175179     * Return s new BasicStroke object with given thickness and style
    176180     * @param code = 3.5 -> thickness=3.5px; 3.5 10 5 -> thickness=3.5px, dashed: 10px filled + 5px empty
    177181     * @return stroke for drawing
    178182     */
    179183    public static Stroke getCustomizedStroke(String code) {
    180         String[] s = code.trim().split("[^\\.0-9]+");
     184        String[] s = CUSTOMIZED_STROKE_PATTERN.split(code.trim());
    181185
    182186        if (s.length==0) return new BasicStroke();
    183187        float w;
  • src/org/openstreetmap/josm/io/CacheFiles.java

     
    1010import java.util.Iterator;
    1111import java.util.Set;
    1212import java.util.TreeMap;
     13import java.util.regex.Pattern;
    1314
    1415import javax.imageio.ImageIO;
    1516
     
    308309        return dirsize;
    309310    }
    310311
     312    private static final Pattern IDENT_PATTERN = Pattern.compile("[^a-zA-Z0-9]");
     313    private static final Pattern IDENT_PATTERN_2 = Pattern.compile("[acegikmoqsuwy]");
     314
    311315    /**
    312316     * Returns a short and unique file name for a given long identifier
    313317     * @return String short filename
     
    320324        } catch(Exception e) {
    321325            // Fall back. Remove unsuitable characters and some random ones to shrink down path length.
    322326            // Limit it to 70 characters, that leaves about 190 for the path on Windows/NTFS
    323             ident = ident.replaceAll("[^a-zA-Z0-9]", "");
    324             ident = ident.replaceAll("[acegikmoqsuwy]", "");
     327            ident = IDENT_PATTERN.matcher(ident).replaceAll("");
     328            ident = IDENT_PATTERN_2.matcher(ident).replaceAll("");
    325329            return ident.substring(ident.length() - 70);
    326330        }
    327331    }
  • src/org/openstreetmap/josm/io/MirroredInputStream.java

     
    1717import java.util.Arrays;
    1818import java.util.Enumeration;
    1919import java.util.List;
     20import java.util.regex.Pattern;
    2021import java.util.zip.ZipEntry;
    2122import java.util.zip.ZipFile;
    2223
     
    2930 * The file mirrored is only downloaded if it has been more than 7 days since last download
    3031 */
    3132public class MirroredInputStream extends InputStream {
     33
    3234    InputStream fs = null;
    3335    File file = null;
    3436
     
    5557     *  - http://... a url. It will be cached on disk.
    5658     * @param destDir the destination directory for the cache file. only applies for urls.
    5759     * @param maxTime the maximum age of the cache file (in seconds)
    58      * @throws IOException when the resource with the given name could not be retrieved
     60     * @throws java.io.IOException when the resource with the given name could not be retrieved
    5961     */
    6062    public MirroredInputStream(String name, String destDir, long maxTime) throws IOException {
    6163        URL url;
     
    7476                    file = checkLocal(url, destDir, maxTime);
    7577                }
    7678            }
    77         } catch (java.net.MalformedURLException e) {
     79        } catch (MalformedURLException e) {
    7880            if (name.startsWith("resource://")) {
    7981                fs = getClass().getResourceAsStream(
    8082                        name.substring("resource:/".length()));
     
    158160                }
    159161                Main.pref.putCollection(prefKey, null);
    160162            }
    161         } catch (java.net.MalformedURLException e) {}
     163        } catch (MalformedURLException e) {}
    162164    }
    163165
    164166    /**
     
    176178        return prefKey.toString().replaceAll("=","_");
    177179    }
    178180
     181    private static final Pattern CHECK_LOCAL_PATTERN = Pattern.compile("[^A-Za-z0-9_.-]");
     182
    179183    private File checkLocal(URL url, String destDir, long maxTime) throws IOException {
    180184        String prefKey = getPrefKey(url, destDir);
    181185        long age = 0L;
     
    206210            destDirFile.mkdirs();
    207211        }
    208212
    209         String a = url.toString().replaceAll("[^A-Za-z0-9_.-]", "_");
     213        String a = CHECK_LOCAL_PATTERN.matcher(url.toString()).replaceAll("_");
    210214        String localPath = "mirror_" + a;
    211215        destDirFile = new File(destDir, localPath + ".tmp");
    212216        BufferedOutputStream bos = null;
     
    254258     * Opens a connection for downloading a resource.
    255259     * <p>
    256260     * Manually follows redirects because
    257      * {@link HttpURLConnection#setFollowRedirects(boolean)} fails if the redirect
     261     * {@link java.net.HttpURLConnection#setFollowRedirects(boolean)} fails if the redirect
    258262     * is going from a http to a https URL, see <a href="http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4620571">bug report</a>.
    259263     * <p>
    260264     * This can causes problems when downloading from certain GitHub URLs.
    261265     *
    262266     * @param downloadUrl The resource URL to download
    263267     * @return The HTTP connection effectively linked to the resource, after all potential redirections
    264      * @throws MalformedURLException If a redirected URL is wrong
    265      * @throws IOException If any I/O operation goes wrong
     268     * @throws java.net.MalformedURLException If a redirected URL is wrong
     269     * @throws java.io.IOException If any I/O operation goes wrong
    266270     * @since 6073
    267271     */
    268272    public static HttpURLConnection connectFollowingRedirect(URL downloadUrl) throws MalformedURLException, IOException {
  • src/org/openstreetmap/josm/io/OsmApi.java

     
    2323import java.util.Collection;
    2424import java.util.Collections;
    2525import java.util.HashMap;
     26import java.util.regex.Pattern;
    2627
    2728import javax.xml.parsers.ParserConfigurationException;
    2829import javax.xml.parsers.SAXParserFactory;
     
    7374     */
    7475    static public final String DEFAULT_API_URL = "http://api.openstreetmap.org/api";
    7576
     77    private static final Pattern API_URL_PATTERN = Pattern.compile(".*openstreetmap.org/api.*");
     78
    7679    // The collection of instantiated OSM APIs
    7780    private static HashMap<String, OsmApi> instances = new HashMap<String, OsmApi>();
    7881
    7982    /**
    80      * Replies the {@link OsmApi} for a given server URL
     83     * Replies the {@link org.openstreetmap.josm.io.OsmApi} for a given server URL
    8184     *
    8285     * @param serverUrl  the server URL
    8386     * @return the OsmApi
     
    9497    }
    9598
    9699    /**
    97      * Replies the {@link OsmApi} for the URL given by the preference <code>osm-server.url</code>
     100     * Replies the {@link org.openstreetmap.josm.io.OsmApi} for the URL given by the preference <code>osm-server.url</code>
    98101     *
    99102     * @return the OsmApi
    100103     * @throws IllegalStateException thrown, if the preference <code>osm-server.url</code> is not set
     
    197200     * Initializes this component by negotiating a protocol version with the server.
    198201     *
    199202     * @param monitor the progress monitor
    200      * @throws OsmTransferCanceledException If the initialisation has been cancelled by user.
    201      * @throws OsmApiInitializationException If any other exception occurs. Use getCause() to get the original exception.
     203     * @throws org.openstreetmap.josm.io.OsmTransferCanceledException If the initialisation has been cancelled by user.
     204     * @throws org.openstreetmap.josm.io.OsmApiInitializationException If any other exception occurs. Use getCause() to get the original exception.
    202205     */
    203206    public void initialize(ProgressMonitor monitor) throws OsmTransferCanceledException, OsmApiInitializationException {
    204207        initialize(monitor, false);
     
    209212     *
    210213     * @param monitor the progress monitor
    211214     * @param fastFail true to request quick initialisation with a small timeout (more likely to throw exception)
    212      * @throws OsmTransferCanceledException If the initialisation has been cancelled by user.
    213      * @throws OsmApiInitializationException If any other exception occurs. Use getCause() to get the original exception.
     215     * @throws org.openstreetmap.josm.io.OsmTransferCanceledException If the initialisation has been cancelled by user.
     216     * @throws org.openstreetmap.josm.io.OsmApiInitializationException If any other exception occurs. Use getCause() to get the original exception.
    214217     */
    215218    public void initialize(ProgressMonitor monitor, boolean fastFail) throws OsmTransferCanceledException, OsmApiInitializationException {
    216219        if (initialized)
     
    238241            /* This is an interim solution for openstreetmap.org not currently
    239242             * transmitting their imagery blacklist in the capabilities call.
    240243             * remove this as soon as openstreetmap.org adds blacklists. */
    241             if (this.serverUrl.matches(".*openstreetmap.org/api.*") && capabilities.getImageryBlacklist().isEmpty())
     244            if (API_URL_PATTERN.matcher(this.serverUrl).matches() && capabilities.getImageryBlacklist().isEmpty())
    242245            {
    243246                capabilities.put("blacklist", "regex", ".*\\.google\\.com/.*");
    244247                capabilities.put("blacklist", "regex", ".*209\\.85\\.2\\d\\d.*");
     
    332335     *
    333336     * @param osm the primitive
    334337     * @param monitor the progress monitor
    335      * @throws OsmTransferException if something goes wrong
     338     * @throws org.openstreetmap.josm.io.OsmTransferException if something goes wrong
    336339     */
    337340    public void createPrimitive(IPrimitive osm, ProgressMonitor monitor) throws OsmTransferException {
    338341        String ret = "";
     
    352355     *
    353356     * @param osm the primitive. Must not be null.
    354357     * @param monitor the progress monitor
    355      * @throws OsmTransferException if something goes wrong
     358     * @throws org.openstreetmap.josm.io.OsmTransferException if something goes wrong
    356359     */
    357360    public void modifyPrimitive(IPrimitive osm, ProgressMonitor monitor) throws OsmTransferException {
    358361        String ret = null;
     
    373376     * Deletes an OSM primitive on the server.
    374377     * @param osm the primitive
    375378     * @param monitor the progress monitor
    376      * @throws OsmTransferException if something goes wrong
     379     * @throws org.openstreetmap.josm.io.OsmTransferException if something goes wrong
    377380     */
    378381    public void deletePrimitive(IPrimitive osm, ProgressMonitor monitor) throws OsmTransferException {
    379382        ensureValidChangeset();
     
    394397     *
    395398     * @param changeset the changeset toe be created. Must not be null.
    396399     * @param progressMonitor the progress monitor
    397      * @throws OsmTransferException signifying a non-200 return code, or connection errors
     400     * @throws org.openstreetmap.josm.io.OsmTransferException signifying a non-200 return code, or connection errors
    398401     * @throws IllegalArgumentException thrown if changeset is null
    399402     */
    400403    public void openChangeset(Changeset changeset, ProgressMonitor progressMonitor) throws OsmTransferException {
     
    421424     * be null and id > 0 must be true.
    422425     *
    423426     * @param changeset the changeset to update. Must not be null.
    424      * @param monitor the progress monitor. If null, uses the {@link NullProgressMonitor#INSTANCE}.
     427     * @param monitor the progress monitor. If null, uses the {@link org.openstreetmap.josm.gui.progress.NullProgressMonitor#INSTANCE}.
    425428     *
    426      * @throws OsmTransferException if something goes wrong.
     429     * @throws org.openstreetmap.josm.io.OsmTransferException if something goes wrong.
    427430     * @throws IllegalArgumentException if changeset is null
    428431     * @throws IllegalArgumentException if changeset.getId() <= 0
    429432     *
     
    462465     * succeeds.
    463466     *
    464467     * @param changeset the changeset to be closed. Must not be null. changeset.getId() > 0 required.
    465      * @param monitor the progress monitor. If null, uses {@link NullProgressMonitor#INSTANCE}
     468     * @param monitor the progress monitor. If null, uses {@link org.openstreetmap.josm.gui.progress.NullProgressMonitor#INSTANCE}
    466469     *
    467      * @throws OsmTransferException if something goes wrong.
     470     * @throws org.openstreetmap.josm.io.OsmTransferException if something goes wrong.
    468471     * @throws IllegalArgumentException thrown if changeset is null
    469472     * @throws IllegalArgumentException thrown if changeset.getId() <= 0
    470473     */
     
    493496     * @param list the list of changed OSM Primitives
    494497     * @param  monitor the progress monitor
    495498     * @return list of processed primitives
    496      * @throws OsmTransferException if something is wrong
     499     * @throws org.openstreetmap.josm.io.OsmTransferException if something is wrong
    497500     */
    498501    public Collection<IPrimitive> uploadDiff(Collection<? extends IPrimitive> list, ProgressMonitor monitor) throws OsmTransferException {
    499502        try {
     
    585588     * @param fastFail true to request a short timeout
    586589     *
    587590     * @return the body of the HTTP response, if and only if the response code was "200 OK".
    588      * @throws OsmTransferException if the HTTP return code was not 200 (and retries have
     591     * @throws org.openstreetmap.josm.io.OsmTransferException if the HTTP return code was not 200 (and retries have
    589592     *    been exhausted), or rewrapping a Java exception.
    590593     */
    591594    private String sendRequest(String requestMethod, String urlSuffix,String requestBody, ProgressMonitor monitor, boolean doAuthenticate, boolean fastFail) throws OsmTransferException {
     
    724727    /**
    725728     * Ensures that the current changeset can be used for uploading data
    726729     *
    727      * @throws OsmTransferException thrown if the current changeset can't be used for
     730     * @throws org.openstreetmap.josm.io.OsmTransferException thrown if the current changeset can't be used for
    728731     * uploading data
    729732     */
    730733    protected void ensureValidChangeset() throws OsmTransferException {
  • src/org/openstreetmap/josm/io/remotecontrol/AddTagsDialog.java

     
    1717import java.util.HashSet;
    1818import java.util.Map;
    1919import java.util.Set;
     20import java.util.regex.Pattern;
    2021import javax.swing.AbstractAction;
    2122import javax.swing.JCheckBox;
    2223
     
    287288        findExistingTags();
    288289    }
    289290
    290      /*
     291    private static final Pattern ADD_TAGS_PATTERN = Pattern.compile("\\s*=\\s*");
     292
     293    /*
    291294     * parse addtags parameters Example URL (part):
    292295     * addtags=wikipedia:de%3DResidenzschloss Dresden|name:en%3DDresden Castle
    293296     */
     
    314317                        int i = 0;
    315318                        for (String tag : tagSet) {
    316319                            // support a  =   b===c as "a"="b===c"
    317                             String [] pair = tag.split("\\s*=\\s*",2);
     320                            String [] pair = ADD_TAGS_PATTERN.split(tag, 2);
    318321                            keyValue[i][0] = pair[0];
    319322                            keyValue[i][1] = pair.length<2 ? "": pair[1];
    320323                            i++;
  • src/org/openstreetmap/josm/io/remotecontrol/handler/AddWayHandler.java

     
    99import java.util.HashMap;
    1010import java.util.LinkedList;
    1111import java.util.List;
     12import java.util.regex.Pattern;
    1213
    1314import org.openstreetmap.josm.Main;
    1415import org.openstreetmap.josm.actions.AutoScaleAction;
     
    2223import org.openstreetmap.josm.gui.util.GuiHelper;
    2324import org.openstreetmap.josm.io.remotecontrol.AddTagsDialog;
    2425import org.openstreetmap.josm.io.remotecontrol.PermissionPrefWithDefault;
    25 import org.openstreetmap.josm.io.remotecontrol.handler.RequestHandler.RequestHandlerBadRequestException;
    2626
    2727/**
    2828 * Adds a way to the current dataset. For instance, {@code /add_way?way=lat1,lon2;lat2,lon2}.
     
    8080        return PermissionPrefWithDefault.CREATE_OBJECTS;
    8181    }
    8282
     83    private static final Pattern SPLIT_WAY_PATTERN = Pattern.compile(";\\s*");
     84    private static final Pattern COORDINATES_PATTERN = Pattern.compile(",\\s*");
     85
    8386    @Override
    8487    protected void validateRequest() throws RequestHandlerBadRequestException {
    8588        allCoordinates.clear();
    86         for (String coordinatesString : args.get("way").split(";\\s*")) {
    87             String[] coordinates = coordinatesString.split(",\\s*", 2);
     89        for (String coordinatesString : SPLIT_WAY_PATTERN.split(args.get("way"))) {
     90            String[] coordinates = COORDINATES_PATTERN.split(coordinatesString, 2);
    8891            if (coordinates.length < 2) {
    8992                throw new RequestHandlerBadRequestException(
    9093                        tr("Invalid coordinates: {0}", Arrays.toString(coordinates)));
  • src/org/openstreetmap/josm/io/remotecontrol/handler/LoadObjectHandler.java

     
    55
    66import java.util.LinkedList;
    77import java.util.List;
     8import java.util.regex.Pattern;
    89
    910import org.openstreetmap.josm.Main;
    1011import org.openstreetmap.josm.actions.DownloadPrimitiveAction;
     
    8081        return PermissionPrefWithDefault.LOAD_DATA;
    8182    }
    8283
     84    private static final Pattern SPLIT_OBJECTS_PATTERN = Pattern.compile(",\\s*");
     85
    8386    @Override
    8487    protected void validateRequest() throws RequestHandlerBadRequestException {
    8588        ps.clear();
    86         for (String i : args.get("objects").split(",\\s*")) {
     89        for (String i : SPLIT_OBJECTS_PATTERN.split(args.get("objects"))) {
    8790            try {
    8891                ps.add(SimplePrimitiveId.fromString(i));
    8992            } catch (IllegalArgumentException e) {
  • src/org/openstreetmap/josm/plugins/PluginInformation.java

     
    2222import java.util.jar.Attributes;
    2323import java.util.jar.JarInputStream;
    2424import java.util.jar.Manifest;
     25import java.util.regex.Pattern;
    2526import javax.swing.ImageIcon;
    2627
    2728import org.openstreetmap.josm.Main;
     
    3738 * @author imi
    3839 */
    3940public class PluginInformation {
     41
    4042    public File file = null;
    4143    public String name = null;
    4244    public int mainversion = 0;
     
    332334        }
    333335    }
    334336
     337    private static final Pattern PLUGIN_NAME_PATTERN = Pattern.compile("[-. ]");
     338
    335339    /**
    336340     * Try to find a plugin after some criterias. Extract the plugin-information
    337341     * from the plugin and return it. The plugin is searched in the following way:
     
    369373     */
    370374    public static PluginInformation findPlugin(String pluginName) throws PluginException {
    371375        String name = pluginName;
    372         name = name.replaceAll("[-. ]", "");
     376        name = PLUGIN_NAME_PATTERN.matcher(name).replaceAll("");
    373377        InputStream manifestStream = PluginInformation.class.getResourceAsStream("/org/openstreetmap/josm/plugins/"+name+"/MANIFEST.MF");
    374378        if (manifestStream != null)
    375379            return new PluginInformation(manifestStream, pluginName, null);
     
    441445     */
    442446    public boolean matches(String filter) {
    443447        if (filter == null) return true;
    444         String[] words = filter.split("\\s+");
     448        String[] words = Utils.WHITE_SPACES_PATTERN.split(filter);
    445449        for (String word: words) {
    446450            if (matches(word, name)
    447451                    || matches(word, description)
  • src/org/openstreetmap/josm/plugins/ReadLocalPluginInformationTask.java

     
    1212import java.util.HashMap;
    1313import java.util.List;
    1414import java.util.Map;
     15import java.util.regex.Pattern;
    1516
    1617import org.openstreetmap.josm.gui.PleaseWaitRunnable;
    1718import org.openstreetmap.josm.gui.progress.ProgressMonitor;
     
    3536 *
    3637 */
    3738public class ReadLocalPluginInformationTask extends PleaseWaitRunnable {
     39
    3840    private Map<String, PluginInformation> availablePlugins;
    3941    private boolean canceled;
    4042
     
    7072        }
    7173    }
    7274
     75    private static final Pattern SITE_NAME_PATTERN = Pattern.compile("^([0-9]+-)?site.*\\.txt$");
     76
    7377    protected void scanSiteCacheFiles(ProgressMonitor monitor, File pluginsDirectory) {
    7478        File[] siteCacheFiles = pluginsDirectory.listFiles(
    7579                new FilenameFilter() {
    7680                    @Override
    7781                    public boolean accept(File dir, String name) {
    78                         return name.matches("^([0-9]+-)?site.*\\.txt$");
     82                        return SITE_NAME_PATTERN.matcher(name).matches();
    7983                    }
    8084                }
    8185        );
     
    96100        }
    97101    }
    98102
     103    private static final Pattern ICON_NAME_PATTERN = Pattern.compile("^([0-9]+-)?site.*plugin-icons\\.zip$");
     104
    99105    protected void scanIconCacheFiles(ProgressMonitor monitor, File pluginsDirectory) {
    100106        File[] siteCacheFiles = pluginsDirectory.listFiles(
    101107                new FilenameFilter() {
    102108                    @Override
    103109                    public boolean accept(File dir, String name) {
    104                         return name.matches("^([0-9]+-)?site.*plugin-icons\\.zip$");
     110                        return ICON_NAME_PATTERN.matcher(name).matches();
    105111                    }
    106112                }
    107113        );
  • src/org/openstreetmap/josm/tools/LanguageInfo.java

     
    22package org.openstreetmap.josm.tools;
    33
    44import java.util.Locale;
     5import java.util.regex.Pattern;
    56
    67public class LanguageInfo {
     8
    79    /**
    810     * Type of the locale to use
    911     * @since 5915
     
    1921        ENGLISH
    2022    };
    2123
     24    private static final Pattern WL_PREFFIX_PATTERN = Pattern.compile("[^_]+_[^_]+");
     25
    2226    /**
    2327     * Replies the wiki language prefix for the given locale. The wiki language
    2428     * prefix has the form 'Xy:' where 'Xy' is a ISO 639 language code in title
    2529     * case (or Xy_AB: for sub languages).
    2630     *
    2731     * @param type the type
    28      * @return the wiki language prefix or {@code null} for {@link LocaleType#BASELANGUAGE}, when
     32     * @return the wiki language prefix or {@code null} for {@link org.openstreetmap.josm.tools.LanguageInfo.LocaleType#BASELANGUAGE}, when
    2933     * base language is identical to default or english
    3034     * @since 5915
    3135     */
     
    3539
    3640        String code = getJOSMLocaleCode();
    3741        if(type == LocaleType.BASELANGUAGE) {
    38             if(code.matches("[^_]+_[^_]+")) {
     42            if(WL_PREFFIX_PATTERN.matcher(code).matches()) {
    3943                code = code.substring(0,2);
    4044                if(code == "en")
    4145                    return null;
     
    5155     * Replies the wiki language prefix for the current locale.
    5256     *
    5357     * @return the wiki language prefix
    54      * @see Locale#getDefault()
    55      * @see #getWikiLanguagePrefix(LocaleType)
     58     * @see java.util.Locale#getDefault()
     59     * @see #getWikiLanguagePrefix(org.openstreetmap.josm.tools.LanguageInfo.LocaleType)
    5660     */
    5761    static public String getWikiLanguagePrefix() {
    5862        return getWikiLanguagePrefix(LocaleType.DEFAULT);
     
    6266     * Replies the JOSM locale code for the default locale.
    6367     *
    6468     * @return the JOSM locale code for the default locale
    65      * @see #getJOSMLocaleCode(Locale)
     69     * @see #getJOSMLocaleCode(java.util.Locale)
    6670     */
    6771    static public String getJOSMLocaleCode() {
    6872        return getJOSMLocaleCode(Locale.getDefault());
     
    7175    /**
    7276     * Replies the locale code used by JOSM for a given locale.
    7377     *
    74      * In most cases JOSM uses the 2-character ISO 639 language code ({@link Locale#getLanguage()}
     78     * In most cases JOSM uses the 2-character ISO 639 language code ({@link java.util.Locale#getLanguage()}
    7579     * to identify the locale of a localized resource, but in some cases it may use the
    76      * programmatic name for locales, as replied by {@link Locale#toString()}.
     80     * programmatic name for locales, as replied by {@link java.util.Locale#toString()}.
    7781     *
    7882     * @param locale the locale. Replies "en" if null.
    7983     * @return the JOSM code for the given locale
  • src/org/openstreetmap/josm/tools/Utils.java

     
    3232import java.util.Collection;
    3333import java.util.Iterator;
    3434import java.util.List;
     35import java.util.regex.Pattern;
    3536import java.util.zip.ZipFile;
    3637
    3738import org.openstreetmap.josm.Main;
     
    4243 */
    4344public class Utils {
    4445
     46    public static final Pattern WHITE_SPACES_PATTERN = Pattern.compile("\\s+");
     47    public static final Pattern DIGITS_PATTERN = Pattern.compile("\\D+");
     48
    4549    public static <T> boolean exists(Iterable<? extends T> collection, Predicate<? super T> predicate) {
    4650        for (T item : collection) {
    4751            if (predicate.evaluate(item))
     
    245249     * Taken from <a href="http://www.rgagnon.com/javadetails/java-0064.html">this article</a> (CC-NC-BY-SA)
    246250     * @param in The source file
    247251     * @param out The destination file
    248      * @throws IOException If any I/O error occurs
     252     * @throws java.io.IOException If any I/O error occurs
    249253     */
    250254    public static void copyFile(File in, File out) throws IOException  {
    251255        // TODO: remove this function when we move to Java 7 (use Files.copy instead)
     
    293297    }
    294298
    295299    /**
    296      * <p>Utility method for closing a {@link Closeable} object.</p>
     300     * <p>Utility method for closing a {@link java.io.Closeable} object.</p>
    297301     *
    298302     * @param c the closeable object. May be null.
    299303     */
     
    307311    }
    308312
    309313    /**
    310      * <p>Utility method for closing a {@link ZipFile}.</p>
     314     * <p>Utility method for closing a {@link java.util.zip.ZipFile}.</p>
    311315     *
    312316     * @param zip the zip file. May be null.
    313317     */
     
    476480
    477481    /**
    478482     * Transforms the collection {@code c} into an unmodifiable collection and
    479      * applies the {@link Function} {@code f} on each element upon access.
     483     * applies the {@link org.openstreetmap.josm.tools.Utils.Function} {@code f} on each element upon access.
    480484     * @param <A> class of input collection
    481485     * @param <B> class of transformed collection
    482486     * @param c a collection
     
    518522
    519523    /**
    520524     * Transforms the list {@code l} into an unmodifiable list and
    521      * applies the {@link Function} {@code f} on each element upon access.
     525     * applies the {@link org.openstreetmap.josm.tools.Utils.Function} {@code f} on each element upon access.
    522526     * @param <A> class of input collection
    523527     * @param <B> class of transformed collection
    524528     * @param l a collection
     
    561565        return new Color(Integer.parseInt(clr, 16));
    562566    }
    563567
     568    private static final Pattern HTTP_PREFFIX_PATTERN = Pattern.compile("https?");
     569
    564570    /**
    565571     * Opens a HTTP connection to the given URL and sets the User-Agent property to JOSM's one.
    566572     * @param httpURL The HTTP url to open (must use http:// or https://)
    567573     * @return An open HTTP connection to the given URL
    568      * @throws IOException if an I/O exception occurs.
     574     * @throws java.io.IOException if an I/O exception occurs.
    569575     * @since 5587
    570576     */
    571577    public static HttpURLConnection openHttpConnection(URL httpURL) throws IOException {
    572         if (httpURL == null || !httpURL.getProtocol().matches("https?")) {
     578        if (httpURL == null || !HTTP_PREFFIX_PATTERN.matcher(httpURL.getProtocol()).matches()) {
    573579            throw new IllegalArgumentException("Invalid HTTP url");
    574580        }
    575581        HttpURLConnection connection = (HttpURLConnection) httpURL.openConnection();
     
    581587     * Opens a connection to the given URL and sets the User-Agent property to JOSM's one.
    582588     * @param url The url to open
    583589     * @return An stream for the given URL
    584      * @throws IOException if an I/O exception occurs.
     590     * @throws java.io.IOException if an I/O exception occurs.
    585591     * @since 5867
    586592     */
    587593    public static InputStream openURL(URL url) throws IOException {
     
    607613     * Opens a connection to the given URL and sets the User-Agent property to JOSM's one.
    608614     * @param url The url to open
    609615     * @return An buffered stream reader for the given URL (using UTF-8)
    610      * @throws IOException if an I/O exception occurs.
     616     * @throws java.io.IOException if an I/O exception occurs.
    611617     * @since 5868
    612618     */
    613619    public static BufferedReader openURLReader(URL url) throws IOException {
     
    619625     * @param httpURL The HTTP url to open (must use http:// or https://)
    620626     * @param keepAlive
    621627     * @return An open HTTP connection to the given URL
    622      * @throws IOException if an I/O exception occurs.
     628     * @throws java.io.IOException if an I/O exception occurs.
    623629     * @since 5587
    624630     */
    625631    public static HttpURLConnection openHttpConnection(URL httpURL, boolean keepAlive) throws IOException {