Ignore:
Timestamp:
2016-07-02T03:55:03+02:00 (8 years ago)
Author:
donvip
Message:

checkstyle

Location:
applications/editors/josm/plugins/imagery_offset_db
Files:
2 added
18 edited

Legend:

Unmodified
Added
Removed
  • applications/editors/josm/plugins/imagery_offset_db/.project

    r32286 r32528  
    1616                        </arguments>
    1717                </buildCommand>
     18                <buildCommand>
     19                        <name>net.sf.eclipsecs.core.CheckstyleBuilder</name>
     20                        <arguments>
     21                        </arguments>
     22                </buildCommand>
    1823        </buildSpec>
    1924        <natures>
    2025                <nature>org.eclipse.jdt.core.javanature</nature>
     26                <nature>net.sf.eclipsecs.core.CheckstyleNature</nature>
    2127        </natures>
    2228</projectDescription>
  • applications/editors/josm/plugins/imagery_offset_db/src/iodb/CalibrationLayer.java

    r29434 r32528  
     1// License: WTFPL. For details, see LICENSE file.
    12package iodb;
    23
    3 import java.awt.*;
     4import static org.openstreetmap.josm.tools.I18n.tr;
     5
     6import java.awt.BasicStroke;
     7import java.awt.Color;
     8import java.awt.Component;
     9import java.awt.Graphics;
     10import java.awt.Graphics2D;
     11import java.awt.Point;
     12import java.awt.RenderingHints;
     13import java.awt.Stroke;
    414import java.awt.event.ActionEvent;
    515import java.awt.geom.GeneralPath;
    6 import javax.swing.*;
     16
     17import javax.swing.AbstractAction;
     18import javax.swing.Action;
     19import javax.swing.Icon;
     20
    721import org.openstreetmap.josm.Main;
    822import org.openstreetmap.josm.actions.AutoScaleAction;
     
    1428import org.openstreetmap.josm.gui.dialogs.LayerListPopup;
    1529import org.openstreetmap.josm.gui.layer.Layer;
    16 import static org.openstreetmap.josm.tools.I18n.tr;
    1730import org.openstreetmap.josm.tools.ImageProvider;
    1831
     
    2942    private LatLon center;
    3043
    31     public CalibrationLayer( CalibrationObject obj ) {
     44    public CalibrationLayer(CalibrationObject obj) {
    3245        super(tr("Calibration Layer"));
    3346        color = Color.RED;
     
    4053     */
    4154    @Override
    42     public void paint( Graphics2D g, MapView mv, Bounds box ) {
     55    public void paint(Graphics2D g, MapView mv, Bounds box) {
    4356        g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
    4457        Stroke oldStroke = g.getStroke();
     
    4659        g.setStroke(new BasicStroke(1));
    4760        LatLon[] geometry = obj.getGeometry();
    48         if( geometry.length == 1 ) {
     61        if (geometry.length == 1) {
    4962            // draw crosshair
    5063            Point p = mv.getPoint(geometry[0]);
     
    5467            g.drawLine(p.x, p.y - 10, p.x, p.y - 20);
    5568            g.drawLine(p.x, p.y + 10, p.x, p.y + 20);
    56         } else if( geometry.length > 1 ) {
     69        } else if (geometry.length > 1) {
    5770            // draw a line
    5871            GeneralPath path = new GeneralPath();
    59             for( int i = 0; i < geometry.length; i++ ) {
     72            for (int i = 0; i < geometry.length; i++) {
    6073                Point p = mv.getPoint(geometry[i]);
    61                 if( i == 0 )
     74                if (i == 0)
    6275                    path.moveTo(p.x, p.y);
    6376                else
     
    7184    @Override
    7285    public Icon getIcon() {
    73         if( icon == null )
     86        if (icon == null)
    7487            icon = ImageProvider.get("calibration_layer");
    7588        return icon;
     
    7790
    7891    @Override
    79     public void mergeFrom( Layer from ) {
    80     }
    81 
    82     @Override
    83     public boolean isMergable( Layer other ) {
     92    public void mergeFrom(Layer from) {
     93    }
     94
     95    @Override
     96    public boolean isMergable(Layer other) {
    8497        return false;
    8598    }
     
    89102     */
    90103    @Override
    91     public void visitBoundingBox( BoundingXYVisitor v ) {
    92         for( LatLon ll : obj.getGeometry() )
     104    public void visitBoundingBox(BoundingXYVisitor v) {
     105        for (LatLon ll : obj.getGeometry()) {
    93106            v.visit(ll);
     107        }
    94108    }
    95109
     
    99113    @Override
    100114    public String getToolTipText() {
    101         if( obj.isDeprecated() )
     115        if (obj.isDeprecated())
    102116            return tr("A deprecated calibration geometry of {0} nodes by {1}", obj.getGeometry().length, obj.getAuthor());
    103117        else
     
    116130    public Action[] getMenuEntries() {
    117131        return new Action[] {
    118             LayerListDialog.getInstance().createShowHideLayerAction(),
    119             LayerListDialog.getInstance().createDeleteLayerAction(),
    120             SeparatorLayerAction.INSTANCE,
    121             new ZoomToLayerAction(),
    122             new SelectColorAction(Color.RED),
    123             new SelectColorAction(Color.CYAN),
    124             new SelectColorAction(Color.YELLOW),
    125             SeparatorLayerAction.INSTANCE,
    126             new LayerListPopup.InfoAction(this)
     132                LayerListDialog.getInstance().createShowHideLayerAction(),
     133                LayerListDialog.getInstance().createDeleteLayerAction(),
     134                SeparatorLayerAction.INSTANCE,
     135                new ZoomToLayerAction(),
     136                new SelectColorAction(Color.RED),
     137                new SelectColorAction(Color.CYAN),
     138                new SelectColorAction(Color.YELLOW),
     139                SeparatorLayerAction.INSTANCE,
     140                new LayerListPopup.InfoAction(this)
    127141        };
    128142    }
     
    134148     */
    135149    public void panToCenter() {
    136         if( center == null ) {
     150        if (center == null) {
    137151            LatLon[] geometry = obj.getGeometry();
    138152            double lat = 0.0;
    139153            double lon = 0.0;
    140             for( int i = 0; i < geometry.length; i++ ) {
     154            for (int i = 0; i < geometry.length; i++) {
    141155                lon += geometry[i].lon();
    142156                lat += geometry[i].lat();
     
    155169        private Color c;
    156170
    157         public SelectColorAction( Color color ) {
     171        SelectColorAction(Color color) {
    158172            super(tr("Change Color"));
    159173            putValue(SMALL_ICON, new SingleColorIcon(color));
     
    161175        }
    162176
    163         public void actionPerformed( ActionEvent e ) {
     177        @Override
     178        public void actionPerformed(ActionEvent e) {
    164179            color = c;
    165180            Main.map.mapView.repaint();
     
    173188        private Color color;
    174189
    175         public SingleColorIcon( Color color ) {
     190        SingleColorIcon(Color color) {
    176191            this.color = color;
    177192        }
    178193
    179         public void paintIcon( Component c, Graphics g, int x, int y ) {
     194        @Override
     195        public void paintIcon(Component c, Graphics g, int x, int y) {
    180196            g.setColor(color);
    181197            g.fillRect(x, y, 24, 24);
    182198        }
    183199
     200        @Override
    184201        public int getIconWidth() {
    185202            return 24;
    186203        }
    187204
     205        @Override
    188206        public int getIconHeight() {
    189207            return 24;
    190208        }
    191 
    192209    }
    193210
     
    197214     */
    198215    class ZoomToLayerAction extends AbstractAction {
    199         public ZoomToLayerAction() {
     216        ZoomToLayerAction() {
    200217            super(tr("Zoom to {0}", tr("layer"))); // to use translation from AutoScaleAction
    201218            putValue(SMALL_ICON, ImageProvider.get("dialogs/autoscale/layer"));
    202219        }
    203220
    204         public void actionPerformed( ActionEvent e ) {
     221        @Override
     222        public void actionPerformed(ActionEvent e) {
    205223            AutoScaleAction.autoScale("layer");
    206224        }
  • applications/editors/josm/plugins/imagery_offset_db/src/iodb/CalibrationObject.java

    r29384 r32528  
     1// License: WTFPL. For details, see LICENSE file.
    12package iodb;
    23
    34import java.util.Map;
     5
    46import org.openstreetmap.josm.data.coor.LatLon;
    57import org.openstreetmap.josm.data.osm.Node;
     
    2830     * Initialize a calibration object from OSM primitive.
    2931     */
    30     public CalibrationObject( OsmPrimitive p ) {
    31         if( p instanceof Node )
    32             geometry = new LatLon[] { ((Node)p).getCoor() };
    33         else if( p instanceof Way ) {
    34             geometry = new LatLon[((Way)p).getNodesCount()];
    35             for( int i = 0; i < geometry.length; i++ )
    36                 geometry[i] = ((Way)p).getNode(i).getCoor();
     32    public CalibrationObject(OsmPrimitive p) {
     33        if (p instanceof Node)
     34            geometry = new LatLon[] {((Node) p).getCoor()};
     35        else if (p instanceof Way) {
     36            geometry = new LatLon[((Way) p).getNodesCount()];
     37            for (int i = 0; i < geometry.length; i++) {
     38                geometry[i] = ((Way) p).getNode(i).getCoor();
     39            }
    3740        } else
    3841            throw new IllegalArgumentException("Calibration Object can be created either from node or a way");
     
    4750
    4851    @Override
    49     public void putServerParams( Map<String, String> map ) {
     52    public void putServerParams(Map<String, String> map) {
    5053        super.putServerParams(map);
    5154        StringBuilder sb = new StringBuilder();
    52         for( int i = 0; i < geometry.length; i++ ) {
    53             if( i > 0 )
     55        for (int i = 0; i < geometry.length; i++) {
     56            if (i > 0)
    5457                sb.append(',');
    5558            sb.append(geometry[i].lon()).append(' ').append(geometry[i].lat());
     
    6063    @Override
    6164    public String toString() {
    62         return "CalibrationObject{" + geometry.length + "nodes; position=" + position + ", date=" + date + ", author=" + author + ", description=" + description + ", abandonDate=" + abandonDate + '}';
     65        return "CalibrationObject{" + geometry.length + "nodes; position=" + position + ", date=" + date + ", author=" + author +
     66                ", description=" + description + ", abandonDate=" + abandonDate + '}';
    6367    }
    6468}
  • applications/editors/josm/plugins/imagery_offset_db/src/iodb/DeprecateOffsetAction.java

    r29434 r32528  
     1// License: WTFPL. For details, see LICENSE file.
    12package iodb;
     3
     4import static org.openstreetmap.josm.tools.I18n.tr;
    25
    36import java.awt.event.ActionEvent;
    47import java.io.UnsupportedEncodingException;
    5 import java.net.*;
     8import java.net.URLEncoder;
     9
    610import javax.swing.AbstractAction;
    711import javax.swing.JOptionPane;
     12
    813import org.openstreetmap.josm.Main;
    914import org.openstreetmap.josm.gui.JosmUserIdentityManager;
    10 import static org.openstreetmap.josm.tools.I18n.tr;
    1115import org.openstreetmap.josm.tools.ImageProvider;
    1216
    1317/**
    1418 * A context-dependent action to deprecate an offset.
    15  * 
     19 *
    1620 * @author Zverik
    1721 * @license WTFPL
     
    2024    private ImageryOffsetBase offset;
    2125    private QuerySuccessListener listener;
    22    
     26
    2327    /**
    2428     * Initialize an action with an offset object.
    2529     */
    26     public DeprecateOffsetAction( ImageryOffsetBase offset ) {
     30    public DeprecateOffsetAction(ImageryOffsetBase offset) {
    2731        super(tr("Deprecate Offset"));
    2832        putValue(SMALL_ICON, ImageProvider.get("dialogs", "delete"));
     
    3741     * on a positive answer.
    3842     */
     43    @Override
    3944    public void actionPerformed(ActionEvent e) {
    40         if( Main.map == null || Main.map.mapView == null || !Main.map.isVisible() )
     45        if (Main.map == null || Main.map.mapView == null || !Main.map.isVisible())
    4146            return;
    42        
     47
    4348        String desc = offset instanceof ImageryOffset ?
    4449                tr("Are you sure this imagery offset is wrong?") :
    45                 tr("Are you sure this calibration geometry is aligned badly?");
    46         if( JOptionPane.showConfirmDialog(Main.parent,
    47                 tr("Warning: deprecation is basically irreversible!")+ "\n" + desc,
    48                 ImageryOffsetTools.DIALOG_TITLE, JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE) != JOptionPane.YES_OPTION ) {
    49             return;
    50         }
    51         deprecateOffset(offset, listener);
     50                    tr("Are you sure this calibration geometry is aligned badly?");
     51                if (JOptionPane.showConfirmDialog(Main.parent,
     52                        tr("Warning: deprecation is basically irreversible!")+ "\n" + desc,
     53                        ImageryOffsetTools.DIALOG_TITLE, JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE) != JOptionPane.YES_OPTION) {
     54                    return;
     55                }
     56                deprecateOffset(offset, listener);
    5257    }
    5358
     
    5560     * Installs a listener to process successful deprecation event.
    5661     */
    57     public void setListener( QuerySuccessListener listener ) {
     62    public void setListener(QuerySuccessListener listener) {
    5863        this.listener = listener;
    5964    }
     
    6166    /**
    6267     * Deprecate the given offset.
    63      * @see #deprecateOffset(iodb.ImageryOffsetBase, iodb.QuerySuccessListener) 
     68     * @see #deprecateOffset(iodb.ImageryOffsetBase, iodb.QuerySuccessListener)
    6469     */
    65     public static void deprecateOffset( ImageryOffsetBase offset ) {
     70    public static void deprecateOffset(ImageryOffsetBase offset) {
    6671        deprecateOffset(offset, null);
    6772    }
     
    7176     * and executes {@link SimpleOffsetQueryTask} with a query to deprecate the offset.
    7277     */
    73     public static void deprecateOffset( ImageryOffsetBase offset, QuerySuccessListener listener ) {
     78    public static void deprecateOffset(ImageryOffsetBase offset, QuerySuccessListener listener) {
    7479        String userName = JosmUserIdentityManager.getInstance().getUserName();
    75         if( userName == null ) {
    76             JOptionPane.showMessageDialog(Main.parent, tr("To store imagery offsets you must be a registered OSM user."), ImageryOffsetTools.DIALOG_TITLE, JOptionPane.ERROR_MESSAGE);
     80        if (userName == null) {
     81            JOptionPane.showMessageDialog(Main.parent, tr("To store imagery offsets you must be a registered OSM user."),
     82                    ImageryOffsetTools.DIALOG_TITLE, JOptionPane.ERROR_MESSAGE);
    7783            return;
    7884        }
     
    8086        String message = offset instanceof ImageryOffset
    8187                ? tr("Please enter the reason why you mark this imagery offset as deprecated")
    82                 : tr("Please enter the reason why you mark this calibration geometry as deprecated");
    83         String reason = StoreImageryOffsetAction.queryDescription(message + ":");
    84         if( reason == null )
    85             return;
    86        
    87         try {
    88             String query = "deprecate?id=" + offset.getId()
    89                 + "&author=" + URLEncoder.encode(userName, "UTF8")
    90                 + "&reason=" + URLEncoder.encode(reason, "UTF8");
    91             SimpleOffsetQueryTask depTask = new SimpleOffsetQueryTask(query, tr("Notifying the server of the deprecation..."));
    92             if( listener != null )
    93                 depTask.setListener(listener);
    94             Main.worker.submit(depTask);
    95         } catch( UnsupportedEncodingException ex ) {
    96             // WTF
    97         }
     88                        : tr("Please enter the reason why you mark this calibration geometry as deprecated");
     89                String reason = StoreImageryOffsetAction.queryDescription(message + ":");
     90                if (reason == null)
     91                    return;
     92
     93                try {
     94                    String query = "deprecate?id=" + offset.getId()
     95                    + "&author=" + URLEncoder.encode(userName, "UTF8")
     96                    + "&reason=" + URLEncoder.encode(reason, "UTF8");
     97                    SimpleOffsetQueryTask depTask = new SimpleOffsetQueryTask(query, tr("Notifying the server of the deprecation..."));
     98                    if (listener != null)
     99                        depTask.setListener(listener);
     100                    Main.worker.submit(depTask);
     101                } catch (UnsupportedEncodingException ex) {
     102                    Main.error(ex);
     103                }
    98104    }
    99105}
  • applications/editors/josm/plugins/imagery_offset_db/src/iodb/GetImageryOffsetAction.java

    r30808 r32528  
     1// License: WTFPL. For details, see LICENSE file.
    12package iodb;
     3
     4import static org.openstreetmap.josm.tools.I18n.tr;
    25
    36import java.awt.event.ActionEvent;
     
    58import java.io.InputStream;
    69import java.io.UnsupportedEncodingException;
    7 import java.net.*;
    8 import java.util.*;
     10import java.net.URLEncoder;
     11import java.util.List;
     12
    913import javax.swing.Action;
    1014import javax.swing.Icon;
    1115import javax.swing.JOptionPane;
     16
    1217import org.openstreetmap.josm.Main;
    1318import org.openstreetmap.josm.actions.JosmAction;
     
    1621import org.openstreetmap.josm.data.projection.Projection;
    1722import org.openstreetmap.josm.gui.layer.ImageryLayer;
    18 import static org.openstreetmap.josm.tools.I18n.tr;
    1923import org.openstreetmap.josm.tools.ImageProvider;
    2024import org.openstreetmap.josm.tools.Shortcut;
     
    2226/**
    2327 * Download a list of imagery offsets for the current position, let user choose which one to use.
    24  * 
     28 *
    2529 * @author Zverik
    2630 * @license WTFPL
     
    2933    private Icon iconOffsetOk;
    3034    private Icon iconOffsetBad;
    31    
     35
    3236    /**
    3337     * Initialize the action. Sets "Ctrl+Alt+I" shortcut: the only shortcut in this plugin.
     
    3741        super(tr("Get Imagery Offset..."), "getoffset", tr("Download offsets for current imagery from a server"),
    3842                Shortcut.registerShortcut("imageryoffset:get", tr("Imagery: {0}", tr("Get Imagery Offset...")),
    39                 KeyEvent.VK_I, Shortcut.ALT_CTRL), true);
     43                        KeyEvent.VK_I, Shortcut.ALT_CTRL), true);
    4044        iconOffsetOk = new ImageProvider("getoffset").setSize(ImageProvider.ImageSizes.MENU).get();
    4145        iconOffsetBad = new ImageProvider("getoffsetnow").setSize(ImageProvider.ImageSizes.MENU).get();
     
    4650     * The action just executes {@link DownloadOffsetsTask}.
    4751     */
     52    @Override
    4853    public void actionPerformed(ActionEvent e) {
    49         if( Main.map == null || Main.map.mapView == null || !Main.map.isVisible() )
     54        if (Main.map == null || Main.map.mapView == null || !Main.map.isVisible())
    5055            return;
    5156        Projection proj = Main.map.mapView.getProjection();
     
    5358        ImageryLayer layer = ImageryOffsetTools.getTopImageryLayer();
    5459        String imagery = ImageryOffsetTools.getImageryID(layer);
    55         if( imagery == null )
     60        if (imagery == null)
    5661            return;
    57        
     62
    5863        DownloadOffsetsTask download = new DownloadOffsetsTask(center, layer, imagery);
    5964        Main.worker.submit(download);
     
    6772    protected void updateEnabledState() {
    6873        boolean state = true;
    69         if( Main.map == null || Main.map.mapView == null || !Main.map.isVisible() )
     74        if (Main.map == null || Main.map.mapView == null || !Main.map.isVisible())
    7075            state = false;
    7176        ImageryLayer layer = ImageryOffsetTools.getTopImageryLayer();
    72         if( ImageryOffsetTools.getImageryID(layer) == null )
     77        if (ImageryOffsetTools.getImageryID(layer) == null)
    7378            state = false;
    7479        setEnabled(state);
    7580    }
    76    
     81
    7782    /**
    7883     * Display a dialog for choosing between offsets. If there are no offsets in
     
    8085     * @param offsets List of offset objects to choose from.
    8186     */
    82     private void showOffsetDialog( List<ImageryOffsetBase> offsets ) {
    83         if( offsets.isEmpty() ) {
     87    private void showOffsetDialog(List<ImageryOffsetBase> offsets) {
     88        if (offsets.isEmpty()) {
    8489            JOptionPane.showMessageDialog(Main.parent,
    8590                    tr("No data for this region. Please adjust imagery layer and upload an offset."),
     
    8893        }
    8994        OffsetDialog offsetDialog = new OffsetDialog(offsets);
    90         if( offsetDialog.showDialog() != null )
     95        if (offsetDialog.showDialog() != null)
    9196            offsetDialog.applyOffset();
    9297    }
     
    95100     * Update action icon based on an offset state.
    96101     */
    97     public void offsetStateChanged( boolean isOffsetGood ) {
     102    @Override
     103    public void offsetStateChanged(boolean isOffsetGood) {
    98104        putValue(Action.SMALL_ICON, isOffsetGood ? iconOffsetOk : iconOffsetBad);
    99105    }
     
    122128         * @param imagery Imagery ID for the layer.
    123129         */
    124         public DownloadOffsetsTask( LatLon center, ImageryLayer layer, String imagery ) {
     130        DownloadOffsetsTask(LatLon center, ImageryLayer layer, String imagery) {
    125131            super(null, tr("Loading imagery offsets..."));
    126132            try {
    127133                String query = "get?lat=" + center.latToString(CoordinateFormat.DECIMAL_DEGREES)
    128                         + "&lon=" + center.lonToString(CoordinateFormat.DECIMAL_DEGREES)
    129                         + "&imagery=" + URLEncoder.encode(imagery, "UTF8");
     134                + "&lon=" + center.lonToString(CoordinateFormat.DECIMAL_DEGREES)
     135                + "&imagery=" + URLEncoder.encode(imagery, "UTF8");
    130136                int radius = Main.pref.getInteger("iodb.radius", -1);
    131                 if( radius > 0 )
     137                if (radius > 0)
    132138                    query = query + "&radius=" + radius;
    133139                setQuery(query);
    134             } catch( UnsupportedEncodingException e ) {
     140            } catch (UnsupportedEncodingException e) {
    135141                throw new IllegalArgumentException(e);
    136142            }
     
    142148        @Override
    143149        protected void afterFinish() {
    144             if( !cancelled && offsets != null )
     150            if (!cancelled && offsets != null)
    145151                showOffsetDialog(offsets);
    146152        }
    147        
     153
    148154        /**
    149155         * Parses the response with {@link IODBReader}.
     
    152158         */
    153159        @Override
    154         protected void processResponse( InputStream inp ) throws UploadException {
     160        protected void processResponse(InputStream inp) throws UploadException {
    155161            offsets = null;
    156162            try {
    157163                offsets = new IODBReader(inp).parse();
    158             } catch( Exception e ) {
     164            } catch (Exception e) {
    159165                throw new UploadException(tr("Error processing XML response: {0}", e.getMessage()));
    160166            }
  • applications/editors/josm/plugins/imagery_offset_db/src/iodb/IODBReader.java

    r30737 r32528  
     1// License: WTFPL. For details, see LICENSE file.
    12package iodb;
    23
     
    89import java.util.Date;
    910import java.util.List;
     11
    1012import javax.xml.parsers.ParserConfigurationException;
    1113import javax.xml.parsers.SAXParserFactory;
     14
    1215import org.openstreetmap.josm.data.coor.LatLon;
    1316import org.openstreetmap.josm.io.UTFInputStreamReader;
     
    2023 * Parses the server response. It expects XML in UTF-8 with several &lt;offset&gt;
    2124 * and &lt;calibration&gt; elements.
    22  * 
     25 *
    2326 * @author Zverik
    2427 * @license WTFPL
     
    2730    private List<ImageryOffsetBase> offsets;
    2831    private InputSource source;
    29    
     32
    3033    /**
    3134     * Initializes the parser. This constructor creates an input source on the input
     
    3437     * @throws IOException Thrown when something's wrong with the stream.
    3538     */
    36     public IODBReader( InputStream source ) throws IOException {
     39    public IODBReader(InputStream source) throws IOException {
    3740        this.source = new InputSource(UTFInputStreamReader.create(source, "UTF-8"));
    3841        this.offsets = new ArrayList<>();
     
    5154            factory.newSAXParser().parse(source, parser);
    5255            return offsets;
    53         } catch( ParserConfigurationException e ) {
     56        } catch (ParserConfigurationException e) {
    5457            throw new SAXException(e);
    5558        }
     
    9396        @Override
    9497        public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
    95             if( !parsingOffset ) {
    96                 if( qName.equals("offset") || qName.equals("calibration") ) {
     98            if (!parsingOffset) {
     99                if (qName.equals("offset") || qName.equals("calibration")) {
    97100                    parsingOffset = true;
    98101                    parsingDeprecate = false;
     
    100103                    fields.position = parseLatLon(attributes);
    101104                    fields.id = Integer.parseInt(attributes.getValue("id"));
    102                     if( attributes.getValue("flagged") != null && attributes.getValue("flagged").equals("yes") )
     105                    if (attributes.getValue("flagged") != null && attributes.getValue("flagged").equals("yes"))
    103106                        fields.flagged = true;
    104107                }
    105108            } else {
    106                 if( qName.equals("node") ) {
     109                if (qName.equals("node")) {
    107110                    fields.geometry.add(parseLatLon(attributes));
    108                 } else if( qName.equals("imagery-position") ) {
     111                } else if (qName.equals("imagery-position")) {
    109112                    fields.imageryPos = parseLatLon(attributes);
    110                 } else if( qName.equals("imagery") ) {
     113                } else if (qName.equals("imagery")) {
    111114                    String minZoom = attributes.getValue("minzoom");
    112115                    String maxZoom = attributes.getValue("maxzoom");
    113                     if( minZoom != null )
     116                    if (minZoom != null)
    114117                        fields.minZoom = Integer.parseInt(minZoom);
    115                     if( maxZoom != null )
     118                    if (maxZoom != null)
    116119                        fields.maxZoom = Integer.parseInt(maxZoom);
    117                 } else if( qName.equals("deprecated") ) {
     120                } else if (qName.equals("deprecated")) {
    118121                    parsingDeprecate = true;
    119122                }
     
    121124            accumulator.setLength(0);
    122125        }
    123        
     126
    124127        @Override
    125128        public void characters(char[] ch, int start, int length) throws SAXException {
    126             if( parsingOffset )
     129            if (parsingOffset)
    127130                accumulator.append(ch, start, length);
    128131        }
     
    130133        @Override
    131134        public void endElement(String uri, String localName, String qName) throws SAXException {
    132             if( parsingOffset ) {
    133                 if( qName.equals("author") ) {
    134                     if( !parsingDeprecate )
     135            if (parsingOffset) {
     136                if (qName.equals("author")) {
     137                    if (!parsingDeprecate)
    135138                        fields.author = accumulator.toString();
    136139                    else
    137140                        fields.abandonAuthor = accumulator.toString();
    138                 } else if( qName.equals("description") ) {
     141                } else if (qName.equals("description")) {
    139142                    fields.description = accumulator.toString();
    140                 } else if( qName.equals("reason") && parsingDeprecate ) {
     143                } else if (qName.equals("reason") && parsingDeprecate) {
    141144                    fields.abandonReason = accumulator.toString();
    142                 } else if( qName.equals("date") ) {
     145                } else if (qName.equals("date")) {
    143146                    try {
    144                         if( !parsingDeprecate )
     147                        if (!parsingDeprecate)
    145148                            fields.date = dateParser.parse(accumulator.toString());
    146149                        else
     
    149152                        throw new SAXException(ex);
    150153                    }
    151                 } else if( qName.equals("deprecated") ) {
     154                } else if (qName.equals("deprecated")) {
    152155                    parsingDeprecate = false;
    153                 } else if( qName.equals("imagery") ) {
     156                } else if (qName.equals("imagery")) {
    154157                    fields.imagery = accumulator.toString();
    155                 } else if( qName.equals("offset") || qName.equals("calibration") ) {
     158                } else if (qName.equals("offset") || qName.equals("calibration")) {
    156159                    // store offset
    157160                    try {
    158161                        offsets.add(fields.constructObject());
    159                     } catch( IllegalArgumentException ex ) {
     162                    } catch (IllegalArgumentException ex) {
    160163                        // On one hand, we don't care, but this situation is one
    161164                        // of those "it can never happen" cases.
     
    167170        }
    168171    }
    169    
     172
    170173    /**
    171174     * An accumulator for parsed fields. When there's enough data, it can construct
     
    191194         * A constructor just calls {@link #clear()}.
    192195         */
    193         public IOFields() {
     196        IOFields() {
    194197            clear();
    195198        }
    196        
     199
    197200        /**
    198201         * Clear all fields to <tt>null</tt> and <tt>-1</tt>.
     
    220223         */
    221224        public ImageryOffsetBase constructObject() {
    222             if( author == null || description == null || position == null || date == null )
     225            if (author == null || description == null || position == null || date == null)
    223226                throw new IllegalArgumentException("Not enought arguments to build an object");
    224227            ImageryOffsetBase result;
    225             if( geometry.isEmpty() ) {
    226                 if( imagery == null || imageryPos == null )
     228            if (geometry.isEmpty()) {
     229                if (imagery == null || imageryPos == null)
    227230                    throw new IllegalArgumentException("Both imagery and imageryPos should be specified for the offset");
    228231                result = new ImageryOffset(imagery, imageryPos);
    229                 if( minZoom >= 0 )
    230                     ((ImageryOffset)result).setMinZoom(minZoom);
    231                 if( maxZoom >= 0 )
    232                     ((ImageryOffset)result).setMaxZoom(maxZoom);
     232                if (minZoom >= 0)
     233                    ((ImageryOffset) result).setMinZoom(minZoom);
     234                if (maxZoom >= 0)
     235                    ((ImageryOffset) result).setMaxZoom(maxZoom);
    233236            } else {
    234237                result = new CalibrationObject(geometry.toArray(new LatLon[0]));
    235238            }
    236             if( id >= 0 )
     239            if (id >= 0)
    237240                result.setId(id);
    238241            result.setBasicInfo(position, author, description, date);
    239242            result.setDeprecated(abandonDate, abandonAuthor, abandonReason);
    240             if( flagged )
     243            if (flagged)
    241244                result.setFlagged(flagged);
    242245            return result;
  • applications/editors/josm/plugins/imagery_offset_db/src/iodb/ImageryIdGenerator.java

    r30737 r32528  
     1// License: WTFPL. For details, see LICENSE file.
    12package iodb;
    23
    3 import java.util.*;
     4import java.util.Arrays;
     5import java.util.Map;
     6import java.util.Set;
     7import java.util.TreeMap;
     8import java.util.TreeSet;
     9
    410import org.openstreetmap.josm.data.imagery.ImageryInfo.ImageryType;
    511
     
    1016 * @license WTFPL
    1117 */
    12 public class ImageryIdGenerator {
     18public final class ImageryIdGenerator {
    1319
    14     public static String getImageryID( String url, ImageryType type ) {
    15         if( url == null )
     20    private ImageryIdGenerator() {
     21        // Hide default constructor for utilities classes
     22    }
     23
     24    public static String getImageryID(String url, ImageryType type) {
     25        if (url == null)
    1626            return null;
    1727
    1828        // predefined layers
    19         if( ImageryType.BING.equals(type) || url.contains("tiles.virtualearth.net") )
     29        if (ImageryType.BING.equals(type) || url.contains("tiles.virtualearth.net"))
    2030            return "bing";
    2131
    22         if( ImageryType.SCANEX.equals(type) && url.toLowerCase().equals("irs") )
     32        if (ImageryType.SCANEX.equals(type) && url.toLowerCase().equals("irs"))
    2333            return "scanex_irs";
    2434
    25         if( ImageryType.TMS.equals(type) && url.toLowerCase().matches(".+tiles\\.mapbox\\.com/v[3-9]/openstreetmap\\.map.*") )
     35        if (ImageryType.TMS.equals(type) && url.toLowerCase().matches(".+tiles\\.mapbox\\.com/v[3-9]/openstreetmap\\.map.*"))
    2636            return "mapbox";
    2737
    2838        boolean isWMS = ImageryType.WMS.equals(type);
    2939
    30 //        System.out.println(url);
     40        //        System.out.println(url);
    3141
    3242        // Remove protocol
     
    3747        i = url.indexOf('?');
    3848        String query = "";
    39         if( i > 0 ) {
     49        if (i > 0) {
    4050            query = url.substring(i);
    4151            url = url.substring(0, i);
     
    4454        // Parse query parameters into a sorted map
    4555        final Set<String> removeWMSParams = new TreeSet<>(Arrays.asList(new String[] {
    46                     "srs", "width", "height", "bbox", "service", "request", "version", "format", "styles", "transparent"
    47                 }));
     56                "srs", "width", "height", "bbox", "service", "request", "version", "format", "styles", "transparent"
     57        }));
    4858        Map<String, String> qparams = new TreeMap<>();
    4959        String[] qparamsStr = query.length() > 1 ? query.substring(1).split("&") : new String[0];
    50         for( String param : qparamsStr ) {
     60        for (String param : qparamsStr) {
    5161            String[] kv = param.split("=");
    5262            kv[0] = kv[0].toLowerCase();
    5363            // WMS: if this is WMS, remove all parameters except map and layers
    54             if( isWMS && removeWMSParams.contains(kv[0]) )
     64            if (isWMS && removeWMSParams.contains(kv[0]))
    5565                continue;
    5666            // TMS: skip parameters with variable values
    57             if( kv.length > 1 && kv[1].indexOf('{') >= 0 && kv[1].indexOf('}') > 0 )
     67            if (kv.length > 1 && kv[1].indexOf('{') >= 0 && kv[1].indexOf('}') > 0)
    5868                continue;
    5969            qparams.put(kv[0].toLowerCase(), kv.length > 1 ? kv[1] : null);
     
    6272        // Reconstruct query parameters
    6373        StringBuilder sb = new StringBuilder();
    64         for( String qk : qparams.keySet() ) {
    65             if( sb.length() > 0 )
     74        for (String qk : qparams.keySet()) {
     75            if (sb.length() > 0)
    6676                sb.append('&');
    67             else if( query.length() > 0 )
     77            else if (query.length() > 0)
    6878                sb.append('?');
    6979            sb.append(qk).append('=').append(qparams.get(qk));
     
    7585        // TMS: remove variable parts
    7686        url = url.replaceAll("\\{[^}]+\\}", "");
    77         while( url.contains("..") )
     87        while (url.contains("..")) {
    7888            url = url.replace("..", ".");
    79         if( url.startsWith(".") )
     89        }
     90        if (url.startsWith("."))
    8091            url = url.substring(1);
    8192
    82 //        System.out.println("-> " + url + query);
    8393        return url + query;
    8494    }
  • applications/editors/josm/plugins/imagery_offset_db/src/iodb/ImageryOffset.java

    r29384 r32528  
     1// License: WTFPL. For details, see LICENSE file.
    12package iodb;
    23
    34import java.util.Map;
     5
    46import org.openstreetmap.josm.data.coor.CoordinateFormat;
    57import org.openstreetmap.josm.data.coor.LatLon;
     
    911 * of the position point on the imagery layer. The offset is then calculated
    1012 * as a difference between the two.
    11  * 
     13 *
    1214 * @author Zverik
    1315 * @license WTFPL
     
    1820    private int minZoom, maxZoom;
    1921
    20     public ImageryOffset( String imagery, LatLon imageryPos ) {
     22    public ImageryOffset(String imagery, LatLon imageryPos) {
    2123        this.imageryPos = imageryPos;
    2224        this.imagery = imagery;
     
    2426        this.maxZoom = 30;
    2527    }
    26    
     28
    2729    public void setMaxZoom(int maxZoom) {
    2830        this.maxZoom = maxZoom;
     
    3234        this.minZoom = minZoom;
    3335    }
    34    
     36
    3537    public LatLon getImageryPos() {
    3638        return imageryPos;
     
    5052
    5153    @Override
    52     public void putServerParams( Map<String, String> map ) {
     54    public void putServerParams(Map<String, String> map) {
    5355        super.putServerParams(map);
    5456        map.put("imagery", imagery);
    5557        map.put("imlat", imageryPos.latToString(CoordinateFormat.DECIMAL_DEGREES));
    5658        map.put("imlon", imageryPos.lonToString(CoordinateFormat.DECIMAL_DEGREES));
    57         if( minZoom > 0 )
     59        if (minZoom > 0)
    5860            map.put("minzoom", String.valueOf(minZoom));
    59         if( maxZoom < 30 )
     61        if (maxZoom < 30)
    6062            map.put("maxzoom", String.valueOf(maxZoom));
    6163    }
     
    6365    @Override
    6466    public String toString() {
    65         return "ImageryOffset{" + "imageryPos=" + imageryPos + ", imagery=" + imagery + "position=" + position + ", date=" + date + ", author=" + author + ", description=" + description + ", abandonDate=" + abandonDate + '}';
     67        return "ImageryOffset{" + "imageryPos=" + imageryPos + ", imagery=" + imagery + "position=" + position + ", date=" + date +
     68                ", author=" + author + ", description=" + description + ", abandonDate=" + abandonDate + '}';
    6669    }
    6770}
  • applications/editors/josm/plugins/imagery_offset_db/src/iodb/ImageryOffsetBase.java

    r29388 r32528  
     1// License: WTFPL. For details, see LICENSE file.
    12package iodb;
    23
    34import java.util.Date;
    45import java.util.Map;
     6
    57import org.openstreetmap.josm.data.coor.CoordinateFormat;
    68import org.openstreetmap.josm.data.coor.LatLon;
     
    1012 * and {@link CalibrationObject} classes and contains common fields
    1113 * like position, author and description.
    12  * 
     14 *
    1315 * @author Zverik
    1416 * @license WTFPL
     
    2426    protected String abandonReason;
    2527    protected boolean flagged;
    26    
     28
    2729    /**
    2830     * Initialize object with the basic information. It's offset location, author, date
    2931     * and description.
    3032     */
    31     public void setBasicInfo( LatLon position, String author, String description, Date date ) {
     33    public void setBasicInfo(LatLon position, String author, String description, Date date) {
    3234        this.position = position;
    3335        this.author = author;
     
    3840    }
    3941
    40     public void setId( long id ) {
     42    public void setId(long id) {
    4143        this.offsetId = id;
    4244    }
     
    6062    }
    6163
    62     public void setFlagged( boolean flagged ) {
     64    public void setFlagged(boolean flagged) {
    6365        this.flagged = flagged;
    6466    }
     
    7577        return abandonReason;
    7678    }
    77    
     79
    7880    /**
    7981     * Check that {@link #getAbandonDate()} is not null. Note that
     
    9698    }
    9799
    98     public void setDescription( String description ) {
     100    public void setDescription(String description) {
    99101        this.description = description;
    100102    }
     
    103105        return position;
    104106    }
    105    
    106     public void putServerParams( Map<String, String> map ) {
     107
     108    public void putServerParams(Map<String, String> map) {
    107109        map.put("lat", position.latToString(CoordinateFormat.DECIMAL_DEGREES));
    108110        map.put("lon", position.lonToString(CoordinateFormat.DECIMAL_DEGREES));
     
    113115    @Override
    114116    public String toString() {
    115         return "ImageryOffsetBase{" + "position=" + position + ", date=" + date + ", author=" + author + ", description=" + description + ", abandonDate=" + abandonDate + '}';
     117        return "ImageryOffsetBase{" + "position=" + position + ", date=" + date + ", author=" + author +
     118                ", description=" + description + ", abandonDate=" + abandonDate + '}';
    116119    }
    117120}
  • applications/editors/josm/plugins/imagery_offset_db/src/iodb/ImageryOffsetPlugin.java

    r31646 r32528  
     1// License: WTFPL. For details, see LICENSE file.
    12package iodb;
    23
     
    3132     * or completely unsuitable for imagery offset actions.
    3233     */
    33     public ImageryOffsetPlugin( PluginInformation info ) {
     34    public ImageryOffsetPlugin(PluginInformation info) {
    3435        super(info);
    3536
     
    4243        JMenu offsetMenu = version < 5803
    4344                ? Main.main.menu.addMenu("Offset", tr("Offset"), KeyEvent.VK_O, 6, "help")
    44                 : Main.main.menu.imageryMenu;
    45         offsetMenu.add(getAction);
    46         offsetMenu.add(storeAction);
     45                        : Main.main.menu.imageryMenu;
     46                offsetMenu.add(getAction);
     47                offsetMenu.add(storeAction);
    4748
    48         // an ugly hack to add this plugin to the toolbar
    49         if( Main.pref.getBoolean("iodb.modify.toolbar", true) ) {
    50             Collection<String> toolbar = new LinkedList<>(ToolbarPreferences.getToolString());
    51             if( !toolbar.contains("getoffset") ) {
    52                 toolbar.add("getoffset");
    53                 Main.pref.putCollection("toolbar", toolbar);
    54                 Main.toolbar.refreshToolbarControl();
    55             }
    56             Main.pref.put("iodb.modify.toolbar", false);
    57         }
     49                // an ugly hack to add this plugin to the toolbar
     50                if (Main.pref.getBoolean("iodb.modify.toolbar", true)) {
     51                    Collection<String> toolbar = new LinkedList<>(ToolbarPreferences.getToolString());
     52                    if (!toolbar.contains("getoffset")) {
     53                        toolbar.add("getoffset");
     54                        Main.pref.putCollection("toolbar", toolbar);
     55                        Main.toolbar.refreshToolbarControl();
     56                    }
     57                    Main.pref.put("iodb.modify.toolbar", false);
     58                }
    5859    }
    5960}
  • applications/editors/josm/plugins/imagery_offset_db/src/iodb/ImageryOffsetTools.java

    r32329 r32528  
     1// License: WTFPL. For details, see LICENSE file.
    12package iodb;
    23
     4import static org.openstreetmap.josm.tools.I18n.tr;
     5
    36import java.text.MessageFormat;
    4 import java.util.*;
     7import java.util.List;
     8
    59import org.openstreetmap.josm.Main;
    610import org.openstreetmap.josm.data.coor.EastNorth;
     
    913import org.openstreetmap.josm.gui.MapView;
    1014import org.openstreetmap.josm.gui.layer.ImageryLayer;
    11 import static org.openstreetmap.josm.tools.I18n.tr;
    1215
    1316/**
    1417 * Some common static methods for querying and processing imagery layers.
    15  * 
     18 *
    1619 * @author Zverik
    1720 * @license WTFPL
    1821 */
    19 public class ImageryOffsetTools {
     22public final class ImageryOffsetTools {
    2023    /**
    2124     * A title for all dialogs created in this plugin.
    2225     */
    2326    public static final String DIALOG_TITLE = tr("Imagery Offset Database");
    24    
     27
     28    private ImageryOffsetTools() {
     29        // Hide default constructor for utilities classes
     30    }
     31
    2532    /**
    2633     * Returns the topmost visible imagery layer.
     
    2835     */
    2936    public static ImageryLayer getTopImageryLayer() {
    30         if( Main.map == null || Main.map.mapView == null )
     37        if (Main.map == null || Main.map.mapView == null)
    3138            return null;
    3239        List<ImageryLayer> layers = Main.getLayerManager().getLayersOfType(ImageryLayer.class);
    33         for( ImageryLayer layer : layers ) {
     40        for (ImageryLayer layer : layers) {
    3441            String url = layer.getInfo().getUrl();
    35             if( layer.isVisible() && url != null && !url.contains("gps-") ) {
     42            if (layer.isVisible() && url != null && !url.contains("gps-")) {
    3643                return layer;
    3744            }
     
    3946        return null;
    4047    }
    41    
     48
    4249    /**
    4350     * Calculates the center of a visible map area.
     
    4956                ? new LatLon(0, 0) : proj.eastNorth2latlon(Main.map.mapView.getCenter());
    5057    }
    51    
     58
    5259    /**
    5360     * Calculates an imagery layer offset.
     
    5764     * @see #applyLayerOffset
    5865     */
    59     public static LatLon getLayerOffset( ImageryLayer layer, LatLon center ) {
     66    public static LatLon getLayerOffset(ImageryLayer layer, LatLon center) {
    6067        Projection proj = Main.getProjection();
    6168        EastNorth offsetCenter = Main.map.mapView.getCenter();
     
    6471        return offsetLL;
    6572    }
    66    
     73
    6774    /**
    6875     * Applies the offset to the imagery layer.
     
    7077     * @see #getLayerOffset
    7178     */
    72     public static void applyLayerOffset( ImageryLayer layer, ImageryOffset offset ) {
     79    public static void applyLayerOffset(ImageryLayer layer, ImageryOffset offset) {
    7380        double[] dxy = calculateOffset(offset);
    7481        layer.setOffset(dxy[0], dxy[1]);
     
    8087     * @see #applyLayerOffset
    8188     */
    82     public static double[] calculateOffset( ImageryOffset offset ) {
     89    public static double[] calculateOffset(ImageryOffset offset) {
    8390        Projection proj = Main.getProjection();
    8491        EastNorth center = proj.latlon2eastNorth(offset.getPosition());
    8592        EastNorth offsetPos = proj.latlon2eastNorth(offset.getImageryPos());
    86         return new double[] { center.getX() - offsetPos.getX(), center.getY() - offsetPos.getY() };
     93        return new double[] {center.getX() - offsetPos.getX(), center.getY() - offsetPos.getY()};
    8794    }
    88    
     95
    8996    /**
    9097     * Generate unique imagery identifier based on its type and URL.
     
    9299     * @return imagery id.
    93100     */
    94     public static String getImageryID( ImageryLayer layer ) {
     101    public static String getImageryID(ImageryLayer layer) {
    95102        return layer == null ? null :
    96                 ImageryIdGenerator.getImageryID(layer.getInfo().getUrl(), layer.getInfo().getImageryType());
     103            ImageryIdGenerator.getImageryID(layer.getInfo().getUrl(), layer.getInfo().getImageryType());
    97104    }
    98105
     
    134141     * Converts distance in meters to a human-readable string.
    135142     */
    136     public static String formatDistance( double d ) {
    137         if( d < 0.0095 ) return formatDistance(d * 1000, tr("mm"), true);
    138         if( d < 0.095 )  return formatDistance(d * 100,  tr("cm"), true );
    139         if( d < 0.95 )   return formatDistance(d * 100,  tr("cm"), false);
    140         if( d < 9.5 )    return formatDistance(d,        tr("m"),  true );
    141         if( d < 950 )    return formatDistance(d,        tr("m"),  false );
    142         if( d < 9500 )   return formatDistance(d / 1000, tr("km"), true);
    143         if( d < 1e6 )    return formatDistance(d / 1000, tr("km"), false);
     143    public static String formatDistance(double d) {
     144        // CHECKSTYLE.OFF: SingleSpaceSeparator
     145        if (d < 0.0095) return formatDistance(d * 1000, tr("mm"), true);
     146        if (d < 0.095)  return formatDistance(d * 100,  tr("cm"), true);
     147        if (d < 0.95)   return formatDistance(d * 100,  tr("cm"), false);
     148        if (d < 9.5)    return formatDistance(d,        tr("m"),  true);
     149        if (d < 950)    return formatDistance(d,        tr("m"),  false);
     150        if (d < 9500)   return formatDistance(d / 1000, tr("km"), true);
     151        if (d < 1e6)    return formatDistance(d / 1000, tr("km"), false);
     152        // CHECKSTYLE.ON: SingleSpaceSeparator
    144153        return "\u221E";
    145154    }
     
    152161     * @return A formatted string.
    153162     */
    154     private static String formatDistance( double d, String si, boolean floating ) {
     163    private static String formatDistance(double d, String si, boolean floating) {
    155164        return MessageFormat.format(floating ? "{0,number,0.0} {1}" : "{0,number,0} {1}", d, si);
    156165    }
  • applications/editors/josm/plugins/imagery_offset_db/src/iodb/ImageryOffsetWatcher.java

    r32462 r32528  
     1// License: WTFPL. For details, see LICENSE file.
    12package iodb;
    23
     
    3233 * @license WTFPL
    3334 */
    34 public class ImageryOffsetWatcher implements ZoomChangeListener, LayerChangeListener, ActiveLayerChangeListener, Destroyable {
     35public final class ImageryOffsetWatcher implements ZoomChangeListener, LayerChangeListener, ActiveLayerChangeListener, Destroyable {
    3536    private static final double THRESHOLD = 1e-8;
    3637    private static ImageryOffsetWatcher instance;
     
    7172     */
    7273    public static ImageryOffsetWatcher getInstance() {
    73         if( instance == null ) {
     74        if (instance == null) {
    7475            instance = new ImageryOffsetWatcher();
    7576        }
     
    8081     * Register an offset state listener.
    8182     */
    82     public void register( OffsetStateListener listener ) {
     83    public void register(OffsetStateListener listener) {
    8384        listeners.add(listener);
    8485        listener.offsetStateChanged(offsetGood);
     
    8889     * Unregister an offset state listener.
    8990     */
    90     public void unregister( OffsetStateListener listener ) {
     91    public void unregister(OffsetStateListener listener) {
    9192        listeners.remove(listener);
    9293    }
     
    9596     * Change stored offset state, notify listeners if needed.
    9697     */
    97     private void setOffsetGood( boolean good ) {
    98         if( good != offsetGood ) {
    99             for( OffsetStateListener listener : listeners )
     98    private void setOffsetGood(boolean good) {
     99        if (good != offsetGood) {
     100            for (OffsetStateListener listener : listeners) {
    100101                listener.offsetStateChanged(good);
     102            }
    101103        }
    102104        offsetGood = good;
     
    107109     */
    108110    private synchronized void checkOffset() {
    109         if( maxDistance <= 0 ) {
     111        if (maxDistance <= 0) {
    110112            setOffsetGood(true);
    111113            return;
    112114        }
    113115        ImageryLayer layer = ImageryOffsetTools.getTopImageryLayer();
    114         if( layer == null ) {
     116        if (layer == null) {
    115117            setOffsetGood(true);
    116118            return;
     
    119121        Integer hash = layer.hashCode();
    120122        ImageryLayerData data = layers.get(hash);
    121         if( data == null ) {
     123        if (data == null) {
    122124            // create entry for this layer and mark as needing alignment
    123125            data = new ImageryLayerData();
     
    125127            data.lastDy = layer.getDy();
    126128            boolean r = false;
    127             if( Math.abs(data.lastDx) + Math.abs(data.lastDy) > THRESHOLD ) {
     129            if (Math.abs(data.lastDx) + Math.abs(data.lastDy) > THRESHOLD) {
    128130                data.lastChecked = center;
    129131                r = true;
     
    133135        } else {
    134136            // now, we have a returning layer.
    135             if( Math.abs(data.lastDx - layer.getDx()) + Math.abs(data.lastDy - layer.getDy()) > THRESHOLD ) {
     137            if (Math.abs(data.lastDx - layer.getDx()) + Math.abs(data.lastDy - layer.getDy()) > THRESHOLD) {
    136138                // offset has changed, record the current position
    137139                data.lastDx = layer.getDx();
     
    153155    public void markGood() {
    154156        ImageryLayer layer = ImageryOffsetTools.getTopImageryLayer();
    155         if( layer != null ) {
     157        if (layer != null) {
    156158            LatLon center = ImageryOffsetTools.getMapCenter();
    157159            Integer hash = layer.hashCode();
    158160            ImageryLayerData data = layers.get(hash);
    159             if( data == null ) {
     161            if (data == null) {
    160162                // create entry for this layer and mark as good
    161163                data = new ImageryLayerData();
     
    216218     * projections: nobody uses them anyway.
    217219     */
    218     private void storeLayerOffset( ImageryLayer layer ) {
     220    private void storeLayerOffset(ImageryLayer layer) {
    219221        String id = ImageryOffsetTools.getImageryID(layer);
    220         if( !Main.pref.getBoolean("iodb.remember.offsets", true) || id == null )
     222        if (!Main.pref.getBoolean("iodb.remember.offsets", true) || id == null)
    221223            return;
    222224        Collection<String> offsets = new LinkedList<>(Main.pref.getCollection("iodb.stored.offsets"));
    223         for( Iterator<String> iter = offsets.iterator(); iter.hasNext(); ) {
     225        for (Iterator<String> iter = offsets.iterator(); iter.hasNext();) {
    224226            String[] offset = iter.next().split(":");
    225             if( offset.length == 5 && offset[0].equals(id) )
     227            if (offset.length == 5 && offset[0].equals(id))
    226228                iter.remove();
    227229        }
     
    234236     * Loads the current imagery layer offset from preferences.
    235237     */
    236     private void loadLayerOffset( ImageryLayer layer ) {
     238    private void loadLayerOffset(ImageryLayer layer) {
    237239        String id = ImageryOffsetTools.getImageryID(layer);
    238         if( !Main.pref.getBoolean("iodb.remember.offsets", true) || id == null )
     240        if (!Main.pref.getBoolean("iodb.remember.offsets", true) || id == null)
    239241            return;
    240242        Collection<String> offsets = Main.pref.getCollection("iodb.stored.offsets");
    241         for( String offset : offsets ) {
     243        for (String offset : offsets) {
    242244            String[] parts = offset.split(":");
    243             if( parts.length == 5 && parts[0].equals(id) ) {
     245            if (parts.length == 5 && parts[0].equals(id)) {
    244246                double[] dparts = new double[4];
    245247                try {
    246                     for( int i = 0; i < 4; i++ )
     248                    for (int i = 0; i < 4; i++) {
    247249                        dparts[i] = Double.parseDouble(parts[i+1]);
    248                 } catch( Exception e ) {
     250                    }
     251                } catch (Exception e) {
    249252                    continue;
    250253                }
    251254                LatLon lastPos = new LatLon(dparts[0], dparts[1]);
    252                 if( lastPos.greatCircleDistance(ImageryOffsetTools.getMapCenter()) < Math.max(maxDistance, 3.0) * 1000 ) {
     255                if (lastPos.greatCircleDistance(ImageryOffsetTools.getMapCenter()) < Math.max(maxDistance, 3.0) * 1000) {
    253256                    // apply offset
    254257                    layer.setOffset(dparts[2], dparts[3]);
     
    277280     */
    278281    public interface OffsetStateListener {
    279         void offsetStateChanged( boolean isOffsetGood );
     282        void offsetStateChanged(boolean isOffsetGood);
    280283    }
    281284}
  • applications/editors/josm/plugins/imagery_offset_db/src/iodb/OffsetDialog.java

    r32462 r32528  
     1// License: WTFPL. For details, see LICENSE file.
    12package iodb;
    23
     
    7273     * @param offsets The list of offset to choose from.
    7374     */
    74     public OffsetDialog( List<ImageryOffsetBase> offsets ) {
     75    public OffsetDialog(List<ImageryOffsetBase> offsets) {
    7576        super(JOptionPane.getFrameForComponent(Main.parent), ImageryOffsetTools.DIALOG_TITLE,
    7677                MODAL ? ModalityType.DOCUMENT_MODAL : ModalityType.MODELESS);
     
    9495        calibrationBox.addActionListener(new ActionListener() {
    9596            @Override
    96             public void actionPerformed( ActionEvent e ) {
     97            public void actionPerformed(ActionEvent e) {
    9798                Main.pref.put(PREF_CALIBRATION, calibrationBox.isSelected());
    9899                updateButtonPanel();
     
    103104        deprecatedBox.addActionListener(new ActionListener() {
    104105            @Override
    105             public void actionPerformed( ActionEvent e ) {
     106            public void actionPerformed(ActionEvent e) {
    106107                Main.pref.put(PREF_DEPRECATED, deprecatedBox.isSelected());
    107108                updateButtonPanel();
     
    135136    private void updateButtonPanel() {
    136137        List<ImageryOffsetBase> filteredOffsets = filterOffsets();
    137         if( buttonPanel == null )
     138        if (buttonPanel == null)
    138139            buttonPanel = new JPanel();
    139140        buttonPanel.removeAll();
    140141        buttonPanel.setLayout(new GridLayout(filteredOffsets.size(), 1, 0, 5));
    141         for( ImageryOffsetBase offset : filteredOffsets ) {
     142        for (ImageryOffsetBase offset : filteredOffsets) {
    142143            OffsetDialogButton button = new OffsetDialogButton(offset);
    143144            button.addActionListener(this);
    144145            JPopupMenu popupMenu = new JPopupMenu();
    145146            popupMenu.add(new OffsetInfoAction(offset));
    146             if( !offset.isDeprecated() ) {
     147            if (!offset.isDeprecated()) {
    147148                DeprecateOffsetAction action = new DeprecateOffsetAction(offset);
    148149                action.setListener(new DeprecateOffsetListener(offset));
     
    164165        boolean showDeprecated = Main.pref.getBoolean(PREF_DEPRECATED, false);
    165166        List<ImageryOffsetBase> filteredOffsets = new ArrayList<>();
    166         for( ImageryOffsetBase offset : offsets ) {
    167             if( offset.isDeprecated() && !showDeprecated )
     167        for (ImageryOffsetBase offset : offsets) {
     168            if (offset.isDeprecated() && !showDeprecated)
    168169                continue;
    169             if( offset instanceof CalibrationObject && !showCalibration )
     170            if (offset instanceof CalibrationObject && !showCalibration)
    170171                continue;
    171172            filteredOffsets.add(offset);
    172             if( filteredOffsets.size() >= MAX_OFFSETS )
     173            if (filteredOffsets.size() >= MAX_OFFSETS)
    173174                break;
    174175        }
     
    182183    @Override
    183184    public void zoomChanged() {
    184         for( Component c : buttonPanel.getComponents() ) {
    185             if( c instanceof OffsetDialogButton ) {
    186                 ((OffsetDialogButton)c).updateLocation();
     185        for (Component c : buttonPanel.getComponents()) {
     186            if (c instanceof OffsetDialogButton) {
     187                ((OffsetDialogButton) c).updateLocation();
    187188            }
    188189        }
     
    194195     */
    195196    @Override
    196     public void paint( Graphics2D g, MapView mv, Bounds bbox ) {
    197         if( offsets == null )
     197    public void paint(Graphics2D g, MapView mv, Bounds bbox) {
     198        if (offsets == null)
    198199            return;
    199200
    200         Graphics2D g2 = (Graphics2D)g.create();
     201        Graphics2D g2 = (Graphics2D) g.create();
    201202        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
    202203        g2.setStroke(new BasicStroke(2));
    203         for( ImageryOffsetBase offset : filterOffsets() ) {
     204        for (ImageryOffsetBase offset : filterOffsets()) {
    204205            Point p = mv.getPoint(offset.getPosition());
    205206            g2.setColor(Color.BLACK);
     
    221222        prepareDialog();
    222223        MapView.addZoomChangeListener(this);
    223         if( !MODAL ) {
     224        if (!MODAL) {
    224225            Main.map.mapView.addTemporaryLayer(this);
    225226            Main.map.mapView.repaint();
     
    237238     */
    238239    @Override
    239     public void actionPerformed( ActionEvent e ) {
    240         if( e.getSource() instanceof OffsetDialogButton ) {
    241             selectedOffset = ((OffsetDialogButton)e.getSource()).getOffset();
     240    public void actionPerformed(ActionEvent e) {
     241        if (e.getSource() instanceof OffsetDialogButton) {
     242            selectedOffset = ((OffsetDialogButton) e.getSource()).getOffset();
    242243        } else
    243244            selectedOffset = null;
     
    245246                || selectedOffset instanceof CalibrationObject
    246247                || Main.pref.getBoolean("iodb.close.on.select", true);
    247         if( closeDialog ) {
     248        if (closeDialog) {
    248249            MapView.removeZoomChangeListener(this);
    249250            setVisible(false);
    250251        }
    251         if( !MODAL ) {
    252             if( closeDialog ) {
     252        if (!MODAL) {
     253            if (closeDialog) {
    253254                Main.map.mapView.removeTemporaryLayer(this);
    254255                Main.map.mapView.repaint();
    255256            }
    256             if( selectedOffset != null ) {
     257            if (selectedOffset != null) {
    257258                applyOffset();
    258                 if( !closeDialog )
     259                if (!closeDialog)
    259260                    updateButtonPanel();
    260261            }
    261262        }
    262263    }
    263 
    264264
    265265    /**
     
    269269     */
    270270    public void applyOffset() {
    271         if( selectedOffset instanceof ImageryOffset ) {
     271        if (selectedOffset instanceof ImageryOffset) {
    272272            ImageryLayer layer = ImageryOffsetTools.getTopImageryLayer();
    273             ImageryOffsetTools.applyLayerOffset(layer, (ImageryOffset)selectedOffset);
     273            ImageryOffsetTools.applyLayerOffset(layer, (ImageryOffset) selectedOffset);
    274274            ImageryOffsetWatcher.getInstance().markGood();
    275275            Main.map.repaint();
    276             if( !Main.pref.getBoolean("iodb.offset.message", false) ) {
     276            if (!Main.pref.getBoolean("iodb.offset.message", false)) {
    277277                JOptionPane.showMessageDialog(Main.parent,
    278278                        tr("The topmost imagery layer has been shifted to presumably match\n"
     
    282282                Main.pref.put("iodb.offset.message", true);
    283283            }
    284         } else if( selectedOffset instanceof CalibrationObject ) {
    285             CalibrationLayer clayer = new CalibrationLayer((CalibrationObject)selectedOffset);
     284        } else if (selectedOffset instanceof CalibrationObject) {
     285            CalibrationLayer clayer = new CalibrationLayer((CalibrationObject) selectedOffset);
    286286            Main.getLayerManager().addLayer(clayer);
    287287            clayer.panToCenter();
    288             if( !Main.pref.getBoolean("iodb.calibration.message", false) ) {
     288            if (!Main.pref.getBoolean("iodb.calibration.message", false)) {
    289289                JOptionPane.showMessageDialog(Main.parent,
    290290                        tr("A layer has been added with a calibration geometry. Hide data layers,\n"
     
    305305         * Initialize the listener with an offset.
    306306         */
    307         public DeprecateOffsetListener( ImageryOffsetBase offset ) {
     307        DeprecateOffsetListener(ImageryOffsetBase offset) {
    308308            this.offset = offset;
    309309        }
     
    324324    class HelpAction extends AbstractAction {
    325325
    326         public HelpAction() {
     326        HelpAction() {
    327327            super(tr("Help"));
    328328            putValue(SMALL_ICON, ImageProvider.get("help"));
     
    330330
    331331        @Override
    332         public void actionPerformed( ActionEvent e ) {
     332        public void actionPerformed(ActionEvent e) {
    333333            String base = Main.pref.get("url.openstreetmap-wiki", "http://wiki.openstreetmap.org/wiki/");
    334334            String lang = LanguageInfo.getWikiLanguagePrefix();
     
    341341                    lang = "";
    342342                }
    343             } catch( IOException ex ) {
     343            } catch (IOException ex) {
    344344                lang = "";
    345345            }
  • applications/editors/josm/plugins/imagery_offset_db/src/iodb/OffsetDialogButton.java

    r29432 r32528  
     1// License: WTFPL. For details, see LICENSE file.
    12package iodb;
    23
    3 import java.awt.*;
    4 import javax.swing.*;
     4import static org.openstreetmap.josm.tools.I18n.tr;
     5
     6import java.awt.AlphaComposite;
     7import java.awt.BasicStroke;
     8import java.awt.BorderLayout;
     9import java.awt.Color;
     10import java.awt.Component;
     11import java.awt.Font;
     12import java.awt.Graphics;
     13import java.awt.Graphics2D;
     14import java.awt.Point;
     15import java.awt.RenderingHints;
     16
     17import javax.swing.Box;
     18import javax.swing.BoxLayout;
     19import javax.swing.Icon;
     20import javax.swing.ImageIcon;
     21import javax.swing.JButton;
     22import javax.swing.JLabel;
     23import javax.swing.JPanel;
     24import javax.swing.SwingConstants;
     25
    526import org.openstreetmap.josm.Main;
    627import org.openstreetmap.josm.data.coor.EastNorth;
     
    930import org.openstreetmap.josm.gui.layer.ImageryLayer;
    1031import org.openstreetmap.josm.tools.ImageProvider;
    11 import static org.openstreetmap.josm.tools.I18n.tr;
    1232
    1333/**
    1434 * A button which shows offset information. Must be spectacular, since it's the only
    1535 * non-JOptionPane GUI in the plugin.
    16  * 
     36 *
    1737 * @author Zverik
    1838 * @license WTFPL
    1939 */
    2040public class OffsetDialogButton extends JButton {
    21    
     41
    2242    private ImageryOffsetBase offset;
    2343
     
    2949     * @param offset An offset to display on the button.
    3050     */
    31     public OffsetDialogButton( ImageryOffsetBase offset ) {
     51    public OffsetDialogButton(ImageryOffsetBase offset) {
    3252        this.offset = offset;
    3353        layoutComponents();
     
    5777        String authorAndDate = offset.isDeprecated()
    5878                ? tr("Deprecated by {0} on {1}", offset.getAbandonAuthor(),
    59                 OffsetInfoAction.DATE_FORMAT.format(offset.getAbandonDate()))
    60                 : tr("Created by {0} on {1}", offset.getAuthor(),
    61                 OffsetInfoAction.DATE_FORMAT.format(offset.getDate()));
    62         JLabel authorAndDateLabel = new JLabel(authorAndDate);
    63         Font authorFont = new Font(authorAndDateLabel.getFont().getName(), Font.ITALIC, authorAndDateLabel.getFont().getSize());
    64         authorAndDateLabel.setFont(authorFont);
    65 
    66         directionArrow = new DirectionIcon(offset.getPosition());
    67         distanceLabel = new JLabel("", directionArrow, SwingConstants.RIGHT);
    68         distanceLabel.setHorizontalTextPosition(SwingConstants.LEFT);
    69         Font distanceFont = new Font(distanceLabel.getFont().getName(), Font.PLAIN, distanceLabel.getFont().getSize());
    70         distanceLabel.setFont(distanceFont);
    71         updateLocation();
    72 
    73         String description = offset.isDeprecated() ? offset.getAbandonReason() : offset.getDescription();
    74         description = description.replace("<", "&lt;").replace(">", "&gt;");
    75         JLabel descriptionLabel = new JLabel("<html><div style=\"width: 300px;\">"+description+"</div></html>");
    76         Font descriptionFont = new Font(descriptionLabel.getFont().getName(), Font.BOLD, descriptionLabel.getFont().getSize());
    77         descriptionLabel.setFont(descriptionFont);
    78 
    79         OffsetIcon offsetIcon = new OffsetIcon(offset);
    80         double offsetDistance = offset instanceof ImageryOffset
    81                 ? offsetIcon.getDistance() : 0.0;
    82 //                ? ((ImageryOffset)offset).getImageryPos().greatCircleDistance(offset.getPosition()) : 0.0;
    83         JLabel offsetLabel = new JLabel(offsetDistance > 0.2 ? ImageryOffsetTools.formatDistance(offsetDistance) : "",
    84                 offsetIcon, SwingConstants.CENTER);
    85         Font offsetFont = new Font(offsetLabel.getFont().getName(), Font.PLAIN, offsetLabel.getFont().getSize() - 2);
    86         offsetLabel.setFont(offsetFont);
    87         offsetLabel.setHorizontalTextPosition(SwingConstants.CENTER);
    88         offsetLabel.setVerticalTextPosition(SwingConstants.BOTTOM);
    89 
    90         Box topLine = new Box(BoxLayout.X_AXIS);
    91         topLine.add(authorAndDateLabel);
    92         topLine.add(Box.createHorizontalGlue());
    93         topLine.add(Box.createHorizontalStrut(10));
    94         topLine.add(distanceLabel);
    95 
    96         JPanel p = new JPanel(new BorderLayout(10, 5));
    97         p.setOpaque(false);
    98         p.add(topLine, BorderLayout.NORTH);
    99         p.add(offsetLabel, BorderLayout.WEST);
    100         p.add(descriptionLabel, BorderLayout.CENTER);
    101         add(p);
     79                        OffsetInfoAction.DATE_FORMAT.format(offset.getAbandonDate()))
     80                        : tr("Created by {0} on {1}", offset.getAuthor(),
     81                                OffsetInfoAction.DATE_FORMAT.format(offset.getDate()));
     82                JLabel authorAndDateLabel = new JLabel(authorAndDate);
     83                Font authorFont = new Font(authorAndDateLabel.getFont().getName(), Font.ITALIC, authorAndDateLabel.getFont().getSize());
     84                authorAndDateLabel.setFont(authorFont);
     85
     86                directionArrow = new DirectionIcon(offset.getPosition());
     87                distanceLabel = new JLabel("", directionArrow, SwingConstants.RIGHT);
     88                distanceLabel.setHorizontalTextPosition(SwingConstants.LEFT);
     89                Font distanceFont = new Font(distanceLabel.getFont().getName(), Font.PLAIN, distanceLabel.getFont().getSize());
     90                distanceLabel.setFont(distanceFont);
     91                updateLocation();
     92
     93                String description = offset.isDeprecated() ? offset.getAbandonReason() : offset.getDescription();
     94                description = description.replace("<", "&lt;").replace(">", "&gt;");
     95                JLabel descriptionLabel = new JLabel("<html><div style=\"width: 300px;\">"+description+"</div></html>");
     96                Font descriptionFont = new Font(descriptionLabel.getFont().getName(), Font.BOLD, descriptionLabel.getFont().getSize());
     97                descriptionLabel.setFont(descriptionFont);
     98
     99                OffsetIcon offsetIcon = new OffsetIcon(offset);
     100                double offsetDistance = offset instanceof ImageryOffset
     101                        ? offsetIcon.getDistance() : 0.0;
     102                        //                ? ((ImageryOffset)offset).getImageryPos().greatCircleDistance(offset.getPosition()) : 0.0;
     103                        JLabel offsetLabel = new JLabel(offsetDistance > 0.2 ? ImageryOffsetTools.formatDistance(offsetDistance) : "",
     104                                offsetIcon, SwingConstants.CENTER);
     105                        Font offsetFont = new Font(offsetLabel.getFont().getName(), Font.PLAIN, offsetLabel.getFont().getSize() - 2);
     106                        offsetLabel.setFont(offsetFont);
     107                        offsetLabel.setHorizontalTextPosition(SwingConstants.CENTER);
     108                        offsetLabel.setVerticalTextPosition(SwingConstants.BOTTOM);
     109
     110                        Box topLine = new Box(BoxLayout.X_AXIS);
     111                        topLine.add(authorAndDateLabel);
     112                        topLine.add(Box.createHorizontalGlue());
     113                        topLine.add(Box.createHorizontalStrut(10));
     114                        topLine.add(distanceLabel);
     115
     116                        JPanel p = new JPanel(new BorderLayout(10, 5));
     117                        p.setOpaque(false);
     118                        p.add(topLine, BorderLayout.NORTH);
     119                        p.add(offsetLabel, BorderLayout.WEST);
     120                        p.add(descriptionLabel, BorderLayout.CENTER);
     121                        add(p);
    102122    }
    103123
    104124    /**
    105125     * Calculates length and direction for two points in the imagery offset object.
    106      * @see #getLengthAndDirection(iodb.ImageryOffset, double, double) 
    107      */
    108     private double[] getLengthAndDirection( ImageryOffset offset ) {
     126     * @see #getLengthAndDirection(iodb.ImageryOffset, double, double)
     127     */
     128    private double[] getLengthAndDirection(ImageryOffset offset) {
    109129        ImageryLayer layer = ImageryOffsetTools.getTopImageryLayer();
    110130        double[] dxy = layer == null ? new double[] {0.0, 0.0} : new double[] {layer.getDx(), layer.getDy()};
     
    118138     * @see #getLengthAndDirection(iodb.ImageryOffset)
    119139     */
    120     public static double[] getLengthAndDirection( ImageryOffset offset, double dx, double dy ) {
     140    public static double[] getLengthAndDirection(ImageryOffset offset, double dx, double dy) {
    121141        Projection proj = Main.getProjection();
    122142        EastNorth pos = proj.latlon2eastNorth(offset.getPosition());
     
    124144        double length = correctedCenterLL.greatCircleDistance(offset.getImageryPos());
    125145        double direction = length < 1e-2 ? 0.0 : correctedCenterLL.heading(offset.getImageryPos());
    126         if( direction < 0 )
     146        if (direction < 0)
    127147            direction += Math.PI * 2;
    128148        return new double[] {length, direction};
    129149    }
    130150
    131     private static void drawArrow( Graphics g, int cx, int cy, double length, double direction ) {
    132         int dx = (int)Math.round(Math.sin(direction) * length / 2);
    133         int dy = (int)Math.round(Math.cos(direction) * length / 2);
     151    private static void drawArrow(Graphics g, int cx, int cy, double length, double direction) {
     152        int dx = (int) Math.round(Math.sin(direction) * length / 2);
     153        int dy = (int) Math.round(Math.cos(direction) * length / 2);
    134154        g.drawLine(cx - dx, cy - dy, cx + dx, cy + dy);
    135155        double wingLength = Math.max(length / 3, 4);
    136156        double d1 = direction - Math.PI / 6;
    137         int dx1 = (int)Math.round(Math.sin(d1) * wingLength);
    138         int dy1 = (int)Math.round(Math.cos(d1) * wingLength);
     157        int dx1 = (int) Math.round(Math.sin(d1) * wingLength);
     158        int dy1 = (int) Math.round(Math.cos(d1) * wingLength);
    139159        g.drawLine(cx + dx, cy + dy, cx + dx - dx1, cy + dy - dy1);
    140160        double d2 = direction + Math.PI / 6;
    141         int dx2 = (int)Math.round(Math.sin(d2) * wingLength);
    142         int dy2 = (int)Math.round(Math.cos(d2) * wingLength);
     161        int dx2 = (int) Math.round(Math.sin(d2) * wingLength);
     162        int dy2 = (int) Math.round(Math.cos(d2) * wingLength);
    143163        g.drawLine(cx + dx, cy + dy, cx + dx - dx2, cy + dy - dy2);
    144164    }
     
    159179         * of an arrow if they're needed.
    160180         */
    161         public OffsetIcon( ImageryOffsetBase offset ) {
     181        OffsetIcon(ImageryOffsetBase offset) {
    162182            isDeprecated = offset.isDeprecated();
    163183            isCalibration = offset instanceof CalibrationObject;
    164             if( offset instanceof ImageryOffset ) {
     184            if (offset instanceof ImageryOffset) {
    165185                background = ImageProvider.get("offset");
    166                 double[] ld = getLengthAndDirection((ImageryOffset)offset);
     186                double[] ld = getLengthAndDirection((ImageryOffset) offset);
    167187                distance = ld[0];
    168188                direction = ld[1];
     
    179199         * Paints the base image and adds to it according to the offset.
    180200         */
    181         public void paintIcon( Component comp, Graphics g, int x, int y ) {
     201        @Override
     202        public void paintIcon(Component comp, Graphics g, int x, int y) {
    182203            background.paintIcon(comp, g, x, y);
    183204
    184             Graphics2D g2 = (Graphics2D)g.create();
     205            Graphics2D g2 = (Graphics2D) g.create();
    185206            g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
    186             if( !isCalibration ) {
     207            if (!isCalibration) {
    187208                g2.setColor(Color.black);
    188209                Point c = new Point(x + getIconWidth() / 2, y + getIconHeight() / 2);
    189                 if( distance < 1e-2 ) {
     210                if (distance < 1e-2) {
    190211                    // no offset
    191212                    g2.fillOval(c.x - 3, c.y - 3, 7, 7);
     
    197218                }
    198219            }
    199             if( isDeprecated ) {
     220            if (isDeprecated) {
    200221                // big red X
    201222                g2.setColor(Color.red);
     
    207228        }
    208229
     230        @Override
    209231        public int getIconWidth() {
    210232            return background.getIconWidth();
    211233        }
    212234
     235        @Override
    213236        public int getIconHeight() {
    214237            return background.getIconHeight();
     
    223246        private double direction;
    224247
    225         public DirectionIcon( LatLon to ) {
     248        DirectionIcon(LatLon to) {
    226249            this.to = to;
    227250        }
    228251
    229         public void updateIcon( LatLon from ) {
     252        public void updateIcon(LatLon from) {
    230253            distance = from.greatCircleDistance(to);
    231254            direction = to.heading(from);
     
    235258         * Paints the base image and adds to it according to the offset.
    236259         */
    237         public void paintIcon( Component comp, Graphics g, int x, int y ) {
    238             Graphics2D g2 = (Graphics2D)g.create();
     260        @Override
     261        public void paintIcon(Component comp, Graphics g, int x, int y) {
     262            Graphics2D g2 = (Graphics2D) g.create();
    239263            g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
    240264            g2.setColor(Color.black);
    241265            Point c = new Point(x + getIconWidth() / 2, y + getIconHeight() / 2);
    242             if( distance < 1 ) {
     266            if (distance < 1) {
    243267                // no offset
    244268                int r = 2;
     
    251275        }
    252276
     277        @Override
    253278        public int getIconWidth() {
    254279            return SIZE;
    255280        }
    256281
     282        @Override
    257283        public int getIconHeight() {
    258284            return SIZE;
  • applications/editors/josm/plugins/imagery_offset_db/src/iodb/OffsetInfoAction.java

    r29434 r32528  
     1// License: WTFPL. For details, see LICENSE file.
    12package iodb;
     3
     4import static org.openstreetmap.josm.tools.I18n.tr;
    25
    36import java.awt.event.ActionEvent;
     
    58import java.net.URLEncoder;
    69import java.text.SimpleDateFormat;
     10
    711import javax.swing.AbstractAction;
    812import javax.swing.JOptionPane;
     13
    914import org.openstreetmap.josm.Main;
    10 import static org.openstreetmap.josm.tools.I18n.tr;
    1115import org.openstreetmap.josm.tools.ImageProvider;
    1216
    1317/**
    1418 * Display an information box for an offset.
    15  * 
     19 *
    1620 * @author Zverik
    1721 * @license WTFPL
     
    2125
    2226    ImageryOffsetBase offset;
    23    
     27
    2428    /**
    2529     * Initializes the action with an offset object.
    2630     * Calls {@link #getInformationObject(iodb.ImageryOffsetBase)}.
    2731     */
    28     public OffsetInfoAction( ImageryOffsetBase offset ) {
     32    public OffsetInfoAction(ImageryOffsetBase offset) {
    2933        super(tr("Offset Information"));
    3034        putValue(SMALL_ICON, ImageProvider.get("info"));
     
    3741     * to report the given offset.
    3842     */
     43    @Override
    3944    public void actionPerformed(ActionEvent e) {
    4045        Object info = offset == null ? null : getInformationObject(offset);
    41         if( offset.isFlagged() )
     46        if (offset.isFlagged())
    4247            JOptionPane.showMessageDialog(Main.parent, info, ImageryOffsetTools.DIALOG_TITLE, JOptionPane.PLAIN_MESSAGE);
    4348        else {
    4449            int result = JOptionPane.showOptionDialog(Main.parent, info, ImageryOffsetTools.DIALOG_TITLE,
    4550                    JOptionPane.DEFAULT_OPTION, JOptionPane.PLAIN_MESSAGE, null,
    46                     new String[] { "OK", tr("Report this offset") }, null);
    47             if( result == 1 ) {
     51                    new String[] {"OK", tr("Report this offset")}, null);
     52            if (result == 1) {
    4853                // ask for a reason
    4954                Object reason = JOptionPane.showInputDialog(Main.parent,
    5055                        tr("You are to notify moderators of this offset. Why?"),
    5156                        ImageryOffsetTools.DIALOG_TITLE, JOptionPane.PLAIN_MESSAGE);
    52                 if( reason != null && reason.toString().length() > 0 ) {
     57                if (reason != null && reason.toString().length() > 0) {
    5358                    try {
    5459                        String query = "report?id=" + offset.getId()
    55                                 + "&reason=" + URLEncoder.encode(reason.toString(), "UTF8");
     60                        + "&reason=" + URLEncoder.encode(reason.toString(), "UTF8");
    5661                        SimpleOffsetQueryTask reportTask =
    5762                                new SimpleOffsetQueryTask(query, tr("Reporting the offset..."));
    5863                        Main.worker.submit(reportTask);
    59                     } catch( UnsupportedEncodingException ex ) {
    60                         // WTF
     64                    } catch (UnsupportedEncodingException ex) {
     65                        Main.error(ex);
    6166                    }
    6267                }
     
    6873     * Constructs a string with all information about the given offset.
    6974     */
    70     public static Object getInformationObject( ImageryOffsetBase offset ) {
     75    public static Object getInformationObject(ImageryOffsetBase offset) {
    7176        StringBuilder sb = new StringBuilder();
    72         if( offset instanceof ImageryOffset ) {
    73             double odist = ((ImageryOffset)offset).getImageryPos().greatCircleDistance(offset.getPosition());
    74             if( odist < 1e-2 ) odist = 0.0;
     77        if (offset instanceof ImageryOffset) {
     78            double odist = ((ImageryOffset) offset).getImageryPos().greatCircleDistance(offset.getPosition());
     79            if (odist < 1e-2) odist = 0.0;
    7580            sb.append(tr("An imagery offset of {0}", ImageryOffsetTools.formatDistance(odist))).append('\n');
    76             sb.append(tr("Imagery ID")).append(": ").append(((ImageryOffset)offset).getImagery()).append('\n');
     81            sb.append(tr("Imagery ID")).append(": ").append(((ImageryOffset) offset).getImagery()).append('\n');
    7782        } else {
    78             sb.append(tr("A calibration geometry of {0} nodes", ((CalibrationObject)offset).getGeometry().length)).append('\n');
     83            sb.append(tr("A calibration geometry of {0} nodes", ((CalibrationObject) offset).getGeometry().length)).append('\n');
    7984        }
    80        
     85
    8186        double dist = ImageryOffsetTools.getMapCenter().greatCircleDistance(offset.getPosition());
    8287        sb.append(dist < 50 ? tr("Determined right here") : tr("Determined {0} away",
    8388                ImageryOffsetTools.formatDistance(dist)));
    84        
     89
    8590        sb.append("\n\n");
    8691        sb.append(tr("Created by {0} on {1}", offset.getAuthor(),
    8792                DATE_FORMAT.format(offset.getDate()))).append('\n');
    8893        sb.append(tr("Description")).append(": ").append(offset.getDescription());
    89        
    90         if( offset.isDeprecated() ) {
     94
     95        if (offset.isDeprecated()) {
    9196            sb.append("\n\n");
    92             sb.append(tr("Deprecated by {0} on {1}",offset.getAbandonAuthor(),
     97            sb.append(tr("Deprecated by {0} on {1}", offset.getAbandonAuthor(),
    9398                    DATE_FORMAT.format(offset.getAbandonDate()))).append('\n');
    9499            sb.append(tr("Reason")).append(": ").append(offset.getAbandonReason());
    95100        }
    96101
    97         if( offset.isFlagged() ) {
     102        if (offset.isFlagged()) {
    98103            sb.append("\n\n").append(tr("This entry has been reported."));
    99104        }
  • applications/editors/josm/plugins/imagery_offset_db/src/iodb/QuerySuccessListener.java

    r29384 r32528  
     1// License: WTFPL. For details, see LICENSE file.
    12package iodb;
    23
  • applications/editors/josm/plugins/imagery_offset_db/src/iodb/SimpleOffsetQueryTask.java

    r29450 r32528  
     1// License: WTFPL. For details, see LICENSE file.
    12package iodb;
     3
     4import static org.openstreetmap.josm.tools.I18n.tr;
    25
    36import java.io.IOException;
    47import java.io.InputStream;
    5 import java.net.*;
    6 import java.util.*;
    7 import java.util.regex.*;
     8import java.net.HttpURLConnection;
     9import java.net.MalformedURLException;
     10import java.net.URL;
     11import java.util.Scanner;
     12import java.util.regex.Matcher;
     13import java.util.regex.Pattern;
     14
    815import javax.swing.JOptionPane;
     16
    917import org.openstreetmap.josm.Main;
    1018import org.openstreetmap.josm.gui.PleaseWaitRunnable;
    11 import static org.openstreetmap.josm.tools.I18n.tr;
    1219
    1320/**
     
    2936     * @param title A title for the progress monitor.
    3037     */
    31     public SimpleOffsetQueryTask( String query, String title ) {
     38    SimpleOffsetQueryTask(String query, String title) {
    3239        super(ImageryOffsetTools.DIALOG_TITLE);
    3340        this.query = query;
     
    3946     * In case a query was not specified when the object was constructed,
    4047     * it can be set with this method.
    41      * @see #SimpleOffsetQueryTask(java.lang.String, java.lang.String) 
     48     * @see #SimpleOffsetQueryTask(java.lang.String, java.lang.String)
    4249     */
    43     public void setQuery( String query ) {
     50    public void setQuery(String query) {
    4451        this.query = query;
    4552    }
     
    4855     * Install a listener for successful responses. There can be only one.
    4956     */
    50     public void setListener( QuerySuccessListener listener ) {
     57    public void setListener(QuerySuccessListener listener) {
    5158        this.listener = listener;
    5259    }
     
    6875            errorMessage = null;
    6976            doQuery(query);
    70         } catch( UploadException e ) {
     77        } catch (UploadException e) {
    7178            errorMessage = tr("Server has rejected the request") + ":\n" + e.getMessage();
    72         } catch( IOException e ) {
     79        } catch (IOException e) {
    7380            errorMessage = tr("Unable to connect to the server") + "\n" + e.getMessage();
    7481        }
     
    7885     * Sends a request to the imagery offset server. Processes exceptions and
    7986     * return codes, calls {@link #processResponse(java.io.InputStream)} on success.
    80      * @param query
    81      * @throws iodb.SimpleOffsetQueryTask.UploadException
    82      * @throws IOException
    8387     */
    84     private void doQuery( String query ) throws UploadException, IOException {
     88    private void doQuery(String query) throws UploadException, IOException {
    8589        try {
    8690            String serverURL = Main.pref.get("iodb.server.url", "http://offsets.textual.ru/");
    8791            URL url = new URL(serverURL + query);
    88 //            Main.info("IODB URL = " + url); // todo: remove in release
    89             HttpURLConnection connection = (HttpURLConnection)url.openConnection();
     92            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    9093            connection.connect();
    91             if( connection.getResponseCode() != 200 ) {
     94            if (connection.getResponseCode() != 200) {
    9295                throw new IOException("HTTP Response code " + connection.getResponseCode() + " (" + connection.getResponseMessage() + ")");
    9396            }
    9497            InputStream inp = connection.getInputStream();
    95             if( inp == null )
     98            if (inp == null)
    9699                throw new IOException("Empty response");
    97100            try {
    98                 if( !cancelled )
     101                if (!cancelled)
    99102                    processResponse(inp);
    100103            } finally {
    101104                connection.disconnect();
    102105            }
    103         } catch( MalformedURLException ex ) {
     106        } catch (MalformedURLException ex) {
    104107            throw new IOException("Malformed URL: " + ex.getMessage());
    105108        }
     
    120123    @Override
    121124    protected void finish() {
    122         if( errorMessage != null ) {
     125        if (errorMessage != null) {
    123126            JOptionPane.showMessageDialog(Main.parent, errorMessage,
    124127                    ImageryOffsetTools.DIALOG_TITLE, JOptionPane.ERROR_MESSAGE);
    125         } else if( listener != null ) {
     128        } else if (listener != null) {
    126129            listener.queryPassed();
    127130        }
     
    133136     * @throws iodb.SimpleOffsetQueryTask.UploadException Thrown if an error message was found.
    134137     */
    135     protected void processResponse( InputStream inp ) throws UploadException {
     138    protected void processResponse(InputStream inp) throws UploadException {
    136139        String response = "";
    137         if( inp != null ) {
     140        if (inp != null) {
    138141            Scanner sc = new Scanner(inp).useDelimiter("\\A");
    139142            response = sc.hasNext() ? sc.next() : "";
     
    141144        Pattern p = Pattern.compile("<(\\w+)>([^<]+)</\\1>");
    142145        Matcher m = p.matcher(response);
    143         if( m.find() ) {
    144             if( m.group(1).equals("error") ) {
     146        if (m.find()) {
     147            if (m.group(1).equals("error")) {
    145148                throw new UploadException(m.group(2));
    146149            }
     
    154157     */
    155158    public static class UploadException extends Exception {
    156         public UploadException( String message ) {
     159        UploadException(String message) {
    157160            super(message);
    158161        }
  • applications/editors/josm/plugins/imagery_offset_db/src/iodb/StoreImageryOffsetAction.java

    r32462 r32528  
     1// License: WTFPL. For details, see LICENSE file.
    12package iodb;
    23
     
    4849    @Override
    4950    public void actionPerformed(ActionEvent e) {
    50         if( Main.map == null || Main.map.mapView == null )
     51        if (Main.map == null || Main.map.mapView == null)
    5152            return;
    5253
    5354        ImageryLayer layer = ImageryOffsetTools.getTopImageryLayer();
    54         if( layer == null )
     55        if (layer == null)
    5556            return;
    5657
    5758        String userName = JosmUserIdentityManager.getInstance().getUserName();
    58         if( userName == null || userName.length() == 0 ) {
     59        if (userName == null || userName.length() == 0) {
    5960            JOptionPane.showMessageDialog(Main.parent,
    6061                    tr("To store imagery offsets you must be a registered OSM user."),
     
    6263            return;
    6364        }
    64         if( userName.indexOf('@') > 0 )
     65        if (userName.indexOf('@') > 0)
    6566            userName = userName.replace('@', ',');
    6667
     
    6970        if (getLayerManager().getEditDataSet() != null) {
    7071            Collection<OsmPrimitive> selectedObjects = getLayerManager().getEditDataSet().getSelected();
    71             if( selectedObjects.size() == 1 ) {
     72            if (selectedObjects.size() == 1) {
    7273                OsmPrimitive selection = selectedObjects.iterator().next();
    73                 if( (selection instanceof Node || selection instanceof Way) && !selection.isIncomplete() && !selection.isReferredByWays(1) ) {
     74                if ((selection instanceof Node || selection instanceof Way) && !selection.isIncomplete() && !selection.isReferredByWays(1)) {
    7475                    String[] options = new String[] {tr("Store calibration geometry"), tr("Store imagery offset")};
    7576                    int result = JOptionPane.showOptionDialog(Main.parent,
     
    7778                            ImageryOffsetTools.DIALOG_TITLE, JOptionPane.DEFAULT_OPTION, JOptionPane.QUESTION_MESSAGE,
    7879                            null, options, options[0]);
    79                     if( result == 2 || result == JOptionPane.CLOSED_OPTION )
     80                    if (result == 2 || result == JOptionPane.CLOSED_OPTION)
    8081                        return;
    81                     if( result == 0 )
     82                    if (result == 0)
    8283                        calibration = selection;
    8384                }
     
    8889        LatLon center = ImageryOffsetTools.getMapCenter();
    8990        ImageryOffsetBase offsetObj;
    90         if( calibration == null ) {
     91        if (calibration == null) {
    9192            // register imagery offset
    92             if( Math.abs(layer.getDx()) < 1e-8 && Math.abs(layer.getDy()) < 1e-8 ) {
    93                 if( JOptionPane.showConfirmDialog(Main.parent,
     93            if (Math.abs(layer.getDx()) < 1e-8 && Math.abs(layer.getDy()) < 1e-8) {
     94                if (JOptionPane.showConfirmDialog(Main.parent,
    9495                        tr("The topmost imagery layer has no offset. Are you sure you want to upload this?"),
    95                         ImageryOffsetTools.DIALOG_TITLE, JOptionPane.YES_NO_OPTION) != JOptionPane.YES_OPTION )
     96                        ImageryOffsetTools.DIALOG_TITLE, JOptionPane.YES_NO_OPTION) != JOptionPane.YES_OPTION)
    9697                    return;
    9798            }
     
    107108        }
    108109        String description = queryDescription(message);
    109         if( description == null )
     110        if (description == null)
    110111            return;
    111112        offsetObj.setBasicInfo(center, userName, null, null);
     
    117118            offsetObj.putServerParams(params);
    118119            StringBuilder query = null;
    119             for( String key : params.keySet() ) {
    120                 if( query == null ) {
     120            for (String key : params.keySet()) {
     121                if (query == null) {
    121122                    query = new StringBuilder("store?");
    122123                } else {
     
    126127            }
    127128            Main.worker.submit(new SimpleOffsetQueryTask(query.toString(), tr("Uploading a new offset...")));
    128         } catch( UnsupportedEncodingException ex ) {
    129             // WTF
     129        } catch (UnsupportedEncodingException ex) {
     130            Main.error(ex);
    130131        }
    131132    }
     
    137138     * @return Either null or a string 3 to 200 letters long.
    138139     */
    139     public static String queryDescription( Object message ) {
     140    public static String queryDescription(Object message) {
    140141        String reason = null;
    141142        boolean iterated = false;
    142143        boolean ok = false;
    143         while( !ok ) {
    144             Object result = JOptionPane.showInputDialog(Main.parent, message, ImageryOffsetTools.DIALOG_TITLE, JOptionPane.PLAIN_MESSAGE, null, null, reason);
    145             if( result == null || result.toString().length() == 0 ) {
     144        while (!ok) {
     145            Object result = JOptionPane.showInputDialog(Main.parent, message,
     146                    ImageryOffsetTools.DIALOG_TITLE, JOptionPane.PLAIN_MESSAGE, null, null, reason);
     147            if (result == null || result.toString().length() == 0) {
    146148                return null;
    147149            }
    148150            reason = result.toString();
    149             if( reason.length() < 3 || reason.length() > 200 ) {
    150                 if( !iterated ) {
     151            if (reason.length() < 3 || reason.length() > 200) {
     152                if (!iterated) {
    151153                    message = message + "\n" + tr("This string should be 3 to 200 letters long.");
    152154                    iterated = true;
     
    165167    protected void updateEnabledState() {
    166168        boolean state = true;
    167         if( Main.map == null || Main.map.mapView == null || !Main.map.isVisible() )
     169        if (Main.map == null || Main.map.mapView == null || !Main.map.isVisible())
    168170            state = false;
    169         if( ImageryOffsetTools.getTopImageryLayer() == null )
     171        if (ImageryOffsetTools.getTopImageryLayer() == null)
    170172            state = false;
    171173        setEnabled(state);
Note: See TracChangeset for help on using the changeset viewer.