Ignore:
Timestamp:
2009-01-25T13:50:05+01:00 (16 years ago)
Author:
stoecker
Message:

apply patch by xeen for bug #1635

File:
1 edited

Legend:

Unmodified
Added
Removed
  • applications/editors/josm/plugins/DirectUpload/src/org/openstreetmap/josm/plugins/DirectUpload/UploadDataGui.java

    r12778 r13373  
    88
    99package org.openstreetmap.josm.plugins.DirectUpload;
     10
     11import java.awt.BorderLayout;
     12import java.awt.Container;
     13import java.awt.Dimension;
    1014import java.awt.event.ItemEvent;
    11 import static org.openstreetmap.josm.tools.I18n.tr;
    12 
     15import java.awt.GridBagLayout;
     16import java.awt.GridBagConstraints;
     17import java.awt.Toolkit;
    1318import java.io.BufferedOutputStream;
    1419import java.io.DataOutputStream;
     
    2328import java.util.logging.Level;
    2429import java.util.logging.Logger;
     30
     31import javax.swing.BorderFactory;
     32import javax.swing.Box;
     33import javax.swing.JButton;
     34import javax.swing.JCheckBox;
     35import javax.swing.JLabel;
    2536import javax.swing.JOptionPane;
     37import javax.swing.JPanel;
     38import javax.swing.JScrollPane;
     39import javax.swing.JTextArea;
    2640import javax.swing.JTextField;
    27 import java.awt.Container;
    28 import java.awt.GridBagLayout;
    29 import java.awt.GridBagConstraints;
     41import javax.swing.UIManager;
     42
    3043import org.openstreetmap.josm.Main;
    3144import org.openstreetmap.josm.data.gpx.GpxData;
     
    3447import org.openstreetmap.josm.gui.layer.GpxLayer;
    3548import org.openstreetmap.josm.gui.MapView;
     49import org.openstreetmap.josm.tools.Base64;
     50import org.openstreetmap.josm.tools.GBC;
     51import static org.openstreetmap.josm.tools.I18n.tr;
    3652
    3753/**
     
    4056 */
    4157public class UploadDataGui extends javax.swing.JFrame {
    42 
    43  String tagging;
    44  String Descriptionfield;
    45  String urlDescription;
    46  String urlTags;
    47  String UserName;
    48  String PassWord;
    49  //GpxData gpxData;
    50 
    51         public static final String API_VERSION = "0.5";
    52         private static final String BASE64_ENC = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
    53         private static final String BOUNDARY = "----------------------------d10f7aa230e8";
    54         private static final String LINE_END = "\r\n";
    55 
    56         boolean dfield;
    57         boolean taggy;
    58         boolean choosy;
    59         boolean user;
    60         boolean pass;
    61         boolean publicheck;
    62 
    63         DateFormat dateFormat = new SimpleDateFormat("yyMMddHHmmss");
    64         Date date = new Date();
    65         String datename = dateFormat.format(date);
     58    private JTextArea OutputDisplay = new JTextArea();
     59    private JTextField descriptionField = new JTextField();
     60    private JTextField tagsField = new JTextField();
     61    private JCheckBox publicCheckbox = new JCheckBox();
     62
     63    public static final String API_VERSION = "0.5";
     64    private static final String BOUNDARY = "----------------------------d10f7aa230e8";
     65    private static final String LINE_END = "\r\n";
     66
     67    private String datename = new SimpleDateFormat("yyMMddHHmmss").format(new Date());
    6668
    6769    /** Creates new form UploadDataGui */
    6870    public UploadDataGui() {
     71        setTitle(tr("Upload Traces"));
    6972        initComponents();
    7073    }
    7174
    72 
    73     /** This method is called from within the constructor to
    74      * initialize the form.
    75      * WARNING: Do NOT modify this code. The content of this method is
    76      * always regenerated by the Form Editor.
    77      */
    78     @SuppressWarnings("unchecked")
    79     // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    8075    private void initComponents() {
    81 
    82         jScrollPane1 = new javax.swing.JScrollPane();
    83         OutputDisplay = new javax.swing.JTextArea();
    84         OkButton = new javax.swing.JButton();
    85         CancelButton = new javax.swing.JButton();
    86         jLabel2 = new javax.swing.JLabel();
    87         PublicTrace = new javax.swing.JCheckBox();
    88         jLabel1 = new javax.swing.JLabel();
    89         descriptionfield = new javax.swing.JTextField();
    90         jLabel3 = new javax.swing.JLabel();
    91         tagfield = new javax.swing.JTextField();
    92 
    9376        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
    9477        setAlwaysOnTop(true);
    95 
    96         OutputDisplay.setColumns(20);
    97         OutputDisplay.setRows(5);
     78        setPreferredSize(new Dimension(350,200));
     79
     80        // Display Center Screen
     81        Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
     82        Dimension labelSize = getPreferredSize();
     83        setLocation(screenSize.width / 2 - (labelSize.width / 2), screenSize.height / 2 - (labelSize.height / 2));
     84
     85        OutputDisplay.setBackground(UIManager.getColor("Panel.background"));
     86        OutputDisplay.setBorder(BorderFactory.createEmptyBorder(0,0,0,0));
     87        OutputDisplay.setEditable(false);
     88        OutputDisplay.setFont(new JLabel().getFont());
     89        OutputDisplay.setLineWrap(true);
     90        OutputDisplay.setWrapStyleWord(true);
     91
     92        JScrollPane jScrollPane1 = new JScrollPane();
    9893        jScrollPane1.setViewportView(OutputDisplay);
    9994
    100         OkButton.setText("Ok");
     95        JButton OkButton = new JButton(tr("Upload GPX track"));
    10196        OkButton.addActionListener(new java.awt.event.ActionListener() {
    10297            public void actionPerformed(java.awt.event.ActionEvent evt) {
     
    105100        });
    106101
    107         CancelButton.setText("Cancel");
     102        JButton CancelButton = new JButton(tr("Cancel"));
    108103        CancelButton.addActionListener(new java.awt.event.ActionListener() {
    109104            public void actionPerformed(java.awt.event.ActionEvent evt) {
     
    112107        });
    113108
    114         jLabel2.setFont(new java.awt.Font("DejaVu Sans", 1, 14));
    115         jLabel2.setText("Direct Upload to OpenStreetMap");
    116 
    117         PublicTrace.setText("Public");
    118         PublicTrace.setToolTipText("Selected makes your trace public in openstreetmap.org");
    119         PublicTrace.addItemListener(new java.awt.event.ItemListener() {
    120             public void itemStateChanged(java.awt.event.ItemEvent evt) {
    121                 PublicTraceItemStateChanged(evt);
    122             }
    123         });
    124 
    125         jLabel1.setText("Description");
    126 
    127         descriptionfield.setToolTipText("Please enter Description about your trace.");
    128         descriptionfield.addFocusListener(new java.awt.event.FocusAdapter() {
    129             public void focusLost(java.awt.event.FocusEvent evt) {
    130                 descriptionfieldFocusLost(evt);
    131             }
    132         });
    133 
    134         jLabel3.setText("Tags");
    135 
    136         tagfield.setToolTipText("Please enter tags about your trace.");
    137         tagfield.addFocusListener(new java.awt.event.FocusAdapter() {
    138             public void focusLost(java.awt.event.FocusEvent evt) {
    139                 tagfieldFocusLost(evt);
    140             }
    141         });
    142 
    143 
    144 
    145     Container contentPane = getContentPane();
    146     contentPane.setLayout(new GridBagLayout());
    147     GridBagConstraints c = new GridBagConstraints();
    148 
    149     c.gridx = 0;
    150     c.gridy = 0;
    151     c.gridwidth = 2;
    152     c.fill = 1;
    153     contentPane.add(OutputDisplay, c);
    154 
    155     c.gridwidth = 1;
    156     c.gridy = 1;
    157     contentPane.add(jLabel3, c);
    158     c.gridx = 1;
    159     contentPane.add(tagfield, c);
    160 
    161     c.gridy = 2; c.gridx = 0;
    162     contentPane.add(jLabel1, c);
    163     c.gridx = 1;
    164     contentPane.add(descriptionfield, c);
    165 
    166     c.gridy = 3; c.gridx = 0;
    167     contentPane.add(jLabel2, c);
    168     c.gridx = 1;
    169     contentPane.add(PublicTrace, c);
    170 
    171     c.gridy = 4; c.gridx = 0;
    172     contentPane.add(CancelButton, c);
    173     c.gridx = 1;
    174     contentPane.add(OkButton, c);
     109        JLabel directUploadLabel = new JLabel(tr("Direct Upload to OpenStreetMap"));
     110
     111        publicCheckbox.setText(tr("Public"));
     112        publicCheckbox.setToolTipText(tr("Selected makes your trace public in openstreetmap.org"));
     113
     114        JLabel descriptionLabel = new JLabel(tr("Description"));
     115        descriptionField.setToolTipText("Please enter Description about your trace.");
     116
     117        JLabel tagsLabel = new JLabel(tr("Tags"));
     118        tagsField.setToolTipText("Please enter tags about your trace.");
     119
     120        JPanel p = new JPanel();
     121        p.setLayout(new GridBagLayout());
     122
     123        p.add(OutputDisplay, GBC.eol().fill());
     124
     125        p.add(tagsLabel, GBC.std().insets(0,10,0,0));
     126        p.add(tagsField, GBC.eol().fill(GBC.HORIZONTAL));
     127
     128        p.add(descriptionLabel, GBC.std().insets(0,10,0,0));
     129        p.add(descriptionField, GBC.eol().fill(GBC.HORIZONTAL));
     130
     131        p.add(publicCheckbox, GBC.eol());
     132
     133        p.add(CancelButton, GBC.std());
     134        p.add(OkButton, GBC.eol().fill(GBC.HORIZONTAL));
     135
     136        getContentPane().setLayout(new GridBagLayout());
     137        getContentPane().add(p, GBC.eol().insets(10,10,10,10).fill());
    175138
    176139        pack();
    177     }// </editor-fold>//GEN-END:initComponents
    178 
    179 
    180 
    181 public void upload(String username, String password, String Descriptionfield, String tagging , GpxData gpxData ) throws IOException {
    182         OutputDisplay.setText("Starting to upload selected file to openstreetmap.org");
    183 
    184     try {
    185 
    186         urlDescription = Descriptionfield.replaceAll("\\.;&?,/","_");
    187         if (urlDescription == null || urlDescription.length() == 0) {
    188              OutputDisplay.setText("No description provided .Please provide some description . For the time being ignore the exception error ");
    189 
    190         }
    191            urlTags = tagging.replaceAll("\\\\.;&?,/","_");
    192 
    193 
    194         URL url = new URL("http://www.openstreetmap.org/api/" + API_VERSION + "/gpx/create");
    195             System.err.println("url: " + url);
    196             OutputDisplay.setText("Uploading in Progress");
    197         HttpURLConnection connect = (HttpURLConnection) url.openConnection();
    198         connect.setConnectTimeout(15000);
    199         connect.setRequestMethod("POST");
    200         connect.setDoOutput(true);
    201         connect.addRequestProperty("Authorization", "Basic "+encodeBase64(username+":"+password));
    202         connect.addRequestProperty("Content-Type", "multipart/form-data; boundary="+BOUNDARY);
    203         connect.addRequestProperty("Connection", "close"); // counterpart of keep-alive
    204         connect.addRequestProperty("Expect", "");
    205         connect.connect();
    206         DataOutputStream out  = new DataOutputStream(new BufferedOutputStream(connect.getOutputStream()));
    207         writeContentDispositionGpxData(out, "file", gpxData);
    208         writeContentDisposition(out, "description", urlDescription);
    209         writeContentDisposition(out, "tags", urlTags);
    210            if(publicheck) {
    211         System.out.println(publicheck);
    212         writeContentDisposition(out, "public", "1");
    213            } else {
    214         writeContentDisposition(out, "public", "0");
    215            }
    216         out.writeBytes("--" + BOUNDARY + "--" + LINE_END);
    217         out.flush();
    218 
    219         int returnCode = connect.getResponseCode();
     140
     141        // If no GPX layer is selected, select one for the user if there is only one GPX layer
     142        if(Main.map != null && Main.map.mapView != null) {
     143            MapView mv=Main.map.mapView;
     144            if(!(mv.getActiveLayer() instanceof GpxLayer)) {
     145                Layer lastLayer=null;
     146                int layerCount=0;
     147                for (Layer l : mv.getAllLayers()) {
     148                    if(l instanceof GpxLayer) {
     149                        lastLayer = l;
     150                        layerCount++;
     151                    }
     152                }
     153                if(layerCount == 1) mv.setActiveLayer(lastLayer);
     154            }
     155
     156            if(mv.getActiveLayer() instanceof GpxLayer) {
     157                GpxData data=((GpxLayer)Main.map.mapView.getActiveLayer()).data;
     158                descriptionField.setText(data.storageFile.getName().replaceAll("[&?/\\\\]"," ").replaceAll("(\\.[^.]*)$",""));
     159            }
     160        }
     161
     162        boolean x=checkForGPXLayer();
     163    }
     164
     165    public void upload(String username, String password, String description, String tags, Boolean isPublic, GpxData gpxData) throws IOException {
     166        if(checkForErrors(username, password, description, gpxData))
     167            return;
     168
     169        description = description.replaceAll("[&?/\\\\]"," ");
     170        tags = tags.replaceAll("[&?/\\\\.,;]"," ");
     171
     172        OutputDisplay.setText(tr("Starting to upload selected file to openstreetmap.org"));
     173
     174        try {
     175            URL url = new URL("http://www.openstreetmap.org/api/" + API_VERSION + "/gpx/create");
     176            //System.err.println("url: " + url);
     177            //OutputDisplay.setText("Uploading in Progress");
     178            HttpURLConnection connect = (HttpURLConnection) url.openConnection();
     179            connect.setConnectTimeout(15000);
     180            connect.setRequestMethod("POST");
     181            connect.setDoOutput(true);
     182            connect.addRequestProperty("Authorization", "Basic " + Base64.encode(username + ":" + password));
     183            connect.addRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);
     184            connect.addRequestProperty("Connection", "close"); // counterpart of keep-alive
     185            connect.addRequestProperty("Expect", "");
     186            connect.connect();
     187            DataOutputStream out  = new DataOutputStream(new BufferedOutputStream(connect.getOutputStream()));
     188
     189            writeContentDispositionGpxData(out, "file", gpxData);
     190            writeContentDisposition(out, "description", description);
     191            writeContentDisposition(out, "tags", (tags!=null && tags.length()>0) ? tags : "");
     192            writeContentDisposition(out, "public", isPublic ? "1" : "0");
     193
     194            out.writeBytes("--" + BOUNDARY + "--" + LINE_END);
     195            out.flush();
     196
     197            int returnCode = connect.getResponseCode();
    220198            String returnMsg = connect.getResponseMessage();
    221             System.err.println(returnCode);
     199            //System.err.println(returnCode);
    222200            OutputDisplay.setText(returnMsg);
    223         if (returnCode != 200) {
    224             if (connect.getHeaderField("Error") != null)
    225                returnMsg += "\n" + connect.getHeaderField("Error");
     201
     202            if (returnCode != 200) {
     203                if (connect.getHeaderField("Error") != null)
     204                    returnMsg += "\n" + connect.getHeaderField("Error");
     205                connect.disconnect();
     206            }
     207            out.close();
    226208            connect.disconnect();
    227        }
    228         out.close();
    229         connect.disconnect();
    230209
    231210        } catch(UnsupportedEncodingException ignore) {
    232211        } catch (MalformedURLException e) {
    233                 OutputDisplay.setText("Cant Upload .");
    234                 e.printStackTrace();
    235     }
    236 
    237 }
    238 
    239 
    240 
    241  public static String getPreferencesDir() {
    242     if (System.getenv("APPDATA") != null)
    243        return System.getenv("APPDATA")+"/JOSM/";
    244        return System.getProperty("user.home")+"/.josm/";
    245     }
    246 
    247 private void OkButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_OkButtonActionPerformed
    248      GpxData gpxData;
    249 
    250         UserName  =  Main.pref.get("osm-server.username");
    251         PassWord =   Main.pref.get("osm-server.password");
    252 
    253         if(Main.map == null || Main.map.mapView == null ||Main.map.mapView.getActiveLayer() == null ||
    254                 !(Main.map.mapView.getActiveLayer() instanceof GpxLayer)){
    255                 JOptionPane.showMessageDialog(Main.parent,
    256                 tr("No GPX layer selected. Cannot upload a trace.")
    257                 );
    258                 return;
    259         }
    260         gpxData = ((GpxLayer)Main.map.mapView.getActiveLayer()).data;
    261                 System.out.println(Descriptionfield);
     212            OutputDisplay.setText(tr("Error while uploading"));
     213            e.printStackTrace();
     214        }
     215    }
     216
     217
     218    private boolean checkForErrors(String username, String password, String description, GpxData gpxData) {
     219        String errors="";
     220        if(description == null || description.length() == 0)
     221            errors += tr("No description provided. Please provide some description.");
     222
     223        if(gpxData == null)
     224            errors += tr("No GPX layer selected. Cannot upload a trace.");
     225
     226        if(username == null || username.length()==0)
     227            errors += tr("No username provided.");
     228
     229        if(password == null || password.length()==0)
     230            errors += tr("No password provided.");
     231
     232        OutputDisplay.setText(errors);
     233        return errors.length() > 0;
     234    }
     235
     236    private boolean checkForGPXLayer() {
     237        if(Main.map == null || Main.map.mapView == null || Main.map.mapView.getActiveLayer() == null || !(Main.map.mapView.getActiveLayer() instanceof GpxLayer)) {
     238            OutputDisplay.setText(tr("No GPX layer selected. Cannot upload a trace."));
     239            return true;
     240        }
     241        return false;
     242    }
     243
     244    private void OkButtonActionPerformed(java.awt.event.ActionEvent evt) {
     245        if(checkForGPXLayer()) return;
     246
     247        //System.out.println(Descriptionfield);
    262248        try {
    263                 upload(UserName,PassWord,Descriptionfield ,tagging ,gpxData) ;
     249            upload(Main.pref.get("osm-server.username"),
     250                   Main.pref.get("osm-server.password"),
     251                   descriptionField.getText(),
     252                   tagsField.getText(),
     253                   publicCheckbox.isSelected(),
     254                   ((GpxLayer)Main.map.mapView.getActiveLayer()).data
     255            );
    264256        } catch (IOException ex) {
    265                 Logger.getLogger(UploadDataGui.class.getName()).log(Level.SEVERE, null, ex);
    266     }
    267 
    268 }//GEN-LAST:event_OkButtonActionPerformed
    269 
    270 private void CancelButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_CancelButtonActionPerformed
     257            Logger.getLogger(UploadDataGui.class.getName()).log(Level.SEVERE, null, ex);
     258        }
     259    }
     260
     261    private void CancelButtonActionPerformed(java.awt.event.ActionEvent evt) {
    271262        dispose();
    272 }//GEN-LAST:event_CancelButtonActionPerformed
    273 
    274 private void PublicTraceItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_PublicTraceItemStateChanged
    275 
    276     if (evt.getStateChange() == ItemEvent.SELECTED) {
    277         publicheck = true;
    278 
    279     }
    280 }//GEN-LAST:event_PublicTraceItemStateChanged
    281 
    282 private void descriptionfieldFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_descriptionfieldFocusLost
    283 
    284      JTextField Descsel = (JTextField)evt.getSource();
    285         Descriptionfield =  Descsel.getText();
    286 
    287 }//GEN-LAST:event_descriptionfieldFocusLost
    288 
    289 private void tagfieldFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_tagfieldFocusLost
    290 
    291      JTextField Tagsel = (JTextField)evt.getSource();
    292         tagging =  Tagsel.getText();
    293 
    294 }//GEN-LAST:event_tagfieldFocusLost
    295 
     263    }
    296264
    297265    private void writeContentDisposition(DataOutputStream out, String name, String value) throws IOException {
     
    300268        out.writeBytes(LINE_END);
    301269        out.writeBytes(value + LINE_END);
    302 
    303     }
    304 
    305     private void writeContentDispositionGpxData(DataOutputStream out, String name, GpxData gpxData ) throws IOException {
    306 
     270    }
     271
     272    private void writeContentDispositionGpxData(DataOutputStream out, String name, GpxData gpxData) throws IOException {
    307273        out.writeBytes("--" + BOUNDARY + LINE_END);
    308274        out.writeBytes("Content-Disposition: form-data; name=\"" + name + "\"; filename=\"" + datename +".gpx" + "\"" + LINE_END);
    309         //out.writeBytes("Content-Disposition: form-data; name=\"" + name + "\"; filename=\"" + gpxData.storageFile.getName() + "\"" + LINE_END);
    310275        out.writeBytes("Content-Type: application/octet-stream" + LINE_END);
    311276        out.writeBytes(LINE_END);
    312277
    313         OutputDisplay.setText("Transferring data to server");
    314             new GpxWriter(out).write(gpxData);
     278        OutputDisplay.setText(tr("Transferring data to server"));
     279        new GpxWriter(out).write(gpxData);
    315280        out.flush();
    316281        out.writeBytes(LINE_END);
    317 
    318     }
    319 
    320  // Taken from Christof Dallermassal java class :
    321 public String encodeBase64(String s) {
    322         StringBuilder out = new StringBuilder();
    323         for (int i = 0; i < (s.length()+2)/3; ++i) {
    324             int l = Math.min(3, s.length()-i*3);
    325             String buf = s.substring(i*3, i*3+l);
    326             out.append(BASE64_ENC.charAt(buf.charAt(0)>>2));
    327             out.append(BASE64_ENC.charAt((buf.charAt(0) & 0x03) << 4 | (l==1?0:(buf.charAt(1) & 0xf0) >> 4)));
    328             out.append(l>1 ? BASE64_ENC.charAt((buf.charAt(1) & 0x0f) << 2 | (l==2 ? 0 : (buf.charAt(2) & 0xc0) >> 6)) : '=');
    329             out.append(l>2 ? BASE64_ENC.charAt(buf.charAt(2) & 0x3f) : '=');
    330 
    331         }
    332         return out.toString();
    333         }
    334 
    335     // Variables declaration - do not modify//GEN-BEGIN:variables
    336     private javax.swing.JButton CancelButton;
    337     private javax.swing.JButton OkButton;
    338     private javax.swing.JTextArea OutputDisplay;
    339     private javax.swing.JCheckBox PublicTrace;
    340     private javax.swing.JTextField descriptionfield;
    341     private javax.swing.JLabel jLabel1;
    342     private javax.swing.JLabel jLabel2;
    343     private javax.swing.JLabel jLabel3;
    344     private javax.swing.JScrollPane jScrollPane1;
    345     private javax.swing.JTextField tagfield;
    346     // End of variables declaration//GEN-END:variables
    347 
     282    }
    348283}
Note: See TracChangeset for help on using the changeset viewer.