Ignore:
Timestamp:
2018-08-18T19:17:07+02:00 (6 years ago)
Author:
donvip
Message:

update to JOSM 14153

Location:
applications/editors/josm/plugins/OSMRecPlugin
Files:
14 edited

Legend:

Unmodified
Added
Removed
  • applications/editors/josm/plugins/OSMRecPlugin/build.xml

    r34144 r34539  
    33
    44    <!-- enter the *lowest* JOSM version this plugin is currently compatible with -->
    5     <property name="plugin.main.version" value="13597"/>
     5    <property name="plugin.main.version" value="14153"/>
    66    <property name="plugin.version" value="2.1"/>
    77
  • applications/editors/josm/plugins/OSMRecPlugin/src/org/openstreetmap/josm/plugins/osmrec/OSMRecPlugin.java

    r33525 r34539  
    88
    99/**
    10  *
     10 * OSM rec plugin
    1111 * @author imis-nkarag
    1212 */
    1313public class OSMRecPlugin extends Plugin {
    1414
    15         private final MenuExportAction menuExportAction;
    16         private static MapFrame mapFrame;
    17         public OSMRecPlugin plugin;
     15    private final MenuExportAction menuExportAction;
     16    private static MapFrame mapFrame;
     17    public OSMRecPlugin plugin;
    1818
    19         public OSMRecPlugin(PluginInformation info) { // NO_UCD (unused code)
    20                 super(info);
    21                 menuExportAction = new MenuExportAction();
    22                 MainApplication.getMenu().toolsMenu.add(menuExportAction);
    23         }
     19    public OSMRecPlugin(PluginInformation info) { // NO_UCD (unused code)
     20        super(info);
     21        menuExportAction = new MenuExportAction();
     22        MainApplication.getMenu().toolsMenu.add(menuExportAction);
     23    }
    2424
    25         @Override
    26         public void mapFrameInitialized(MapFrame oldFrame, MapFrame newFrame) {
    27                 if (oldFrame == null && newFrame != null) { // map frame added
    28                         setCurrentMapFrame(newFrame);
    29                         setState(this);
    30                 }
    31         }
     25    @Override
     26    public void mapFrameInitialized(MapFrame oldFrame, MapFrame newFrame) {
     27        if (oldFrame == null && newFrame != null) { // map frame added
     28            setCurrentMapFrame(newFrame);
     29            setState(this);
     30        }
     31    }
    3232
    33         private void setCurrentMapFrame(MapFrame newFrame) {
    34                 OSMRecPlugin.mapFrame = newFrame;
    35         }
     33    private void setCurrentMapFrame(MapFrame newFrame) {
     34        OSMRecPlugin.mapFrame = newFrame;
     35    }
    3636
    37         public static MapFrame getCurrentMapFrame() {
    38                 return mapFrame;
    39         }
     37    public static MapFrame getCurrentMapFrame() {
     38        return mapFrame;
     39    }
    4040
    41         private void setState(OSMRecPlugin plugin) {
    42                 this.plugin = plugin;
    43         }
     41    private void setState(OSMRecPlugin plugin) {
     42        this.plugin = plugin;
     43    }
    4444
    45         public OSMRecPlugin getState() {
    46                 return plugin;
    47         }
     45    public OSMRecPlugin getState() {
     46        return plugin;
     47    }
    4848
    49         //    @Override
    50         //    public PreferenceSetting getPreferenceSetting() {
    51         //        return new PreferenceEditor();
    52         //    }
     49    //    @Override
     50    //    public PreferenceSetting getPreferenceSetting() {
     51    //        return new PreferenceEditor();
     52    //    }
    5353}
  • applications/editors/josm/plugins/OSMRecPlugin/src/org/openstreetmap/josm/plugins/osmrec/OSMRecPluginHelper.java

    r34144 r34539  
    9090import org.opengis.referencing.operation.MathTransform;
    9191import org.opengis.referencing.operation.TransformException;
    92 import org.openstreetmap.josm.Main;
    9392import org.openstreetmap.josm.actions.JosmAction;
    9493import org.openstreetmap.josm.command.ChangePropertyCommand;
     94import org.openstreetmap.josm.data.UndoRedoHandler;
    9595import org.openstreetmap.josm.data.osm.Node;
     96import org.openstreetmap.josm.data.osm.OsmDataManager;
    9697import org.openstreetmap.josm.data.osm.OsmPrimitive;
    9798import org.openstreetmap.josm.data.osm.Tag;
     
    122123import org.openstreetmap.josm.plugins.osmrec.parsers.TextualStatistics;
    123124import org.openstreetmap.josm.plugins.osmrec.personalization.UserDataExtractAndTrainWorker;
     125import org.openstreetmap.josm.spi.preferences.Config;
    124126import org.openstreetmap.josm.tools.GBC;
    125127import org.openstreetmap.josm.tools.Logging;
     
    165167    private String customSVMModelPath;
    166168    private final String combinedModelClasses;
    167     private final String combinedModel;
    168169
    169170    // Selection that we are editing by using both dialogs
     
    195196    OSMRecPluginHelper(DefaultTableModel propertyData, Map<String, Map<String, Integer>> valueCount) {
    196197        this.tagData = propertyData;
    197         fileHistory = Main.pref.getList("file-open.history");
     198        fileHistory = Config.getPref().getList("file-open.history");
    198199        if (!fileHistory.isEmpty()) {
    199200            MAIN_PATH = (String) fileHistory.toArray()[0];
     
    204205        TEXTUAL_LIST_PATH = MODEL_PATH + "/textualList.txt";
    205206        combinedModelClasses = MODEL_PATH + "/combinedModel.1";
    206         combinedModel = MODEL_PATH + "/combinedModel.0";
    207207        bestModelPath = MODEL_PATH + "/best_model";
    208208        customSVMModelPath = bestModelPath;
     
    221221    public void addTag() {
    222222        changedKey = null;
    223         sel = Main.main.getInProgressSelection();
     223        sel = OsmDataManager.getInstance().getInProgressSelection();
    224224        if (sel == null || sel.isEmpty()) return;
    225225
     
    243243    public void editTag(final int row, boolean focusOnKey) {
    244244        changedKey = null;
    245         sel = Main.main.getInProgressSelection();
     245        sel = OsmDataManager.getInstance().getInProgressSelection();
    246246        String key = "";
    247247
    248         @SuppressWarnings("unchecked")
    249248        Map<String, Integer> dumPar = new HashMap<>();
    250249        dumPar.put(" ", -1);
     
    282281        if (PROPERTY_REMEMBER_TAGS.get() && recentTags.isEmpty()) {
    283282            recentTags.clear();
    284             Collection<String> c = Main.pref.getList("properties.recent-tags");
     283            Collection<String> c = Config.getPref().getList("properties.recent-tags");
    285284            Iterator<String> it = c.iterator();
    286285            String key, value;
     
    303302                c.add(t.getValue());
    304303            }
    305             Main.pref.putList("properties.recent-tags", c);
     304            Config.getPref().putList("properties.recent-tags", c);
    306305        }
    307306    }
     
    315314    private boolean warnOverwriteKey(String action, String togglePref) {
    316315        ExtendedDialog ed = new ExtendedDialog(
    317                 Main.parent,
     316                MainApplication.getMainFrame(),
    318317                tr("Overwrite key"),
    319318                new String[]{tr("Replace"), tr("Cancel")});
     
    367366
    368367        private TrainingDialog(String key, int row, Map<String, Integer> map, final boolean initialFocusOnKey) {
    369             super(Main.parent, tr("Training process configuration"), new String[] {tr("Cancel")});
     368            super(MainApplication.getMainFrame(), tr("Training process configuration"), new String[] {tr("Cancel")});
    370369
    371370            setButtonIcons(new String[] {"ok", "cancel"});
     
    424423            daysField.setColumns(FIELD_COLUMNS);
    425424
    426             Collection<String> fileHistory = Main.pref.getList("file-open.history");
     425            Collection<String> fileHistory = Config.getPref().getList("file-open.history");
    427426            if (!fileHistory.isEmpty()) {
    428427                inputFileField.setText(MAIN_PATH);
     
    930929
    931930            setRememberWindowGeometry(getClass().getName() + ".geometry",
    932                     WindowGeometry.centerInWindow(Main.parent, size));
     931                    WindowGeometry.centerInWindow(MainApplication.getMainFrame(), size));
    933932        }
    934933
     
    12001199            };
    12011200
    1202             dlg = pane.createDialog(Main.parent, tr("Model Settings"));
     1201            dlg = pane.createDialog(MainApplication.getMainFrame(), tr("Model Settings"));
    12031202            dlg.setVisible(true);
    12041203        }
     
    14301429
    14311430        AddTagsDialog() {
    1432             super(Main.parent, tr("Add value?"), new String[] {tr("OK"), tr("Cancel")});
     1431            super(MainApplication.getMainFrame(), tr("Add value?"), new String[] {tr("OK"), tr("Cancel")});
    14331432            setButtonIcons(new String[] {"ok", "cancel"});
    14341433            setCancelButton(2);
     
    18311830            AutoCompletionManager.rememberUserInput(key, value, false);
    18321831            commandCount++;
    1833             MainApplication.undoRedo.add(new ChangePropertyCommand(sel, key, value));
     1832            UndoRedoHandler.getInstance().add(new ChangePropertyCommand(sel, key, value));
    18341833            changedKey = key;
    18351834        }
    18361835
    18371836        public void undoAllTagsAdding() {
    1838             MainApplication.undoRedo.undo(commandCount);
     1837            UndoRedoHandler.getInstance().undo(commandCount);
    18391838        }
    18401839
  • applications/editors/josm/plugins/OSMRecPlugin/src/org/openstreetmap/josm/plugins/osmrec/OSMRecToggleDialog.java

    r33525 r34539  
    3131import javax.swing.table.TableModel;
    3232
    33 import org.openstreetmap.josm.Main;
    3433import org.openstreetmap.josm.actions.JosmAction;
    35 import org.openstreetmap.josm.data.SelectionChangedListener;
     34import org.openstreetmap.josm.data.osm.DataSelectionListener;
    3635import org.openstreetmap.josm.data.osm.DefaultNameFormatter;
    3736import org.openstreetmap.josm.data.osm.IRelation;
     37import org.openstreetmap.josm.data.osm.OsmDataManager;
    3838import org.openstreetmap.josm.data.osm.OsmPrimitive;
    3939import org.openstreetmap.josm.data.osm.Relation;
     
    7070 */
    7171public class OSMRecToggleDialog extends ToggleDialog
    72 implements SelectionChangedListener, DataSetListenerAdapter.Listener {
    73 
    74         /**
    75          * The tag data of selected objects.
    76          */
    77         private final DefaultTableModel tagData = new ReadOnlyTableModel();
    78 
    79         /**
    80          * The membership data of selected objects.
    81          */
    82         private final DefaultTableModel membershipData = new ReadOnlyTableModel();
    83 
    84         /**
    85          * The tags table.
    86          */
    87         private final JTable tagTable = new JTable(tagData);
    88 
    89         /**
    90          * The membership table.
    91          */
    92         private final JTable membershipTable = new JTable(membershipData);
    93 
    94         /** JPanel containing both previous tables */
    95         private final JPanel bothTables = new JPanel();
    96 
    97         private final transient Map<String, Map<String, Integer>> valueCount = new TreeMap<>();
    98         /**
    99          * This sub-object is responsible for all adding and editing of tags
    100          */
    101         private final transient OSMRecPluginHelper editHelper = new OSMRecPluginHelper(tagData, valueCount);
    102 
    103         private final AddAction addAction = new AddAction();
    104         private final EditActionTrain editAction = new EditActionTrain();
    105         //    private final DeleteAction deleteAction = new DeleteAction();
    106         //    private final JosmAction[] josmActions = new JosmAction[]{addAction, editAction, deleteAction};
    107 
    108         /**
    109          * The Add button (needed to be able to disable it)
    110          */
    111         private final SideButton btnAdd = new SideButton(addAction);
    112         /**
    113          * The Edit button (needed to be able to disable it)
    114          */
    115         private final SideButton btnEdit = new SideButton(editAction);
    116 
    117         /**
    118          * Text to display when nothing selected.
    119          */
    120         private final JLabel selectSth = new JLabel("<html><p>"
    121                         + tr("Select objects or create new objects and get recommendation.") + "</p></html>");
    122 
    123         // <editor-fold defaultstate="collapsed" desc="Dialog construction and helper methods">
    124 
    125         /**
    126          * Create a new OSMRecToggleDialog
    127          */
    128         public OSMRecToggleDialog() {
    129                 super(tr("Tags/Memberships"), "propertiesdialog", tr("Tags for selected objects."),
    130                                 Shortcut.registerShortcut("subwindow:properties", tr("Toggle: {0}", tr("Tags/Memberships")), KeyEvent.VK_P,
    131                                                 Shortcut.ALT_SHIFT), 150, true);
    132 
    133                 System.out.println("cleaning test..");
    134                 bothTables.setLayout(new GridBagLayout());
    135                 bothTables.setVisible(false); //my
    136                 // Let the actions know when selection in the tables change
    137                 tagTable.getSelectionModel().addListSelectionListener(editAction);
    138                 membershipTable.getSelectionModel().addListSelectionListener(editAction);
    139 
    140                 JScrollPane scrollPane = (JScrollPane) createLayout(bothTables, true,
    141                                 Arrays.asList(this.btnAdd, this.btnEdit));
    142 
    143                 MouseClickWatch mouseClickWatch = new MouseClickWatch();
    144                 tagTable.addMouseListener(mouseClickWatch);
    145                 membershipTable.addMouseListener(mouseClickWatch);
    146                 scrollPane.addMouseListener(mouseClickWatch);
    147                 editHelper.loadTagsIfNeeded();
    148 
    149         }
    150 
    151         /**
    152          * This simply fires up an {@link RelationEditor} for the relation shown; everything else
    153          * is the editor's business.
    154          *
    155          * @param row position
    156          */
    157         private void editMembership(int row) {
    158                 Relation relation = (Relation) membershipData.getValueAt(row, 0);
    159                 MainApplication.getMap().relationListDialog.selectRelation(relation);
    160         }
    161 
    162         private int findRow(TableModel model, Object value) {
    163                 for (int i = 0; i < model.getRowCount(); i++) {
    164                         if (model.getValueAt(i, 0).equals(value))
    165                                 return i;
    166                 }
    167                 return -1;
    168         }
    169 
    170         /**
    171          * Update selection status, call @{link #selectionChanged} function.
    172          */
    173         private void updateSelection() {
    174                 // Parameter is ignored in this class
    175                 selectionChanged(null);
    176         }
    177 
    178         // </editor-fold>
    179 
    180         // <editor-fold defaultstate="collapsed" desc="Event listeners methods">
    181 
    182         @Override
    183         public void selectionChanged(Collection<? extends OsmPrimitive> newSelection) {
    184                 if (tagTable == null)
    185                         return; // selection changed may be received in base class constructor before init
    186                 if (tagTable.getCellEditor() != null) {
    187                         tagTable.getCellEditor().cancelCellEditing();
    188                 }
    189 
    190                 // Ignore parameter as we do not want to operate always on real selection here, especially in draw mode
    191                 Collection<OsmPrimitive> newSel = Main.main.getInProgressSelection();
    192                 if (newSel == null) {
    193                         newSel = Collections.<OsmPrimitive>emptyList();
    194                 }
    195 
    196                 String selectedTag;
    197                 Relation selectedRelation = null;
    198                 selectedTag = editHelper.getChangedKey(); // select last added or last edited key by default
    199                 if (selectedTag == null && tagTable.getSelectedRowCount() == 1) {
    200                         selectedTag = (String) tagData.getValueAt(tagTable.getSelectedRow(), 0);
    201                 }
    202                 if (membershipTable.getSelectedRowCount() == 1) {
    203                         selectedRelation = (Relation) membershipData.getValueAt(membershipTable.getSelectedRow(), 0);
    204                 }
    205 
    206                 // re-load tag data
    207                 tagData.setRowCount(0);
    208 
    209                 final Map<String, String> tags = new HashMap<>();
    210                 valueCount.clear();
    211                 for (Entry<String, Map<String, Integer>> e : valueCount.entrySet()) {
    212                         int count = 0;
    213                         for (Entry<String, Integer> e1 : e.getValue().entrySet()) {
    214                                 count += e1.getValue();
    215                         }
    216                         if (count < newSel.size()) {
    217                                 e.getValue().put("", newSel.size() - count);
    218                         }
    219                         tagData.addRow(new Object[]{e.getKey(), e.getValue()});
    220                         tags.put(e.getKey(), e.getValue().size() == 1
    221                                         ? e.getValue().keySet().iterator().next() : tr("<different>"));
    222                 }
    223 
    224                 membershipData.setRowCount(0);
    225 
    226                 Map<Relation, MemberInfo> roles = new HashMap<>();
    227                 for (OsmPrimitive primitive: newSel) {
    228                         for (OsmPrimitive ref: primitive.getReferrers(true)) {
    229                                 if (ref instanceof Relation && !ref.isIncomplete() && !ref.isDeleted()) {
    230                                         Relation r = (Relation) ref;
    231                                         MemberInfo mi = roles.get(r);
    232                                         if (mi == null) {
    233                                                 mi = new MemberInfo(newSel);
    234                                         }
    235                                         roles.put(r, mi);
    236                                         int i = 1;
    237                                         for (RelationMember m : r.getMembers()) {
    238                                                 if (m.getMember() == primitive) {
    239                                                         mi.add(m, i);
    240                                                 }
    241                                                 ++i;
    242                                         }
    243                                 }
    244                         }
    245                 }
    246 
    247                 List<Relation> sortedRelations = new ArrayList<>(roles.keySet());
    248                 Collections.sort(sortedRelations, new Comparator<Relation>() {
    249                         @Override public int compare(Relation o1, Relation o2) {
    250                                 int comp = Boolean.valueOf(o1.isDisabledAndHidden()).compareTo(o2.isDisabledAndHidden());
    251                                 return comp != 0 ? comp : DefaultNameFormatter.getInstance().getRelationComparator().compare(o1, o2);
    252                         } });
    253 
    254                 for (Relation r: sortedRelations) {
    255                         membershipData.addRow(new Object[]{r, roles.get(r)});
    256                 }
    257 
    258                 membershipTable.getTableHeader().setVisible(membershipData.getRowCount() > 0);
    259                 membershipTable.setVisible(membershipData.getRowCount() > 0);
    260 
    261                 boolean hasSelection = !newSel.isEmpty();
    262                 boolean hasTags = hasSelection && tagData.getRowCount() > 0;
    263                 boolean hasMemberships = hasSelection && membershipData.getRowCount() > 0;
    264 
    265                 addAction.setEnabled(hasSelection);
    266                 //editAction.setEnabled(hasTags || hasMemberships);
    267                 editAction.setEnabled(true);
    268                 tagTable.setVisible(hasTags);
    269                 tagTable.getTableHeader().setVisible(hasTags);
    270                 selectSth.setVisible(!hasSelection);
    271 
    272                 int selectedIndex;
    273                 if (selectedTag != null && (selectedIndex = findRow(tagData, selectedTag)) != -1) {
    274                         tagTable.changeSelection(selectedIndex, 0, false, false);
    275                 } else if (selectedRelation != null && (selectedIndex = findRow(membershipData, selectedRelation)) != -1) {
    276                         membershipTable.changeSelection(selectedIndex, 0, false, false);
    277                 } else if (hasTags) {
    278                         tagTable.changeSelection(0, 0, false, false);
    279                 } else if (hasMemberships) {
    280                         membershipTable.changeSelection(0, 0, false, false);
    281                 }
    282         }
    283 
    284         @Override
    285         public void processDatasetEvent(AbstractDatasetChangedEvent event) {
    286                 updateSelection();
    287         }
    288 
    289         // </editor-fold>
    290 
    291         // <editor-fold defaultstate="collapsed" desc="Methods that are called by plugins to extend fuctionality ">
    292 
    293 
    294         /**
    295          * Returns the selected tag.
    296          * @return The current selected tag
    297          */
    298         @SuppressWarnings("unchecked")
    299         public Tag getSelectedProperty() {
    300                 int row = tagTable.getSelectedRow();
    301                 if (row == -1) return null;
    302                 Map<String, Integer> map = (TreeMap<String, Integer>) tagData.getValueAt(row, 1);
    303                 return new Tag(
    304                                 tagData.getValueAt(row, 0).toString(),
    305                                 map.size() > 1 ? "" : map.keySet().iterator().next());
    306         }
    307 
    308         /**
    309          * Returns the selected relation membership.
    310          * @return The current selected relation membership
    311          */
    312         public IRelation getSelectedMembershipRelation() {
    313                 int row = membershipTable.getSelectedRow();
    314                 return row > -1 ? (IRelation) membershipData.getValueAt(row, 0) : null;
    315         }
    316 
    317         // </editor-fold>
    318 
    319         /**
    320          * Class that watches for mouse clicks
    321          * @author imi
    322          */
    323         public class MouseClickWatch extends MouseAdapter {
    324                 @Override
    325                 public void mouseClicked(MouseEvent e) {
    326                         if (e.getClickCount() < 2) {
    327                                 // single click, clear selection in other table not clicked in
    328                                 if (e.getSource() == tagTable) {
    329                                         membershipTable.clearSelection();
    330                                 } else if (e.getSource() == membershipTable) {
    331                                         tagTable.clearSelection();
    332                                 }
    333                         } else if (e.getSource() == tagTable) {
    334                                 // double click, edit or add tag
    335                                 int row = tagTable.rowAtPoint(e.getPoint());
    336                                 if (row > -1) {
    337                                         boolean focusOnKey = tagTable.columnAtPoint(e.getPoint()) == 0;
    338                                         editHelper.editTag(row, focusOnKey);
    339                                 } else {
    340                                         editHelper.addTag();
    341                                 }
    342                         } else if (e.getSource() == membershipTable) {
    343                                 int row = membershipTable.rowAtPoint(e.getPoint());
    344                                 if (row > -1) {
    345                                         editMembership(row);
    346                                 }
    347                         } else {
    348                                 editHelper.addTag();
    349                         }
    350                 }
    351 
    352                 @Override
    353                 public void mousePressed(MouseEvent e) {
    354                         if (e.getSource() == tagTable) {
    355                                 membershipTable.clearSelection();
    356                         } else if (e.getSource() == membershipTable) {
    357                                 tagTable.clearSelection();
    358                         }
    359                 }
    360         }
    361 
    362         static class MemberInfo {
    363                 private List<RelationMember> role = new ArrayList<>();
    364                 private Set<OsmPrimitive> members = new HashSet<>();
    365                 private List<Integer> position = new ArrayList<>();
    366                 private Iterable<OsmPrimitive> selection;
    367                 private String positionString;
    368                 private String roleString;
    369 
    370                 MemberInfo(Iterable<OsmPrimitive> selection) {
    371                         this.selection = selection;
    372                 }
    373 
    374                 void add(RelationMember r, Integer p) {
    375                         role.add(r);
    376                         members.add(r.getMember());
    377                         position.add(p);
    378                 }
    379 
    380                 @Override
    381                 public String toString() {
    382                         return "MemberInfo{" +
    383                                         "roles='" + roleString + '\'' +
    384                                         ", positions='" + positionString + '\'' +
    385                                         '}';
    386                 }
    387         }
    388 
    389         /**
    390          * Class that allows fast creation of read-only table model with String columns
    391          */
    392         public static class ReadOnlyTableModel extends DefaultTableModel {
    393                 @Override
    394                 public boolean isCellEditable(int row, int column) {
    395                         return false;
    396                 }
    397 
    398                 @Override
    399                 public Class<?> getColumnClass(int columnIndex) {
    400                         return String.class;
    401                 }
    402         }
    403 
    404         /**
    405          * Action handling add button press in properties dialog.
    406          */
    407         class AddAction extends JosmAction {
    408                 AddAction() {
    409                         super(tr("Add Recommendation"), /* ICON() */ "dialogs/add", tr("Add a recommended key/value pair to your object"),
    410                                         Shortcut.registerShortcut("properties:add", tr("Add Tag"), KeyEvent.VK_A,
    411                                                         Shortcut.ALT), false);
    412                 }
    413 
    414                 @Override
    415                 public void actionPerformed(ActionEvent e) {
    416                         editHelper.addTag();
    417                         btnAdd.requestFocusInWindow();
    418                 }
    419         }
    420 
    421         /**
    422          * Action handling edit button press in properties dialog.
    423          * training process dialog/configuration
    424          */
    425         class EditActionTrain extends JosmAction implements ListSelectionListener {
    426                 EditActionTrain() {
    427                         super(tr("Train a Model"), /* ICON() */ "dialogs/fix", tr("Start the training engine!"),
    428                                         Shortcut.registerShortcut("properties:edit", tr("Edit Tags"), KeyEvent.VK_S,
    429                                                         Shortcut.ALT), false);
    430                         setEnabled(true);
    431                         updateEnabledState();
    432                 }
    433 
    434                 @Override
    435                 public void actionPerformed(ActionEvent e) {
    436                         if (!isEnabled())
    437                                 return;
    438                         if (tagTable.getSelectedRowCount() == 1) {
    439                                 int row = tagTable.getSelectedRow();
    440                                 editHelper.editTag(row, false);
    441                         } else if (membershipTable.getSelectedRowCount() == 1) {
    442                                 int row = membershipTable.getSelectedRow();
    443                                 editHelper.editTag(row, false);
    444                         } else {
    445                                 editHelper.editTag(1, false);
    446                         }
    447                 }
    448 
    449                 @Override
    450                 protected void updateEnabledState() {
    451                         setEnabled(true);
    452                 }
    453 
    454                 @Override
    455                 public void valueChanged(ListSelectionEvent e) {
    456                         updateEnabledState();
    457                 }
    458         }
     72implements DataSelectionListener, DataSetListenerAdapter.Listener {
     73
     74    /**
     75     * The tag data of selected objects.
     76     */
     77    private final DefaultTableModel tagData = new ReadOnlyTableModel();
     78
     79    /**
     80     * The membership data of selected objects.
     81     */
     82    private final DefaultTableModel membershipData = new ReadOnlyTableModel();
     83
     84    /**
     85     * The tags table.
     86     */
     87    private final JTable tagTable = new JTable(tagData);
     88
     89    /**
     90     * The membership table.
     91     */
     92    private final JTable membershipTable = new JTable(membershipData);
     93
     94    /** JPanel containing both previous tables */
     95    private final JPanel bothTables = new JPanel();
     96
     97    private final transient Map<String, Map<String, Integer>> valueCount = new TreeMap<>();
     98    /**
     99     * This sub-object is responsible for all adding and editing of tags
     100     */
     101    private final transient OSMRecPluginHelper editHelper = new OSMRecPluginHelper(tagData, valueCount);
     102
     103    private final AddAction addAction = new AddAction();
     104    private final EditActionTrain editAction = new EditActionTrain();
     105    //    private final DeleteAction deleteAction = new DeleteAction();
     106    //    private final JosmAction[] josmActions = new JosmAction[]{addAction, editAction, deleteAction};
     107
     108    /**
     109     * The Add button (needed to be able to disable it)
     110     */
     111    private final SideButton btnAdd = new SideButton(addAction);
     112    /**
     113     * The Edit button (needed to be able to disable it)
     114     */
     115    private final SideButton btnEdit = new SideButton(editAction);
     116
     117    /**
     118     * Text to display when nothing selected.
     119     */
     120    private final JLabel selectSth = new JLabel("<html><p>"
     121            + tr("Select objects or create new objects and get recommendation.") + "</p></html>");
     122
     123    // <editor-fold defaultstate="collapsed" desc="Dialog construction and helper methods">
     124
     125    /**
     126     * Create a new OSMRecToggleDialog
     127     */
     128    public OSMRecToggleDialog() {
     129        super(tr("Tags/Memberships"), "propertiesdialog", tr("Tags for selected objects."),
     130                Shortcut.registerShortcut("subwindow:properties", tr("Toggle: {0}", tr("Tags/Memberships")), KeyEvent.VK_P,
     131                        Shortcut.ALT_SHIFT), 150, true);
     132
     133        System.out.println("cleaning test..");
     134        bothTables.setLayout(new GridBagLayout());
     135        bothTables.setVisible(false); //my
     136        // Let the actions know when selection in the tables change
     137        tagTable.getSelectionModel().addListSelectionListener(editAction);
     138        membershipTable.getSelectionModel().addListSelectionListener(editAction);
     139
     140        JScrollPane scrollPane = (JScrollPane) createLayout(bothTables, true,
     141                Arrays.asList(this.btnAdd, this.btnEdit));
     142
     143        MouseClickWatch mouseClickWatch = new MouseClickWatch();
     144        tagTable.addMouseListener(mouseClickWatch);
     145        membershipTable.addMouseListener(mouseClickWatch);
     146        scrollPane.addMouseListener(mouseClickWatch);
     147        editHelper.loadTagsIfNeeded();
     148
     149    }
     150
     151    /**
     152     * This simply fires up an {@link RelationEditor} for the relation shown; everything else
     153     * is the editor's business.
     154     *
     155     * @param row position
     156     */
     157    private void editMembership(int row) {
     158        Relation relation = (Relation) membershipData.getValueAt(row, 0);
     159        MainApplication.getMap().relationListDialog.selectRelation(relation);
     160    }
     161
     162    private int findRow(TableModel model, Object value) {
     163        for (int i = 0; i < model.getRowCount(); i++) {
     164            if (model.getValueAt(i, 0).equals(value))
     165                return i;
     166        }
     167        return -1;
     168    }
     169
     170    /**
     171     * Update selection status, call @{link #selectionChanged} function.
     172     */
     173    private void updateSelection() {
     174        // Parameter is ignored in this class
     175        selectionChanged(null);
     176    }
     177
     178    // </editor-fold>
     179
     180    // <editor-fold defaultstate="collapsed" desc="Event listeners methods">
     181
     182    @Override
     183    public void selectionChanged(SelectionChangeEvent event) {
     184        if (tagTable == null)
     185            return; // selection changed may be received in base class constructor before init
     186        if (tagTable.getCellEditor() != null) {
     187            tagTable.getCellEditor().cancelCellEditing();
     188        }
     189
     190        // Ignore parameter as we do not want to operate always on real selection here, especially in draw mode
     191        Collection<OsmPrimitive> newSel = OsmDataManager.getInstance().getInProgressSelection();
     192        if (newSel == null) {
     193            newSel = Collections.<OsmPrimitive>emptyList();
     194        }
     195
     196        String selectedTag;
     197        Relation selectedRelation = null;
     198        selectedTag = editHelper.getChangedKey(); // select last added or last edited key by default
     199        if (selectedTag == null && tagTable.getSelectedRowCount() == 1) {
     200            selectedTag = (String) tagData.getValueAt(tagTable.getSelectedRow(), 0);
     201        }
     202        if (membershipTable.getSelectedRowCount() == 1) {
     203            selectedRelation = (Relation) membershipData.getValueAt(membershipTable.getSelectedRow(), 0);
     204        }
     205
     206        // re-load tag data
     207        tagData.setRowCount(0);
     208
     209        final Map<String, String> tags = new HashMap<>();
     210        valueCount.clear();
     211        for (Entry<String, Map<String, Integer>> e : valueCount.entrySet()) {
     212            int count = 0;
     213            for (Entry<String, Integer> e1 : e.getValue().entrySet()) {
     214                count += e1.getValue();
     215            }
     216            if (count < newSel.size()) {
     217                e.getValue().put("", newSel.size() - count);
     218            }
     219            tagData.addRow(new Object[]{e.getKey(), e.getValue()});
     220            tags.put(e.getKey(), e.getValue().size() == 1
     221                    ? e.getValue().keySet().iterator().next() : tr("<different>"));
     222        }
     223
     224        membershipData.setRowCount(0);
     225
     226        Map<Relation, MemberInfo> roles = new HashMap<>();
     227        for (OsmPrimitive primitive: newSel) {
     228            for (OsmPrimitive ref: primitive.getReferrers(true)) {
     229                if (ref instanceof Relation && !ref.isIncomplete() && !ref.isDeleted()) {
     230                    Relation r = (Relation) ref;
     231                    MemberInfo mi = roles.get(r);
     232                    if (mi == null) {
     233                        mi = new MemberInfo();
     234                    }
     235                    roles.put(r, mi);
     236                    int i = 1;
     237                    for (RelationMember m : r.getMembers()) {
     238                        if (m.getMember() == primitive) {
     239                            mi.add(m, i);
     240                        }
     241                        ++i;
     242                    }
     243                }
     244            }
     245        }
     246
     247        List<Relation> sortedRelations = new ArrayList<>(roles.keySet());
     248        Collections.sort(sortedRelations, new Comparator<Relation>() {
     249            @Override public int compare(Relation o1, Relation o2) {
     250                int comp = Boolean.valueOf(o1.isDisabledAndHidden()).compareTo(o2.isDisabledAndHidden());
     251                return comp != 0 ? comp : DefaultNameFormatter.getInstance().getRelationComparator().compare(o1, o2);
     252            } });
     253
     254        for (Relation r: sortedRelations) {
     255            membershipData.addRow(new Object[]{r, roles.get(r)});
     256        }
     257
     258        membershipTable.getTableHeader().setVisible(membershipData.getRowCount() > 0);
     259        membershipTable.setVisible(membershipData.getRowCount() > 0);
     260
     261        boolean hasSelection = !newSel.isEmpty();
     262        boolean hasTags = hasSelection && tagData.getRowCount() > 0;
     263        boolean hasMemberships = hasSelection && membershipData.getRowCount() > 0;
     264
     265        addAction.setEnabled(hasSelection);
     266        //editAction.setEnabled(hasTags || hasMemberships);
     267        editAction.setEnabled(true);
     268        tagTable.setVisible(hasTags);
     269        tagTable.getTableHeader().setVisible(hasTags);
     270        selectSth.setVisible(!hasSelection);
     271
     272        int selectedIndex;
     273        if (selectedTag != null && (selectedIndex = findRow(tagData, selectedTag)) != -1) {
     274            tagTable.changeSelection(selectedIndex, 0, false, false);
     275        } else if (selectedRelation != null && (selectedIndex = findRow(membershipData, selectedRelation)) != -1) {
     276            membershipTable.changeSelection(selectedIndex, 0, false, false);
     277        } else if (hasTags) {
     278            tagTable.changeSelection(0, 0, false, false);
     279        } else if (hasMemberships) {
     280            membershipTable.changeSelection(0, 0, false, false);
     281        }
     282    }
     283
     284    @Override
     285    public void processDatasetEvent(AbstractDatasetChangedEvent event) {
     286        updateSelection();
     287    }
     288
     289    // </editor-fold>
     290
     291    // <editor-fold defaultstate="collapsed" desc="Methods that are called by plugins to extend fuctionality ">
     292
     293
     294    /**
     295     * Returns the selected tag.
     296     * @return The current selected tag
     297     */
     298    @SuppressWarnings("unchecked")
     299    public Tag getSelectedProperty() {
     300        int row = tagTable.getSelectedRow();
     301        if (row == -1) return null;
     302        Map<String, Integer> map = (TreeMap<String, Integer>) tagData.getValueAt(row, 1);
     303        return new Tag(
     304                tagData.getValueAt(row, 0).toString(),
     305                map.size() > 1 ? "" : map.keySet().iterator().next());
     306    }
     307
     308    /**
     309     * Returns the selected relation membership.
     310     * @return The current selected relation membership
     311     */
     312    public IRelation<?> getSelectedMembershipRelation() {
     313        int row = membershipTable.getSelectedRow();
     314        return row > -1 ? (IRelation<?>) membershipData.getValueAt(row, 0) : null;
     315    }
     316
     317    // </editor-fold>
     318
     319    /**
     320     * Class that watches for mouse clicks
     321     * @author imi
     322     */
     323    public class MouseClickWatch extends MouseAdapter {
     324        @Override
     325        public void mouseClicked(MouseEvent e) {
     326            if (e.getClickCount() < 2) {
     327                // single click, clear selection in other table not clicked in
     328                if (e.getSource() == tagTable) {
     329                    membershipTable.clearSelection();
     330                } else if (e.getSource() == membershipTable) {
     331                    tagTable.clearSelection();
     332                }
     333            } else if (e.getSource() == tagTable) {
     334                // double click, edit or add tag
     335                int row = tagTable.rowAtPoint(e.getPoint());
     336                if (row > -1) {
     337                    boolean focusOnKey = tagTable.columnAtPoint(e.getPoint()) == 0;
     338                    editHelper.editTag(row, focusOnKey);
     339                } else {
     340                    editHelper.addTag();
     341                }
     342            } else if (e.getSource() == membershipTable) {
     343                int row = membershipTable.rowAtPoint(e.getPoint());
     344                if (row > -1) {
     345                    editMembership(row);
     346                }
     347            } else {
     348                editHelper.addTag();
     349            }
     350        }
     351
     352        @Override
     353        public void mousePressed(MouseEvent e) {
     354            if (e.getSource() == tagTable) {
     355                membershipTable.clearSelection();
     356            } else if (e.getSource() == membershipTable) {
     357                tagTable.clearSelection();
     358            }
     359        }
     360    }
     361
     362    static class MemberInfo {
     363        private List<RelationMember> role = new ArrayList<>();
     364        private Set<OsmPrimitive> members = new HashSet<>();
     365        private List<Integer> position = new ArrayList<>();
     366        private String positionString;
     367        private String roleString;
     368
     369        MemberInfo() {
     370        }
     371
     372        void add(RelationMember r, Integer p) {
     373            role.add(r);
     374            members.add(r.getMember());
     375            position.add(p);
     376        }
     377
     378        @Override
     379        public String toString() {
     380            return "MemberInfo{" +
     381                    "roles='" + roleString + '\'' +
     382                    ", positions='" + positionString + '\'' +
     383                    '}';
     384        }
     385    }
     386
     387    /**
     388     * Class that allows fast creation of read-only table model with String columns
     389     */
     390    public static class ReadOnlyTableModel extends DefaultTableModel {
     391        @Override
     392        public boolean isCellEditable(int row, int column) {
     393            return false;
     394        }
     395
     396        @Override
     397        public Class<?> getColumnClass(int columnIndex) {
     398            return String.class;
     399        }
     400    }
     401
     402    /**
     403     * Action handling add button press in properties dialog.
     404     */
     405    class AddAction extends JosmAction {
     406        AddAction() {
     407            super(tr("Add Recommendation"), /* ICON() */ "dialogs/add", tr("Add a recommended key/value pair to your object"),
     408                    Shortcut.registerShortcut("properties:add", tr("Add Tag"), KeyEvent.VK_A,
     409                            Shortcut.ALT), false);
     410        }
     411
     412        @Override
     413        public void actionPerformed(ActionEvent e) {
     414            editHelper.addTag();
     415            btnAdd.requestFocusInWindow();
     416        }
     417    }
     418
     419    /**
     420     * Action handling edit button press in properties dialog.
     421     * training process dialog/configuration
     422     */
     423    class EditActionTrain extends JosmAction implements ListSelectionListener {
     424        EditActionTrain() {
     425            super(tr("Train a Model"), /* ICON() */ "dialogs/fix", tr("Start the training engine!"),
     426                    Shortcut.registerShortcut("properties:edit", tr("Edit Tags"), KeyEvent.VK_S,
     427                            Shortcut.ALT), false);
     428            setEnabled(true);
     429            updateEnabledState();
     430        }
     431
     432        @Override
     433        public void actionPerformed(ActionEvent e) {
     434            if (!isEnabled())
     435                return;
     436            if (tagTable.getSelectedRowCount() == 1) {
     437                int row = tagTable.getSelectedRow();
     438                editHelper.editTag(row, false);
     439            } else if (membershipTable.getSelectedRowCount() == 1) {
     440                int row = membershipTable.getSelectedRow();
     441                editHelper.editTag(row, false);
     442            } else {
     443                editHelper.editTag(1, false);
     444            }
     445        }
     446
     447        @Override
     448        protected void updateEnabledState() {
     449            setEnabled(true);
     450        }
     451
     452        @Override
     453        public void valueChanged(ListSelectionEvent e) {
     454            updateEnabledState();
     455        }
     456    }
    459457}
  • applications/editors/josm/plugins/OSMRecPlugin/src/org/openstreetmap/josm/plugins/osmrec/core/TrainWorker.java

    r33013 r34539  
    697697    protected void done() {
    698698        try {
    699             System.out.println("Training process complete! - > " + get());
     699            get();
    700700            setProgress(100);
    701701        } catch (InterruptedException | ExecutionException ignore) {
  • applications/editors/josm/plugins/OSMRecPlugin/src/org/openstreetmap/josm/plugins/osmrec/extractor/Analyzer.java

    r32404 r34539  
    66import java.io.InputStream;
    77import java.io.InputStreamReader;
     8import java.nio.charset.StandardCharsets;
    89import java.util.AbstractMap;
    910import java.util.AbstractMap.SimpleEntry;
     
    383384        InputStream fstream = Analyzer.class.getResourceAsStream("/resources/files/stopWords.txt");
    384385
    385         try (BufferedReader br = new BufferedReader(new InputStreamReader(fstream))) {
     386        try (BufferedReader br = new BufferedReader(new InputStreamReader(fstream, StandardCharsets.UTF_8))) {
    386387            String strLine;
    387388
  • applications/editors/josm/plugins/OSMRecPlugin/src/org/openstreetmap/josm/plugins/osmrec/extractor/FrequenceExtractor.java

    r33525 r34539  
    1414import org.openstreetmap.josm.plugins.osmrec.container.OSMWay;
    1515import org.openstreetmap.josm.tools.Logging;
    16 import org.openstreetmap.josm.tools.Utils;
     16import org.openstreetmap.josm.tools.XmlUtils;
    1717import org.xml.sax.Attributes;
    1818import org.xml.sax.SAXException;
     
    2727public class FrequenceExtractor extends DefaultHandler {
    2828
    29         private final List<OSMNode> nodeList; //will be populated with nodes
    30         private final List<OSMRelation> relationList;
    31         private final Map<String, OSMNode> nodesWithIDs; //map containing IDs as Strings and the corresponding OSMNode objects
    32         private final List<OSMWay> wayList;  //populated with ways of the OSM file
    33         private final String osmXmlFileName;
    34         private OSMNode nodeTmp;
    35         private OSMWay wayTmp;
    36         private OSMRelation relationTmp;
    37         private boolean inWay = false; //when parser is in a way node becomes true in order to track the parser position
    38         private boolean inNode = false; //becomes true when the parser is in a simple node
    39         private boolean inRelation = false; //becomes true when the parser is in a relarion node
    40         private Map<String, Integer> frequency;
    41 
    42         public FrequenceExtractor(String osmXmlFileName) {
    43                 this.osmXmlFileName = osmXmlFileName;
    44                 nodeList = new ArrayList<>();
    45                 wayList = new ArrayList<>();
    46                 relationList = new ArrayList<>();
    47                 nodesWithIDs = new HashMap<>();
    48                 frequency = new HashMap<>();
    49                 for (int i = 0; i < 100; i++) {
    50                         frequency.put("", 0);
    51                 }
    52         }
    53 
    54         public void parseDocument() {
    55                 Logging.info("extracting frequencies...");
    56                 try {
    57                         Utils.newSafeSAXParser().parse(osmXmlFileName, this);
    58                 } catch (ParserConfigurationException | IOException | SAXException e) {
    59                         Logging.error(e);
    60                 }
    61         }
    62 
    63         @Override
    64         public void startElement(String s, String s1, String elementName, Attributes attributes) throws SAXException {
    65 
    66                 // if current element is an OSMNode , create new node and populate with the appropriate values
    67                 if (elementName.equalsIgnoreCase("node")) {
    68                         nodeTmp = new OSMNode();
    69                         inNode = true;
    70                         inWay = false;
    71                         inRelation = false;
    72 
    73                 } else if (elementName.equalsIgnoreCase("way")) {
    74                         wayTmp = new OSMWay();
    75                         //wayTmp.setID(attributes.getValue("id"));
    76                         inWay = true;
    77                         inNode = false;
    78                         inRelation = false;
    79                 } else if (elementName.equalsIgnoreCase("relation")) {
    80                         relationTmp = new OSMRelation();
    81                         //relationTmp.setID(attributes.getValue("id"));
    82                         inRelation = true;
    83                         inWay = false;
    84                         inNode = false;
    85                 } else if (elementName.equalsIgnoreCase("nd")) {
    86                         //wayTmp.addNodeReference(attributes.getValue("ref"));
    87 
    88                 } else if (elementName.equalsIgnoreCase("tag")) {
    89 
    90                         if (inNode) {
    91                                 //if the path is in an OSMNode set tagKey and value to the corresponding node
    92                                 nodeTmp.setTagKeyValue(attributes.getValue("k"), attributes.getValue("v"));
    93                         } else if (inWay) {
    94                                 //else if the path is in an OSM way set tagKey and value to the corresponding way
    95                                 wayTmp.setTagKeyValue(attributes.getValue("k"), attributes.getValue("v"));
    96                         } else if (inRelation) {
    97                                 //set the key-value pairs of relation tags
    98                                 relationTmp.setTagKeyValue(attributes.getValue("k"), attributes.getValue("v"));
    99                         }
    100 
    101                 } else if (elementName.equalsIgnoreCase("member")) {
    102                         //relationTmp.addMemberReference(attributes.getValue("ref"));
    103                 }
    104         }
    105 
    106         @Override
    107         public void endElement(String s, String s1, String element) throws SAXException {
    108                 // if end of node element, add to appropriate list
    109                 if (element.equalsIgnoreCase("node")) {
    110                         Map<String, String> tags = nodeTmp.getTagKeyValue();
    111                         if (tags.keySet().contains("name")) {
    112                                 for (Map.Entry<String, String> tag : tags.entrySet()) {
    113                                         if (tag.getKey().equals("name")) {
    114                                                 //split name value in each white space and store the values separetely. Count each occurance
    115                                                 String name = tag.getValue();
    116                                                 String[] SplitName = name.split("\\s+");
    117 
    118                                                 for (String split : SplitName) {
    119                                                         //put all splits with zero, at the constructor. put here the incremented values. for tomoro
    120                                                         if (frequency.get(split) != null) {
    121                                                                 int k = frequency.get(split) +1;
    122                                                                 frequency.put(split, k);
    123                                                         } else {
    124                                                                 frequency.put(split, 1);
    125                                                         }
    126                                                 }
    127                                         }
    128                                 }
    129                         }
    130                 }
    131 
    132                 if (element.equalsIgnoreCase("way")) {
    133                         //name frequency
    134                         Map<String, String> tags = wayTmp.getTagKeyValue();
    135 
    136                         if (tags.keySet().contains("name")) {
    137                                 for (Map.Entry<String, String> tag : tags.entrySet()) {
    138                                         if (tag.getKey().equals("name")) {
    139                                                 //split name value in each white space and store the values separetely. Count each occurance
    140                                                 String name = tag.getValue();
    141                                                 String[] SplitName = name.split("\\s+");
    142                                                 for (String split : SplitName) {
    143                                                         //put all splits with zero, at the constructor. put here the incremented values. for tomoro
    144                                                         if (frequency.get(split) != null) {
    145                                                                 int k = frequency.get(split) +1;
    146                                                                 frequency.put(split, k);
    147                                                         } else {
    148                                                                 frequency.put(split, 1);
    149                                                         }
    150                                                 }
    151                                         }
    152                                 }
    153                         }
    154                 }
    155 
    156                 if (element.equalsIgnoreCase("relation")) {
    157                         //name frequency
    158                         Map<String, String> tags = relationTmp.getTagKeyValue();
    159 
    160                         if (tags.keySet().contains("name")) {
    161                                 for (Map.Entry<String, String> tag : tags.entrySet()) {
    162                                         if (tag.getKey().equals("name")) {
    163                                                 //split name value in each white space and store the values separetely. Count each occurance
    164                                                 String name = tag.getValue();
    165                                                 String[] SplitName = name.split("\\s+");
    166 
    167                                                 for (String split : SplitName) {
    168                                                         //put all splits with zero, at the constructor. put here the incremented values. for tomoro
    169                                                         if (frequency.get(split) != null) {
    170                                                                 int k = frequency.get(split) +1;
    171                                                                 frequency.put(split, k);
    172                                                         } else {
    173                                                                 frequency.put(split, 1);
    174                                                         }
    175                                                 }
    176                                         }
    177                                 }
    178                         }
    179                 }
    180         }
    181 
    182         public List<OSMNode> getNodeList() {
    183                 return nodeList;
    184         }
    185 
    186         public List<OSMWay> getWayList() {
    187                 return wayList;
    188         }
    189 
    190         public List<OSMRelation> getRelationList() {
    191                 return relationList;
    192         }
    193 
    194         public Map<String, OSMNode> getNodesWithIDs() {
    195                 return nodesWithIDs;
    196         }
    197 
    198         //frequency temp
    199         public Map<String, Integer> getFrequency() {
    200                 return frequency;
    201         }
     29    private final List<OSMNode> nodeList; //will be populated with nodes
     30    private final List<OSMRelation> relationList;
     31    private final Map<String, OSMNode> nodesWithIDs; //map containing IDs as Strings and the corresponding OSMNode objects
     32    private final List<OSMWay> wayList;  //populated with ways of the OSM file
     33    private final String osmXmlFileName;
     34    private OSMNode nodeTmp;
     35    private OSMWay wayTmp;
     36    private OSMRelation relationTmp;
     37    private boolean inWay = false; //when parser is in a way node becomes true in order to track the parser position
     38    private boolean inNode = false; //becomes true when the parser is in a simple node
     39    private boolean inRelation = false; //becomes true when the parser is in a relarion node
     40    private Map<String, Integer> frequency;
     41
     42    public FrequenceExtractor(String osmXmlFileName) {
     43        this.osmXmlFileName = osmXmlFileName;
     44        nodeList = new ArrayList<>();
     45        wayList = new ArrayList<>();
     46        relationList = new ArrayList<>();
     47        nodesWithIDs = new HashMap<>();
     48        frequency = new HashMap<>();
     49        for (int i = 0; i < 100; i++) {
     50            frequency.put("", 0);
     51        }
     52    }
     53
     54    public void parseDocument() {
     55        Logging.info("extracting frequencies...");
     56        try {
     57            XmlUtils.newSafeSAXParser().parse(osmXmlFileName, this);
     58        } catch (ParserConfigurationException | IOException | SAXException e) {
     59            Logging.error(e);
     60        }
     61    }
     62
     63    @Override
     64    public void startElement(String s, String s1, String elementName, Attributes attributes) throws SAXException {
     65
     66        // if current element is an OSMNode , create new node and populate with the appropriate values
     67        if (elementName.equalsIgnoreCase("node")) {
     68            nodeTmp = new OSMNode();
     69            inNode = true;
     70            inWay = false;
     71            inRelation = false;
     72
     73        } else if (elementName.equalsIgnoreCase("way")) {
     74            wayTmp = new OSMWay();
     75            //wayTmp.setID(attributes.getValue("id"));
     76            inWay = true;
     77            inNode = false;
     78            inRelation = false;
     79        } else if (elementName.equalsIgnoreCase("relation")) {
     80            relationTmp = new OSMRelation();
     81            //relationTmp.setID(attributes.getValue("id"));
     82            inRelation = true;
     83            inWay = false;
     84            inNode = false;
     85        } else if (elementName.equalsIgnoreCase("nd")) {
     86            //wayTmp.addNodeReference(attributes.getValue("ref"));
     87
     88        } else if (elementName.equalsIgnoreCase("tag")) {
     89
     90            if (inNode) {
     91                //if the path is in an OSMNode set tagKey and value to the corresponding node
     92                nodeTmp.setTagKeyValue(attributes.getValue("k"), attributes.getValue("v"));
     93            } else if (inWay) {
     94                //else if the path is in an OSM way set tagKey and value to the corresponding way
     95                wayTmp.setTagKeyValue(attributes.getValue("k"), attributes.getValue("v"));
     96            } else if (inRelation) {
     97                //set the key-value pairs of relation tags
     98                relationTmp.setTagKeyValue(attributes.getValue("k"), attributes.getValue("v"));
     99            }
     100
     101        } else if (elementName.equalsIgnoreCase("member")) {
     102            //relationTmp.addMemberReference(attributes.getValue("ref"));
     103        }
     104    }
     105
     106    @Override
     107    public void endElement(String s, String s1, String element) throws SAXException {
     108        // if end of node element, add to appropriate list
     109        if (element.equalsIgnoreCase("node")) {
     110            Map<String, String> tags = nodeTmp.getTagKeyValue();
     111            if (tags.keySet().contains("name")) {
     112                for (Map.Entry<String, String> tag : tags.entrySet()) {
     113                    if (tag.getKey().equals("name")) {
     114                        //split name value in each white space and store the values separetely. Count each occurance
     115                        String name = tag.getValue();
     116                        String[] SplitName = name.split("\\s+");
     117
     118                        for (String split : SplitName) {
     119                            //put all splits with zero, at the constructor. put here the incremented values. for tomoro
     120                            if (frequency.get(split) != null) {
     121                                int k = frequency.get(split) +1;
     122                                frequency.put(split, k);
     123                            } else {
     124                                frequency.put(split, 1);
     125                            }
     126                        }
     127                    }
     128                }
     129            }
     130        }
     131
     132        if (element.equalsIgnoreCase("way")) {
     133            //name frequency
     134            Map<String, String> tags = wayTmp.getTagKeyValue();
     135
     136            if (tags.keySet().contains("name")) {
     137                for (Map.Entry<String, String> tag : tags.entrySet()) {
     138                    if (tag.getKey().equals("name")) {
     139                        //split name value in each white space and store the values separetely. Count each occurance
     140                        String name = tag.getValue();
     141                        String[] SplitName = name.split("\\s+");
     142                        for (String split : SplitName) {
     143                            //put all splits with zero, at the constructor. put here the incremented values. for tomoro
     144                            if (frequency.get(split) != null) {
     145                                int k = frequency.get(split) +1;
     146                                frequency.put(split, k);
     147                            } else {
     148                                frequency.put(split, 1);
     149                            }
     150                        }
     151                    }
     152                }
     153            }
     154        }
     155
     156        if (element.equalsIgnoreCase("relation")) {
     157            //name frequency
     158            Map<String, String> tags = relationTmp.getTagKeyValue();
     159
     160            if (tags.keySet().contains("name")) {
     161                for (Map.Entry<String, String> tag : tags.entrySet()) {
     162                    if (tag.getKey().equals("name")) {
     163                        //split name value in each white space and store the values separetely. Count each occurance
     164                        String name = tag.getValue();
     165                        String[] SplitName = name.split("\\s+");
     166
     167                        for (String split : SplitName) {
     168                            //put all splits with zero, at the constructor. put here the incremented values. for tomoro
     169                            if (frequency.get(split) != null) {
     170                                int k = frequency.get(split) +1;
     171                                frequency.put(split, k);
     172                            } else {
     173                                frequency.put(split, 1);
     174                            }
     175                        }
     176                    }
     177                }
     178            }
     179        }
     180    }
     181
     182    public List<OSMNode> getNodeList() {
     183        return nodeList;
     184    }
     185
     186    public List<OSMWay> getWayList() {
     187        return wayList;
     188    }
     189
     190    public List<OSMRelation> getRelationList() {
     191        return relationList;
     192    }
     193
     194    public Map<String, OSMNode> getNodesWithIDs() {
     195        return nodesWithIDs;
     196    }
     197
     198    //frequency temp
     199    public Map<String, Integer> getFrequency() {
     200        return frequency;
     201    }
    202202}
  • applications/editors/josm/plugins/OSMRecPlugin/src/org/openstreetmap/josm/plugins/osmrec/extractor/LanguageDetector.java

    r33525 r34539  
    2323public final class LanguageDetector {
    2424
    25         private static LanguageDetector languageDetector = null;
     25    private static LanguageDetector languageDetector = null;
    2626
    27         private LanguageDetector() {
    28                 //prevent instatiation
    29         }
     27    private LanguageDetector() {
     28        //prevent instatiation
     29    }
    3030
    31         public static LanguageDetector getInstance(String languageProfilesPath) {
    32                 if (languageDetector == null) {
    33                         languageDetector = new LanguageDetector();
    34                         loadProfilesFromStream(languageProfilesPath);
    35                         //profilesLoaded = true;
    36                 }
    37                 return languageDetector;
    38         }
     31    public static LanguageDetector getInstance(String languageProfilesPath) {
     32        if (languageDetector == null) {
     33            languageDetector = new LanguageDetector();
     34            loadProfilesFromStream(languageProfilesPath);
     35            //profilesLoaded = true;
     36        }
     37        return languageDetector;
     38    }
    3939
    40         public static void loadProfilesFromStream(String languageProfilesPath) { //create profiles directory in system from stream and load them
     40    public static void loadProfilesFromStream(String languageProfilesPath) { //create profiles directory in system from stream and load them
    4141
    42                 /*  supported languages
     42        /*  supported languages
    4343            el:greek, en:english, de:german, fr:french, es:spanish, ru:russian, tr:turkish, zh-cn:chinese, hi:hindi
    44                 */
    45                 InputStream languageProfilesInputStreamEl = LanguageDetector.class.getResourceAsStream("/profiles/el");
    46                 InputStream languageProfilesInputStreamEn = LanguageDetector.class.getResourceAsStream("/profiles/en");
    47                 InputStream languageProfilesInputStreamDe = LanguageDetector.class.getResourceAsStream("/profiles/de");
    48                 InputStream languageProfilesInputStreamFr = LanguageDetector.class.getResourceAsStream("/profiles/fr");
    49                 InputStream languageProfilesInputStreamEs = LanguageDetector.class.getResourceAsStream("/profiles/es");
    50                 InputStream languageProfilesInputStreamRu = LanguageDetector.class.getResourceAsStream("/profiles/ru");
    51                 InputStream languageProfilesInputStreamTr = LanguageDetector.class.getResourceAsStream("/profiles/tr");
    52                 InputStream languageProfilesInputStreamZh = LanguageDetector.class.getResourceAsStream("/profiles/zh-cn");
    53                 InputStream languageProfilesInputStreamHi = LanguageDetector.class.getResourceAsStream("/profiles/hi");
    54                 //InputStream languageProfilesInputStream2 = LanguageDetector.class.getResourceAsStream("/resources/profiles/en");
     44        */
     45        InputStream languageProfilesInputStreamEl = LanguageDetector.class.getResourceAsStream("/profiles/el");
     46        InputStream languageProfilesInputStreamEn = LanguageDetector.class.getResourceAsStream("/profiles/en");
     47        InputStream languageProfilesInputStreamDe = LanguageDetector.class.getResourceAsStream("/profiles/de");
     48        InputStream languageProfilesInputStreamFr = LanguageDetector.class.getResourceAsStream("/profiles/fr");
     49        InputStream languageProfilesInputStreamEs = LanguageDetector.class.getResourceAsStream("/profiles/es");
     50        InputStream languageProfilesInputStreamRu = LanguageDetector.class.getResourceAsStream("/profiles/ru");
     51        InputStream languageProfilesInputStreamTr = LanguageDetector.class.getResourceAsStream("/profiles/tr");
     52        InputStream languageProfilesInputStreamZh = LanguageDetector.class.getResourceAsStream("/profiles/zh-cn");
     53        InputStream languageProfilesInputStreamHi = LanguageDetector.class.getResourceAsStream("/profiles/hi");
     54        //InputStream languageProfilesInputStream2 = LanguageDetector.class.getResourceAsStream("/resources/profiles/en");
    5555
    56                 if (!new File(languageProfilesPath).exists()) {
    57                         Utils.mkDirs(new File(languageProfilesPath));
    58                 }
     56        if (!new File(languageProfilesPath).exists()) {
     57            Utils.mkDirs(new File(languageProfilesPath));
     58        }
    5959
    60                 File languageProfilesOutputFileEl = new File(languageProfilesPath + "/el");
    61                 File languageProfilesOutputFileEn = new File(languageProfilesPath + "/en");
    62                 File languageProfilesOutputFileDe = new File(languageProfilesPath + "/de");
    63                 File languageProfilesOutputFileFr = new File(languageProfilesPath + "/fr");
    64                 File languageProfilesOutputFileEs = new File(languageProfilesPath + "/es");
    65                 File languageProfilesOutputFileRu = new File(languageProfilesPath + "/ru");
    66                 File languageProfilesOutputFileTr = new File(languageProfilesPath + "/tr");
    67                 File languageProfilesOutputFileZh = new File(languageProfilesPath + "/zh-cn");
    68                 File languageProfilesOutputFileHi = new File(languageProfilesPath + "/hi");
     60        File languageProfilesOutputFileEl = new File(languageProfilesPath + "/el");
     61        File languageProfilesOutputFileEn = new File(languageProfilesPath + "/en");
     62        File languageProfilesOutputFileDe = new File(languageProfilesPath + "/de");
     63        File languageProfilesOutputFileFr = new File(languageProfilesPath + "/fr");
     64        File languageProfilesOutputFileEs = new File(languageProfilesPath + "/es");
     65        File languageProfilesOutputFileRu = new File(languageProfilesPath + "/ru");
     66        File languageProfilesOutputFileTr = new File(languageProfilesPath + "/tr");
     67        File languageProfilesOutputFileZh = new File(languageProfilesPath + "/zh-cn");
     68        File languageProfilesOutputFileHi = new File(languageProfilesPath + "/hi");
    6969
    70                 try {
    71                         languageProfilesOutputFileEl.createNewFile();
    72                         languageProfilesOutputFileEn.createNewFile();
    73                         languageProfilesOutputFileDe.createNewFile();
    74                         languageProfilesOutputFileFr.createNewFile();
    75                         languageProfilesOutputFileEs.createNewFile();
    76                         languageProfilesOutputFileRu.createNewFile();
    77                         languageProfilesOutputFileTr.createNewFile();
    78                         languageProfilesOutputFileZh.createNewFile();
    79                         languageProfilesOutputFileHi.createNewFile();
    80                 } catch (IOException ex) {
    81                         Logger.getLogger(LanguageDetector.class.getName()).log(Level.SEVERE, null, ex);
    82                         Logging.error(ex);
    83                 }
     70        try {
     71            languageProfilesOutputFileEl.createNewFile();
     72            languageProfilesOutputFileEn.createNewFile();
     73            languageProfilesOutputFileDe.createNewFile();
     74            languageProfilesOutputFileFr.createNewFile();
     75            languageProfilesOutputFileEs.createNewFile();
     76            languageProfilesOutputFileRu.createNewFile();
     77            languageProfilesOutputFileTr.createNewFile();
     78            languageProfilesOutputFileZh.createNewFile();
     79            languageProfilesOutputFileHi.createNewFile();
     80        } catch (IOException ex) {
     81            Logger.getLogger(LanguageDetector.class.getName()).log(Level.SEVERE, null, ex);
     82            Logging.error(ex);
     83        }
    8484
    85                 try {
    86                         Files.copy(languageProfilesInputStreamEl, languageProfilesOutputFileEl.toPath());
    87                         Files.copy(languageProfilesInputStreamEn, languageProfilesOutputFileEn.toPath());
    88                         Files.copy(languageProfilesInputStreamDe, languageProfilesOutputFileDe.toPath());
    89                         Files.copy(languageProfilesInputStreamFr, languageProfilesOutputFileFr.toPath());
    90                         Files.copy(languageProfilesInputStreamEs, languageProfilesOutputFileEs.toPath());
    91                         Files.copy(languageProfilesInputStreamRu, languageProfilesOutputFileRu.toPath());
    92                         Files.copy(languageProfilesInputStreamTr, languageProfilesOutputFileTr.toPath());
    93                         Files.copy(languageProfilesInputStreamZh, languageProfilesOutputFileZh.toPath());
    94                         Files.copy(languageProfilesInputStreamHi, languageProfilesOutputFileHi.toPath());
    95                 } catch (IOException ex) {
    96                         Logger.getLogger(LanguageDetector.class.getName()).log(Level.SEVERE, null, ex);
    97                         Logging.error(ex);
    98                 }
     85        try {
     86            Files.copy(languageProfilesInputStreamEl, languageProfilesOutputFileEl.toPath());
     87            Files.copy(languageProfilesInputStreamEn, languageProfilesOutputFileEn.toPath());
     88            Files.copy(languageProfilesInputStreamDe, languageProfilesOutputFileDe.toPath());
     89            Files.copy(languageProfilesInputStreamFr, languageProfilesOutputFileFr.toPath());
     90            Files.copy(languageProfilesInputStreamEs, languageProfilesOutputFileEs.toPath());
     91            Files.copy(languageProfilesInputStreamRu, languageProfilesOutputFileRu.toPath());
     92            Files.copy(languageProfilesInputStreamTr, languageProfilesOutputFileTr.toPath());
     93            Files.copy(languageProfilesInputStreamZh, languageProfilesOutputFileZh.toPath());
     94            Files.copy(languageProfilesInputStreamHi, languageProfilesOutputFileHi.toPath());
     95        } catch (IOException ex) {
     96            Logger.getLogger(LanguageDetector.class.getName()).log(Level.SEVERE, null, ex);
     97            Logging.error(ex);
     98        }
    9999
    100                 try {
    101                         DetectorFactory.loadProfile(languageProfilesPath);
    102                 } catch (LangDetectException ex) {
    103                         Logger.getLogger(LanguageDetector.class.getName()).log(Level.SEVERE, null, ex);
    104                         Logging.error(ex);
    105                 }
    106         }
     100        try {
     101            DetectorFactory.loadProfile(languageProfilesPath);
     102        } catch (LangDetectException ex) {
     103            Logger.getLogger(LanguageDetector.class.getName()).log(Level.SEVERE, null, ex);
     104            Logging.error(ex);
     105        }
     106    }
    107107
    108         public String detect(String text) {
    109                 try {
    110                         Detector detector = DetectorFactory.create();
    111                         detector.append(text);
    112                         return detector.detect();
    113                 } catch (LangDetectException ex) {
    114                         Logger.getLogger(LanguageDetector.class.getName()).log(Level.SEVERE, null, ex);
    115                         Logging.error(ex);
    116                         return "en"; //default lang to return if anything goes wrong at detection
    117                 }
    118         }
     108    public String detect(String text) {
     109        try {
     110            Detector detector = DetectorFactory.create();
     111            detector.append(text);
     112            return detector.detect();
     113        } catch (LangDetectException ex) {
     114            Logger.getLogger(LanguageDetector.class.getName()).log(Level.SEVERE, null, ex);
     115            Logging.error(ex);
     116            return "en"; //default lang to return if anything goes wrong at detection
     117        }
     118    }
    119119}
  • applications/editors/josm/plugins/OSMRecPlugin/src/org/openstreetmap/josm/plugins/osmrec/parsers/Mapper.java

    r33800 r34539  
    2929        mappingsWithIDs = new HashMap<>();
    3030        idsWithMappings = new HashMap<>();
    31 
    3231    }
    3332
    3433    public void parseFile(InputStream inps) throws FileNotFoundException {
    35 
    3634        Scanner input = new Scanner(inps, "UTF-8"); //the Map file contains lines of the mappings separated with the symbol "|"
    3735        //e.g. highway motorway | Motorway
     
    5048        constructMappingsWithIDs();
    5149        constructIDsWithMappings();
    52         System.out.println("Mappings file parsed successfully!");
    53         //LOG.info("Mappings file parsed successfully!");
    5450    }
    5551
  • applications/editors/josm/plugins/OSMRecPlugin/src/org/openstreetmap/josm/plugins/osmrec/parsers/OSMParser.java

    r33525 r34539  
    2525import org.openstreetmap.josm.plugins.osmrec.container.OSMWay;
    2626import org.openstreetmap.josm.tools.Logging;
    27 import org.openstreetmap.josm.tools.Utils;
     27import org.openstreetmap.josm.tools.XmlUtils;
    2828import org.xml.sax.Attributes;
    2929import org.xml.sax.SAXException;
     
    4545public class OSMParser extends DefaultHandler {
    4646
    47         //private static final org.apache.log4j.Logger LOG = org.apache.log4j.Logger.getLogger(OSMParser.class);
    48 
    49         //change from wgs84 to cartesian for later processing of the geometry
    50         private static final CoordinateReferenceSystem sourceCRS = DefaultGeographicCRS.WGS84;
    51         private static final CoordinateReferenceSystem targetCRS = DefaultGeocentricCRS.CARTESIAN;
    52         private final GeometryFactory geometryFactory = new GeometryFactory();
    53         private static MathTransform transform = null;
    54         private final List<OSMNode> nodeList; //will be populated with nodes
    55         private final List<OSMRelation> relationList;
    56         private final Map<String, OSMNode> nodesWithIDs; //map containing IDs as Strings and the corresponding OSMNode objects
    57         private final List<OSMWay> wayList;  //populated with ways of the OSM file
    58         private final String osmXmlFileName;
    59         private OSMNode nodeTmp; //variable to hold the node object
    60         private OSMWay wayTmp;   //variable to hold the way object
    61         private OSMRelation relationTmp;
    62         private boolean inWay = false; //when parser is in a way node becomes true in order to track the parser position
    63         private boolean inNode = false; //becomes true when the parser is in a simple node
    64         private boolean inRelation = false; //becomes true when the parser is in a relarion node
    65 
    66         public OSMParser(String osmXmlFileName) {
    67                 this.osmXmlFileName = osmXmlFileName;
    68                 nodeList = new ArrayList<>();
    69                 wayList = new ArrayList<>();
    70                 relationList = new ArrayList<>();
    71                 nodesWithIDs = new HashMap<>();
    72                 try {
    73                         transform = CRS.findMathTransform(sourceCRS, targetCRS, true);
    74                 } catch (FactoryException ex) {
    75                         Logger.getLogger(OSMParser.class.getName()).log(Level.SEVERE, null, ex);
    76                 }
    77         }
    78 
    79         public void parseDocument() {
    80                 try {
    81                         Utils.newSafeSAXParser().parse(osmXmlFileName, this);
    82                 } catch (ParserConfigurationException | SAXException | IOException e) {
    83                         Logging.error(e);
    84                 }
    85         }
    86 
    87         @Override
    88         public void startElement(String s, String s1, String elementName, Attributes attributes) throws SAXException {
    89 
    90                 // if current element is an OSMNode , create new node and populate with the appropriate values
    91                 if (elementName.equalsIgnoreCase("node")) {
    92                         nodeTmp = new OSMNode();
    93                         nodeTmp.setID(attributes.getValue("id"));
    94                         nodeTmp.setUser(attributes.getValue("user"));
    95                         //parse geometry
    96                         double longitude = Double.parseDouble(attributes.getValue("lon"));
    97                         double latitude = Double.parseDouble(attributes.getValue("lat"));
    98 
    99                         Coordinate targetGeometry = null;
    100                         Coordinate sourceCoordinate = new Coordinate(longitude, latitude);
    101                         try {
    102                                 targetGeometry = JTS.transform(sourceCoordinate, null, transform);
    103                         } catch (MismatchedDimensionException | TransformException ex) {
    104                                 Logger.getLogger(OSMParser.class.getName()).log(Level.SEVERE, null, ex);
    105                         }
    106 
    107                         //create geometry object
    108                         Geometry geom = geometryFactory.createPoint(new Coordinate(targetGeometry));
    109                         nodeTmp.setGeometry(geom);
    110                         inNode = true;
    111                         inWay = false;
    112                         inRelation = false;
    113 
    114                 } else if (elementName.equalsIgnoreCase("way")) {
    115                         wayTmp = new OSMWay();
    116                         wayTmp.setID(attributes.getValue("id"));
    117 
    118                         if (attributes.getValue("user") != null) {
    119                                 wayTmp.setUser(attributes.getValue("user"));
    120                         } else {
    121                                 wayTmp.setUser("undefined");
    122                         }
    123 
    124                         inWay = true;
    125                         inNode = false;
    126                         inRelation = false;
    127                 } else if (elementName.equalsIgnoreCase("relation")) {
    128                         relationTmp = new OSMRelation();
    129                         relationTmp.setID(attributes.getValue("id"));
    130                         inRelation = true;
    131                         inWay = false;
    132                         inNode = false;
    133                 } else if (elementName.equalsIgnoreCase("nd")) {
    134                         wayTmp.addNodeReference(attributes.getValue("ref"));
    135 
    136                 } else if (elementName.equalsIgnoreCase("tag")) {
    137 
    138                         if (inNode) {
    139                                 //if the path is in an OSMNode set tagKey and value to the corresponding node
    140                                 nodeTmp.setTagKeyValue(attributes.getValue("k"), attributes.getValue("v"));
    141                         } else if (inWay) {
    142                                 //else if the path is in an OSM way set tagKey and value to the corresponding way
    143                                 wayTmp.setTagKeyValue(attributes.getValue("k"), attributes.getValue("v"));
    144                         } else if (inRelation) {
    145                                 //set the key-value pairs of relation tags
    146                                 relationTmp.setTagKeyValue(attributes.getValue("k"), attributes.getValue("v"));
    147                         }
    148                 } else if (elementName.equalsIgnoreCase("member")) {
    149                         relationTmp.addMemberReference(attributes.getValue("ref"));
    150                 }
    151         }
    152 
    153         @Override
    154         public void endElement(String s, String s1, String element) throws SAXException {
    155                 // if end of node element, add to appropriate list
    156                 if (element.equalsIgnoreCase("node")) {
    157                         nodeList.add(nodeTmp);
    158                         nodesWithIDs.put(nodeTmp.getID(), nodeTmp);
    159                 }
    160 
    161                 if (element.equalsIgnoreCase("way")) {
    162 
    163                         //construct the Way geometry from each node of the node references
    164                         List<String> references = wayTmp.getNodeReferences();
    165 
    166                         for (String entry: references) {
    167                                 Geometry geometry = nodesWithIDs.get(entry).getGeometry(); //get the geometry of the node with ID=entry
    168                                 wayTmp.addNodeGeometry(geometry); //add the node geometry in this way
    169 
    170                         }
    171                         Geometry geom = geometryFactory.buildGeometry(wayTmp.getNodeGeometries());
    172 
    173                         if ((wayTmp.getNumberOfNodes() > 3) &&
    174                                         wayTmp.getNodeGeometries().get(0).equals(wayTmp.getNodeGeometries()
    175                                                         .get(wayTmp.getNodeGeometries().size()-1))) {
    176                                 //checks if the beginning and ending node are the same and the number of nodes are more than 3.
    177                                 //the nodes must be more than 3, because jts does not allow a construction of a linear ring with less points.
    178 
    179                                 if (!((wayTmp.getTagKeyValue().containsKey("barrier")) || wayTmp.getTagKeyValue().containsKey("highway"))) {
    180                                         //this is not a barrier nor a road, so construct a polygon geometry
    181 
    182                                         LinearRing linear = geometryFactory.createLinearRing(geom.getCoordinates());
    183                                         Polygon poly = new Polygon(linear, null, geometryFactory);
    184                                         wayTmp.setGeometry(poly);
    185                                 } else {
    186                                         //it is either a barrier or a road, so construct a linear ring geometry
    187                                         LinearRing linear = geometryFactory.createLinearRing(geom.getCoordinates());
    188                                         wayTmp.setGeometry(linear);
    189                                 }
    190                         } else if (wayTmp.getNumberOfNodes() > 1) {
    191                                 //it is an open geometry with more than one nodes, make it linestring
    192 
    193                                 LineString lineString = geometryFactory.createLineString(geom.getCoordinates());
    194                                 wayTmp.setGeometry(lineString);
    195                         } else { //we assume all the rest geometries are points
    196                                 //some ways happen to have only one point. Construct a  Point.
    197                                 Point point = geometryFactory.createPoint(geom.getCoordinate());
    198                                 wayTmp.setGeometry(point);
    199                         }
    200                         wayList.add(wayTmp);
    201                 }
    202 
    203                 if (element.equalsIgnoreCase("relation")) {
    204                         relationList.add(relationTmp);
    205                 }
    206         }
    207 
    208         public List<OSMNode> getNodeList() {
    209                 return nodeList;
    210         }
    211 
    212         public List<OSMWay> getWayList() {
    213                 return wayList;
    214         }
    215 
    216         public List<OSMRelation> getRelationList() {
    217                 return relationList;
    218         }
    219 
    220         public Map<String, OSMNode> getNodesWithIDs() {
    221                 return nodesWithIDs;
    222         }
     47    //private static final org.apache.log4j.Logger LOG = org.apache.log4j.Logger.getLogger(OSMParser.class);
     48
     49    //change from wgs84 to cartesian for later processing of the geometry
     50    private static final CoordinateReferenceSystem sourceCRS = DefaultGeographicCRS.WGS84;
     51    private static final CoordinateReferenceSystem targetCRS = DefaultGeocentricCRS.CARTESIAN;
     52    private final GeometryFactory geometryFactory = new GeometryFactory();
     53    private static MathTransform transform = null;
     54    private final List<OSMNode> nodeList; //will be populated with nodes
     55    private final List<OSMRelation> relationList;
     56    private final Map<String, OSMNode> nodesWithIDs; //map containing IDs as Strings and the corresponding OSMNode objects
     57    private final List<OSMWay> wayList;  //populated with ways of the OSM file
     58    private final String osmXmlFileName;
     59    private OSMNode nodeTmp; //variable to hold the node object
     60    private OSMWay wayTmp;   //variable to hold the way object
     61    private OSMRelation relationTmp;
     62    private boolean inWay = false; //when parser is in a way node becomes true in order to track the parser position
     63    private boolean inNode = false; //becomes true when the parser is in a simple node
     64    private boolean inRelation = false; //becomes true when the parser is in a relarion node
     65
     66    public OSMParser(String osmXmlFileName) {
     67        this.osmXmlFileName = osmXmlFileName;
     68        nodeList = new ArrayList<>();
     69        wayList = new ArrayList<>();
     70        relationList = new ArrayList<>();
     71        nodesWithIDs = new HashMap<>();
     72        try {
     73            transform = CRS.findMathTransform(sourceCRS, targetCRS, true);
     74        } catch (FactoryException ex) {
     75            Logger.getLogger(OSMParser.class.getName()).log(Level.SEVERE, null, ex);
     76        }
     77    }
     78
     79    public void parseDocument() {
     80        try {
     81            XmlUtils.newSafeSAXParser().parse(osmXmlFileName, this);
     82        } catch (ParserConfigurationException | SAXException | IOException e) {
     83            Logging.error(e);
     84        }
     85    }
     86
     87    @Override
     88    public void startElement(String s, String s1, String elementName, Attributes attributes) throws SAXException {
     89
     90        // if current element is an OSMNode , create new node and populate with the appropriate values
     91        if (elementName.equalsIgnoreCase("node")) {
     92            nodeTmp = new OSMNode();
     93            nodeTmp.setID(attributes.getValue("id"));
     94            nodeTmp.setUser(attributes.getValue("user"));
     95            //parse geometry
     96            double longitude = Double.parseDouble(attributes.getValue("lon"));
     97            double latitude = Double.parseDouble(attributes.getValue("lat"));
     98
     99            Coordinate targetGeometry = null;
     100            Coordinate sourceCoordinate = new Coordinate(longitude, latitude);
     101            try {
     102                targetGeometry = JTS.transform(sourceCoordinate, null, transform);
     103            } catch (MismatchedDimensionException | TransformException ex) {
     104                Logger.getLogger(OSMParser.class.getName()).log(Level.SEVERE, null, ex);
     105            }
     106
     107            //create geometry object
     108            Geometry geom = geometryFactory.createPoint(new Coordinate(targetGeometry));
     109            nodeTmp.setGeometry(geom);
     110            inNode = true;
     111            inWay = false;
     112            inRelation = false;
     113
     114        } else if (elementName.equalsIgnoreCase("way")) {
     115            wayTmp = new OSMWay();
     116            wayTmp.setID(attributes.getValue("id"));
     117
     118            if (attributes.getValue("user") != null) {
     119                wayTmp.setUser(attributes.getValue("user"));
     120            } else {
     121                wayTmp.setUser("undefined");
     122            }
     123
     124            inWay = true;
     125            inNode = false;
     126            inRelation = false;
     127        } else if (elementName.equalsIgnoreCase("relation")) {
     128            relationTmp = new OSMRelation();
     129            relationTmp.setID(attributes.getValue("id"));
     130            inRelation = true;
     131            inWay = false;
     132            inNode = false;
     133        } else if (elementName.equalsIgnoreCase("nd")) {
     134            wayTmp.addNodeReference(attributes.getValue("ref"));
     135
     136        } else if (elementName.equalsIgnoreCase("tag")) {
     137
     138            if (inNode) {
     139                //if the path is in an OSMNode set tagKey and value to the corresponding node
     140                nodeTmp.setTagKeyValue(attributes.getValue("k"), attributes.getValue("v"));
     141            } else if (inWay) {
     142                //else if the path is in an OSM way set tagKey and value to the corresponding way
     143                wayTmp.setTagKeyValue(attributes.getValue("k"), attributes.getValue("v"));
     144            } else if (inRelation) {
     145                //set the key-value pairs of relation tags
     146                relationTmp.setTagKeyValue(attributes.getValue("k"), attributes.getValue("v"));
     147            }
     148        } else if (elementName.equalsIgnoreCase("member")) {
     149            relationTmp.addMemberReference(attributes.getValue("ref"));
     150        }
     151    }
     152
     153    @Override
     154    public void endElement(String s, String s1, String element) throws SAXException {
     155        // if end of node element, add to appropriate list
     156        if (element.equalsIgnoreCase("node")) {
     157            nodeList.add(nodeTmp);
     158            nodesWithIDs.put(nodeTmp.getID(), nodeTmp);
     159        }
     160
     161        if (element.equalsIgnoreCase("way")) {
     162
     163            //construct the Way geometry from each node of the node references
     164            List<String> references = wayTmp.getNodeReferences();
     165
     166            for (String entry: references) {
     167                Geometry geometry = nodesWithIDs.get(entry).getGeometry(); //get the geometry of the node with ID=entry
     168                wayTmp.addNodeGeometry(geometry); //add the node geometry in this way
     169
     170            }
     171            Geometry geom = geometryFactory.buildGeometry(wayTmp.getNodeGeometries());
     172
     173            if ((wayTmp.getNumberOfNodes() > 3) &&
     174                    wayTmp.getNodeGeometries().get(0).equals(wayTmp.getNodeGeometries()
     175                            .get(wayTmp.getNodeGeometries().size()-1))) {
     176                //checks if the beginning and ending node are the same and the number of nodes are more than 3.
     177                //the nodes must be more than 3, because jts does not allow a construction of a linear ring with less points.
     178
     179                if (!((wayTmp.getTagKeyValue().containsKey("barrier")) || wayTmp.getTagKeyValue().containsKey("highway"))) {
     180                    //this is not a barrier nor a road, so construct a polygon geometry
     181
     182                    LinearRing linear = geometryFactory.createLinearRing(geom.getCoordinates());
     183                    Polygon poly = new Polygon(linear, null, geometryFactory);
     184                    wayTmp.setGeometry(poly);
     185                } else {
     186                    //it is either a barrier or a road, so construct a linear ring geometry
     187                    LinearRing linear = geometryFactory.createLinearRing(geom.getCoordinates());
     188                    wayTmp.setGeometry(linear);
     189                }
     190            } else if (wayTmp.getNumberOfNodes() > 1) {
     191                //it is an open geometry with more than one nodes, make it linestring
     192
     193                LineString lineString = geometryFactory.createLineString(geom.getCoordinates());
     194                wayTmp.setGeometry(lineString);
     195            } else { //we assume all the rest geometries are points
     196                //some ways happen to have only one point. Construct a  Point.
     197                Point point = geometryFactory.createPoint(geom.getCoordinate());
     198                wayTmp.setGeometry(point);
     199            }
     200            wayList.add(wayTmp);
     201        }
     202
     203        if (element.equalsIgnoreCase("relation")) {
     204            relationList.add(relationTmp);
     205        }
     206    }
     207
     208    public List<OSMNode> getNodeList() {
     209        return nodeList;
     210    }
     211
     212    public List<OSMWay> getWayList() {
     213        return wayList;
     214    }
     215
     216    public List<OSMRelation> getRelationList() {
     217        return relationList;
     218    }
     219
     220    public Map<String, OSMNode> getNodesWithIDs() {
     221        return nodesWithIDs;
     222    }
    223223}
  • applications/editors/josm/plugins/OSMRecPlugin/src/org/openstreetmap/josm/plugins/osmrec/parsers/TextualStatistics.java

    r33800 r34539  
    1414 * @author imis-nkarag
    1515 */
    16 
    1716public class TextualStatistics {
    1817
    19     //private static final org.apache.log4j.Logger LOG = org.apache.log4j.Logger.getLogger(TextualStatistics.class);
    2018    private List<String> textualList;
    2119
     
    2826            textualList.add(nextLine);
    2927        }
    30         //LOG.info("Name occurences parsed successfully!");
    3128    }
    3229
  • applications/editors/josm/plugins/OSMRecPlugin/src/org/openstreetmap/josm/plugins/osmrec/personalization/HistoryParser.java

    r33525 r34539  
    2929import org.openstreetmap.josm.tools.HttpClient;
    3030import org.openstreetmap.josm.tools.Logging;
    31 import org.openstreetmap.josm.tools.Utils;
     31import org.openstreetmap.josm.tools.XmlUtils;
    3232import org.w3c.dom.Node;
    3333import org.w3c.dom.NodeList;
     
    4848 */
    4949public class HistoryParser {
    50         private static final String OSM_API = OsmApi.getOsmApi().getBaseUrl();
    51         private static final CoordinateReferenceSystem sourceCRS = DefaultGeographicCRS.WGS84;
    52         private static final CoordinateReferenceSystem targetCRS = DefaultGeocentricCRS.CARTESIAN;
    53         private static final GeometryFactory geometryFactory = new GeometryFactory();
    54         private MathTransform transform;
    55         private OSMNode nodeTmp;
    56 
    57         private final List<OSMNode> nodeList;
    58         private final Map<String, OSMNode> nodesWithIDs;
    59         private final List<OSMWay> wayList;
    60         private OSMWay wayTmp;
    61         private final String username;
    62 
    63         /**
    64         * Constructs a new {@code HistoryParser}.
    65         * @param username user name
    66         */
    67         public HistoryParser(String username) {
    68                 this.username = username;
    69                 transform = null;
    70                 try {
    71                         transform = CRS.findMathTransform(sourceCRS, targetCRS, true);
    72                 } catch (FactoryException ex) {
    73                         Logger.getLogger(HistoryParser.class.getName()).log(Level.SEVERE, null, ex);
    74                 }
    75                 nodeList = new ArrayList<>();
    76                 nodesWithIDs = new HashMap<>();
    77                 wayList = new ArrayList<>();
    78         }
    79 
    80         public void historyParse(String timeInterval) {
    81 
    82                 HashSet<String> changesetIDsList = new HashSet<>();
    83 
    84                 try {
    85                         String osmUrl = OSM_API + "changesets?display_name=" + username + "&time=" + timeInterval;
    86                         InputStream xml = HttpClient.create(new URL(osmUrl)).connect().getContent();
    87                         NodeList nodes = Utils.parseSafeDOM(xml).getElementsByTagName("changeset");
    88 
    89                         Logging.debug("changeset size "+ nodes.getLength());
    90                         for (int i = 0; i < nodes.getLength(); i++) {
    91                                 Logging.debug("attributes of " + i + "th changeset");
    92                                 String id = nodes.item(i).getAttributes().item(3).toString();
    93                                 Logging.debug("id:" + nodes.item(i).getAttributes().item(3));
    94                                 id = stripQuotes(id);
    95                                 changesetIDsList.add(id);
    96                         }
    97 
    98                         for (String id : changesetIDsList) {
    99                                 getChangesetByID(id);
    100                         }
    101                 } catch (IOException | ParserConfigurationException | SAXException ex) {
    102                         Logger.getLogger(HistoryParser.class.getName()).log(Level.SEVERE, null, ex);
    103                 }
    104         }
    105 
    106         private void getChangesetByID(String id) {
    107                 try {
    108                         String changesetByIDURL = OSM_API+ "changeset/" + id + "/download";
    109                         InputStream xml = HttpClient.create(new URL(changesetByIDURL)).connect().getContent();
    110                         Node osmChange = Utils.parseSafeDOM(xml).getFirstChild();
    111 
    112                         //get all nodes first, in order to be able to call all nodes references and create the geometries
    113                         for (int i = 0; i < osmChange.getChildNodes().getLength(); i++) {
    114                                 String changeType = osmChange.getChildNodes().item(i).getNodeName();
    115                                 if (!(changeType.equals("#text") || changeType.equals("delete"))) {
    116 
    117                                         NodeList changeChilds = osmChange.getChildNodes().item(i).getChildNodes();
    118 
    119                                         Node osmObject = changeChilds.item(1);
    120 
    121                                         if (osmObject.getNodeName().equals("node")) {
    122                                                 //node data
    123                                                 nodeTmp = new OSMNode();
    124                                                 nodeTmp.setID(osmObject.getAttributes().getNamedItem("id").getNodeValue());
    125 
    126                                                 //parse geometry
    127                                                 double longitude = Double.parseDouble(osmObject.getAttributes().getNamedItem("lon").getNodeValue());
    128                                                 double latitude = Double.parseDouble(osmObject.getAttributes().getNamedItem("lat").getNodeValue());
    129                                                 Coordinate targetGeometry = null;
    130                                                 Coordinate sourceCoordinate = new Coordinate(longitude, latitude);
    131                                                 try {
    132                                                         targetGeometry = JTS.transform(sourceCoordinate, null, transform);
    133                                                 } catch (MismatchedDimensionException | TransformException ex) {
    134                                                         Logger.getLogger(HistoryParser.class.getName()).log(Level.SEVERE, null, ex);
    135                                                 }
    136 
    137                                                 //create geometry object
    138                                                 Geometry geom = geometryFactory.createPoint(new Coordinate(targetGeometry));
    139                                                 nodeTmp.setGeometry(geom);
    140 
    141                                                 nodeList.add(nodeTmp);
    142                                                 nodesWithIDs.put(nodeTmp.getID(), nodeTmp);
    143                                         }
    144                                 }
    145                         }
    146 
    147                         for (int i = 0; i < osmChange.getChildNodes().getLength(); i++) {
    148                                 String changeType = osmChange.getChildNodes().item(i).getNodeName();
    149                                 if (!(changeType.equals("#text") || changeType.equals("delete"))) {
    150                                         NodeList changeChilds = osmChange.getChildNodes().item(i).getChildNodes();
    151 
    152                                         Node osmObject = changeChilds.item(1);
    153                                         if (osmObject.getNodeName().equals("way")) {
    154 
    155                                                 //get way data
    156                                                 wayTmp = new OSMWay();
    157                                                 wayTmp.setID(osmObject.getAttributes().getNamedItem("id").getNodeValue());
    158                                                 // extract tags, then set tags to osm object
    159                                                 Logging.debug("\n\nWAY: " + wayTmp.getID());
    160                                                 for (int l = 0; l < osmObject.getChildNodes().getLength(); l++) {
    161                                                         String wayChild = osmObject.getChildNodes().item(l).getNodeName();
    162 
    163                                                         if (wayChild.equals("tag")) {
    164                                                                 String key = osmObject.getChildNodes().item(l).getAttributes().getNamedItem("k").getNodeValue();
    165                                                                 String value = osmObject.getChildNodes().item(l).getAttributes().getNamedItem("v").getNodeValue();
    166                                                                 System.out.println("key: " + key + " value: " + value);
    167                                                                 wayTmp.setTagKeyValue(key, value);
    168                                                         } else if (wayChild.equals("nd")) {
    169                                                                 wayTmp.addNodeReference(osmObject.getChildNodes().item(l).getAttributes().getNamedItem("ref").getNodeValue());
    170                                                         }
    171                                                 }
    172 
    173                                                 //construct the Way geometry from each node of the node references
    174                                                 List<String> references = wayTmp.getNodeReferences();
    175 
    176                                                 for (String entry: references) {
    177                                                         if (nodesWithIDs.containsKey(entry)) {
    178                                                                 Geometry geometry = nodesWithIDs.get(entry).getGeometry(); //get the geometry of the node with ID=entry
    179                                                                 wayTmp.addNodeGeometry(geometry); //add the node geometry in this way
    180                                                         } else {
    181                                                                 Logging.debug("nodes with ids, no entry " + entry);
    182                                                                 getNodeFromAPI(entry);
    183                                                         }
    184                                                 }
    185 
    186                                                 Geometry geom = geometryFactory.buildGeometry(wayTmp.getNodeGeometries());
    187                                                 if ((wayTmp.getNodeGeometries().size() > 3) &&
    188                                                                 wayTmp.getNodeGeometries().get(0).equals(wayTmp.getNodeGeometries()
    189                                                                                 .get(wayTmp.getNodeGeometries().size()-1))) {
    190                                                         //checks if the beginning and ending node are the same and the number of nodes are more than 3.
    191                                                         //the nodes must be more than 3, because jts does not allow a construction of a linear ring with less points.
    192 
    193                                                         if (!((wayTmp.getTagKeyValue().containsKey("barrier")) || wayTmp.getTagKeyValue().containsKey("highway"))) {
    194                                                                 //this is not a barrier nor a road, so construct a polygon geometry
    195 
    196                                                                 LinearRing linear = geometryFactory.createLinearRing(geom.getCoordinates());
    197                                                                 Polygon poly = new Polygon(linear, null, geometryFactory);
    198                                                                 wayTmp.setGeometry(poly);
    199                                                         } else {
    200                                                                 //it is either a barrier or a road, so construct a linear ring geometry
    201                                                                 LinearRing linear = geometryFactory.createLinearRing(geom.getCoordinates());
    202                                                                 wayTmp.setGeometry(linear);
    203                                                         }
    204                                                 } else if (wayTmp.getNodeGeometries().size() > 1) {
    205                                                         //it is an open geometry with more than one nodes, make it linestring
    206 
    207                                                         LineString lineString = geometryFactory.createLineString(geom.getCoordinates());
    208                                                         wayTmp.setGeometry(lineString);
    209                                                 } else { //we assume all the rest geometries are points
    210                                                         //some ways happen to have only one point. Construct a  Point.
    211                                                         Point point = geometryFactory.createPoint(geom.getCoordinate());
    212                                                         wayTmp.setGeometry(point);
    213                                                 }
    214                                                 wayList.add(wayTmp);
    215                                         }
    216                                 }
    217                         }
    218                 } catch (IOException | ParserConfigurationException | SAXException ex) {
    219                         Logger.getLogger(HistoryParser.class.getName()).log(Level.SEVERE, null, ex);
    220                 }
    221         }
    222 
    223         private String stripQuotes(String id) {
    224                 return id.substring(4, id.length()-1);
    225         }
    226 
    227         private void getNodeFromAPI(String nodeID) {
    228                 try {
    229                         String osmUrl = OSM_API + "node/" + nodeID;
    230                         InputStream xml = HttpClient.create(new URL(osmUrl)).connect().getContent();
    231                         NodeList nodes = Utils.parseSafeDOM(xml).getElementsByTagName("node");
    232                         String lat = nodes.item(0).getAttributes().getNamedItem("lat").getNodeValue();
    233                         String lon = nodes.item(0).getAttributes().getNamedItem("lon").getNodeValue();
    234 
    235                         nodeTmp = new OSMNode();
    236                         nodeTmp.setID(nodeID);
    237 
    238                         //parse geometry
    239                         double longitude = Double.parseDouble(lon);
    240                         double latitude = Double.parseDouble(lat);
    241                         Coordinate targetGeometry = null;
    242                         Coordinate sourceCoordinate = new Coordinate(longitude, latitude);
    243                         try {
    244                                 targetGeometry = JTS.transform(sourceCoordinate, null, transform);
    245                         } catch (MismatchedDimensionException | TransformException ex) {
    246                                 Logger.getLogger(HistoryParser.class.getName()).log(Level.SEVERE, null, ex);
    247                         }
    248 
    249                         //create geometry object
    250                         Geometry geom = geometryFactory.createPoint(new Coordinate(targetGeometry));
    251                         nodeTmp.setGeometry(geom);
    252 
    253                         nodeList.add(nodeTmp);
    254                         nodesWithIDs.put(nodeTmp.getID(), nodeTmp);
    255 
    256                 } catch (IOException | ParserConfigurationException | SAXException ex) {
    257                         Logger.getLogger(HistoryParser.class.getName()).log(Level.SEVERE, null, ex);
    258                 }
    259         }
    260 
    261         public List<OSMWay> getWayList() {
    262                 return wayList;
    263         }
     50    private static final String OSM_API = OsmApi.getOsmApi().getBaseUrl();
     51    private static final CoordinateReferenceSystem sourceCRS = DefaultGeographicCRS.WGS84;
     52    private static final CoordinateReferenceSystem targetCRS = DefaultGeocentricCRS.CARTESIAN;
     53    private static final GeometryFactory geometryFactory = new GeometryFactory();
     54    private MathTransform transform;
     55    private OSMNode nodeTmp;
     56
     57    private final List<OSMNode> nodeList;
     58    private final Map<String, OSMNode> nodesWithIDs;
     59    private final List<OSMWay> wayList;
     60    private OSMWay wayTmp;
     61    private final String username;
     62
     63    /**
     64    * Constructs a new {@code HistoryParser}.
     65    * @param username user name
     66    */
     67    public HistoryParser(String username) {
     68        this.username = username;
     69        transform = null;
     70        try {
     71            transform = CRS.findMathTransform(sourceCRS, targetCRS, true);
     72        } catch (FactoryException ex) {
     73            Logger.getLogger(HistoryParser.class.getName()).log(Level.SEVERE, null, ex);
     74        }
     75        nodeList = new ArrayList<>();
     76        nodesWithIDs = new HashMap<>();
     77        wayList = new ArrayList<>();
     78    }
     79
     80    public void historyParse(String timeInterval) {
     81
     82        HashSet<String> changesetIDsList = new HashSet<>();
     83
     84        try {
     85            String osmUrl = OSM_API + "changesets?display_name=" + username + "&time=" + timeInterval;
     86            InputStream xml = HttpClient.create(new URL(osmUrl)).connect().getContent();
     87            NodeList nodes = XmlUtils.parseSafeDOM(xml).getElementsByTagName("changeset");
     88
     89            Logging.debug("changeset size "+ nodes.getLength());
     90            for (int i = 0; i < nodes.getLength(); i++) {
     91                Logging.debug("attributes of " + i + "th changeset");
     92                String id = nodes.item(i).getAttributes().item(3).toString();
     93                Logging.debug("id:" + nodes.item(i).getAttributes().item(3));
     94                id = stripQuotes(id);
     95                changesetIDsList.add(id);
     96            }
     97
     98            for (String id : changesetIDsList) {
     99                getChangesetByID(id);
     100            }
     101        } catch (IOException | ParserConfigurationException | SAXException ex) {
     102            Logger.getLogger(HistoryParser.class.getName()).log(Level.SEVERE, null, ex);
     103        }
     104    }
     105
     106    private void getChangesetByID(String id) {
     107        try {
     108            String changesetByIDURL = OSM_API+ "changeset/" + id + "/download";
     109            InputStream xml = HttpClient.create(new URL(changesetByIDURL)).connect().getContent();
     110            Node osmChange = XmlUtils.parseSafeDOM(xml).getFirstChild();
     111
     112            //get all nodes first, in order to be able to call all nodes references and create the geometries
     113            for (int i = 0; i < osmChange.getChildNodes().getLength(); i++) {
     114                String changeType = osmChange.getChildNodes().item(i).getNodeName();
     115                if (!(changeType.equals("#text") || changeType.equals("delete"))) {
     116
     117                    NodeList changeChilds = osmChange.getChildNodes().item(i).getChildNodes();
     118
     119                    Node osmObject = changeChilds.item(1);
     120
     121                    if (osmObject.getNodeName().equals("node")) {
     122                        //node data
     123                        nodeTmp = new OSMNode();
     124                        nodeTmp.setID(osmObject.getAttributes().getNamedItem("id").getNodeValue());
     125
     126                        //parse geometry
     127                        double longitude = Double.parseDouble(osmObject.getAttributes().getNamedItem("lon").getNodeValue());
     128                        double latitude = Double.parseDouble(osmObject.getAttributes().getNamedItem("lat").getNodeValue());
     129                        Coordinate targetGeometry = null;
     130                        Coordinate sourceCoordinate = new Coordinate(longitude, latitude);
     131                        try {
     132                            targetGeometry = JTS.transform(sourceCoordinate, null, transform);
     133                        } catch (MismatchedDimensionException | TransformException ex) {
     134                            Logger.getLogger(HistoryParser.class.getName()).log(Level.SEVERE, null, ex);
     135                        }
     136
     137                        //create geometry object
     138                        Geometry geom = geometryFactory.createPoint(new Coordinate(targetGeometry));
     139                        nodeTmp.setGeometry(geom);
     140
     141                        nodeList.add(nodeTmp);
     142                        nodesWithIDs.put(nodeTmp.getID(), nodeTmp);
     143                    }
     144                }
     145            }
     146
     147            for (int i = 0; i < osmChange.getChildNodes().getLength(); i++) {
     148                String changeType = osmChange.getChildNodes().item(i).getNodeName();
     149                if (!(changeType.equals("#text") || changeType.equals("delete"))) {
     150                    NodeList changeChilds = osmChange.getChildNodes().item(i).getChildNodes();
     151
     152                    Node osmObject = changeChilds.item(1);
     153                    if (osmObject.getNodeName().equals("way")) {
     154
     155                        //get way data
     156                        wayTmp = new OSMWay();
     157                        wayTmp.setID(osmObject.getAttributes().getNamedItem("id").getNodeValue());
     158                        // extract tags, then set tags to osm object
     159                        Logging.debug("\n\nWAY: " + wayTmp.getID());
     160                        for (int l = 0; l < osmObject.getChildNodes().getLength(); l++) {
     161                            String wayChild = osmObject.getChildNodes().item(l).getNodeName();
     162
     163                            if (wayChild.equals("tag")) {
     164                                String key = osmObject.getChildNodes().item(l).getAttributes().getNamedItem("k").getNodeValue();
     165                                String value = osmObject.getChildNodes().item(l).getAttributes().getNamedItem("v").getNodeValue();
     166                                System.out.println("key: " + key + " value: " + value);
     167                                wayTmp.setTagKeyValue(key, value);
     168                            } else if (wayChild.equals("nd")) {
     169                                wayTmp.addNodeReference(osmObject.getChildNodes().item(l).getAttributes().getNamedItem("ref").getNodeValue());
     170                            }
     171                        }
     172
     173                        //construct the Way geometry from each node of the node references
     174                        List<String> references = wayTmp.getNodeReferences();
     175
     176                        for (String entry: references) {
     177                            if (nodesWithIDs.containsKey(entry)) {
     178                                Geometry geometry = nodesWithIDs.get(entry).getGeometry(); //get the geometry of the node with ID=entry
     179                                wayTmp.addNodeGeometry(geometry); //add the node geometry in this way
     180                            } else {
     181                                Logging.debug("nodes with ids, no entry " + entry);
     182                                getNodeFromAPI(entry);
     183                            }
     184                        }
     185
     186                        Geometry geom = geometryFactory.buildGeometry(wayTmp.getNodeGeometries());
     187                        if ((wayTmp.getNodeGeometries().size() > 3) &&
     188                                wayTmp.getNodeGeometries().get(0).equals(wayTmp.getNodeGeometries()
     189                                        .get(wayTmp.getNodeGeometries().size()-1))) {
     190                            //checks if the beginning and ending node are the same and the number of nodes are more than 3.
     191                            //the nodes must be more than 3, because jts does not allow a construction of a linear ring with less points.
     192
     193                            if (!((wayTmp.getTagKeyValue().containsKey("barrier")) || wayTmp.getTagKeyValue().containsKey("highway"))) {
     194                                //this is not a barrier nor a road, so construct a polygon geometry
     195
     196                                LinearRing linear = geometryFactory.createLinearRing(geom.getCoordinates());
     197                                Polygon poly = new Polygon(linear, null, geometryFactory);
     198                                wayTmp.setGeometry(poly);
     199                            } else {
     200                                //it is either a barrier or a road, so construct a linear ring geometry
     201                                LinearRing linear = geometryFactory.createLinearRing(geom.getCoordinates());
     202                                wayTmp.setGeometry(linear);
     203                            }
     204                        } else if (wayTmp.getNodeGeometries().size() > 1) {
     205                            //it is an open geometry with more than one nodes, make it linestring
     206
     207                            LineString lineString = geometryFactory.createLineString(geom.getCoordinates());
     208                            wayTmp.setGeometry(lineString);
     209                        } else { //we assume all the rest geometries are points
     210                            //some ways happen to have only one point. Construct a  Point.
     211                            Point point = geometryFactory.createPoint(geom.getCoordinate());
     212                            wayTmp.setGeometry(point);
     213                        }
     214                        wayList.add(wayTmp);
     215                    }
     216                }
     217            }
     218        } catch (IOException | ParserConfigurationException | SAXException ex) {
     219            Logger.getLogger(HistoryParser.class.getName()).log(Level.SEVERE, null, ex);
     220        }
     221    }
     222
     223    private String stripQuotes(String id) {
     224        return id.substring(4, id.length()-1);
     225    }
     226
     227    private void getNodeFromAPI(String nodeID) {
     228        try {
     229            String osmUrl = OSM_API + "node/" + nodeID;
     230            InputStream xml = HttpClient.create(new URL(osmUrl)).connect().getContent();
     231            NodeList nodes = XmlUtils.parseSafeDOM(xml).getElementsByTagName("node");
     232            String lat = nodes.item(0).getAttributes().getNamedItem("lat").getNodeValue();
     233            String lon = nodes.item(0).getAttributes().getNamedItem("lon").getNodeValue();
     234
     235            nodeTmp = new OSMNode();
     236            nodeTmp.setID(nodeID);
     237
     238            //parse geometry
     239            double longitude = Double.parseDouble(lon);
     240            double latitude = Double.parseDouble(lat);
     241            Coordinate targetGeometry = null;
     242            Coordinate sourceCoordinate = new Coordinate(longitude, latitude);
     243            try {
     244                targetGeometry = JTS.transform(sourceCoordinate, null, transform);
     245            } catch (MismatchedDimensionException | TransformException ex) {
     246                Logger.getLogger(HistoryParser.class.getName()).log(Level.SEVERE, null, ex);
     247            }
     248
     249            //create geometry object
     250            Geometry geom = geometryFactory.createPoint(new Coordinate(targetGeometry));
     251            nodeTmp.setGeometry(geom);
     252
     253            nodeList.add(nodeTmp);
     254            nodesWithIDs.put(nodeTmp.getID(), nodeTmp);
     255
     256        } catch (IOException | ParserConfigurationException | SAXException ex) {
     257            Logger.getLogger(HistoryParser.class.getName()).log(Level.SEVERE, null, ex);
     258        }
     259    }
     260
     261    public List<OSMWay> getWayList() {
     262        return wayList;
     263    }
    264264}
  • applications/editors/josm/plugins/OSMRecPlugin/src/org/openstreetmap/josm/plugins/osmrec/personalization/TrainByUser.java

    r33013 r34539  
    701701    protected void done() {
    702702        try {
    703             System.out.println("Training process complete! - > " + get());
     703            get();
    704704            firePropertyChange("progress", getProgress(), 100);
    705705            setProgress(100);
  • applications/editors/josm/plugins/OSMRecPlugin/src/org/openstreetmap/josm/plugins/osmrec/personalization/UserDataExtractAndTrainWorker.java

    r32404 r34539  
    4040    private final boolean topKIsSelected;
    4141    private final LanguageDetector languageDetector;
    42     private int userTrainProgress = 0;
    4342
    4443    public UserDataExtractAndTrainWorker(String inputFilePath, String username, Integer days, boolean byArea, boolean validateFlag,
Note: See TracChangeset for help on using the changeset viewer.