Example usage for org.w3c.dom Document getElementsByTagName

List of usage examples for org.w3c.dom Document getElementsByTagName

Introduction

In this page you can find the example usage for org.w3c.dom Document getElementsByTagName.

Prototype

public NodeList getElementsByTagName(String tagname);

Source Link

Document

Returns a NodeList of all the Elements in document order with a given tag name and are contained in the document.

Usage

From source file:Models.Geographic.Repository.RepositoryGoogle.java

/**
 * Method that geocoding a address from google api
 * @param country/*from w  ww  .  j a  v  a  2 s .  com*/
 * @param adm1
 * @param adm2
 * @param adm3
 * @param local_area
 * @param locality
 * @param uncertainty
 * @return 
 */
public static Location georenferencing(String country, String adm1, String adm2, String adm3, String local_area,
        String locality, double uncertainty) {
    Location a = null;
    String key;
    try {
        key = FixData.generateKey(new String[] { country, adm1, adm2, adm3, local_area, locality });
        if (RepositoryGoogle.db == null)
            RepositoryGoogle.db = new HashMap();
        if (RepositoryGoogle.db.containsKey(key))
            return (Location) RepositoryGoogle.db.get(key);
        String data = (!locality.equals("") ? locality : "")
                + (!local_area.equals("") ? local_area + "+,+" : "") + (!adm3.equals("") ? adm3 + "+,+" : "")
                + (!adm2.equals("") ? adm2 + "+,+" : "") + (!adm1.equals("") ? adm1 + "+,+" : "")
                + (!country.equals("") ? country + "+,+" : "");
        URL url = new URL(Configuration.getParameter("geocoding_google_url_send_xml") + "address="
                + data.replace(" ", "%20").replace(".", "").replace(";", ""));
        URL file_url = new URL(
                url.getProtocol() + "://" + url.getHost() + signRequest(url.getPath(), url.getQuery()));
        // Get information from URL
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        // Create a proxy to work in CIAT (erase this in another place)
        //Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("proxy2.ciat.cgiar.org", 8080));
        DocumentBuilder db = dbf.newDocumentBuilder();
        //Document doc = db.parse(file_url.openConnection(proxy).getInputStream());
        Document doc = db.parse(file_url.openConnection().getInputStream());
        // Document with data
        if (doc != null) {
            NodeList locationList = doc.getElementsByTagName("location");
            NodeList locationTypeList = doc.getElementsByTagName("location_type");
            NodeList viewPortList = doc.getElementsByTagName("viewport");
            Node location = null, lat = null, lng = null;
            if (locationList.getLength() > 0) {
                for (int i = 0; i < locationList.getLength(); i++) {
                    location = locationList.item(i);
                    if (location.hasChildNodes()) {
                        lat = location.getChildNodes().item(1);
                        lng = location.getChildNodes().item(3);
                    }
                }
                Node locationType = null;
                if (locationTypeList.getLength() > 0) {
                    for (int i = 0; i < locationTypeList.getLength(); i++)
                        locationType = locationTypeList.item(i);
                }
                Node viewPort = null, northeast = null, southwest = null, lat_northeast = null,
                        lng_northeast = null, lat_southwest = null, lng_southwest = null;
                if (viewPortList.getLength() > 0) {
                    for (int i = 0; i < viewPortList.getLength(); i++) {
                        viewPort = viewPortList.item(i);
                        if (viewPort.hasChildNodes()) {
                            northeast = viewPort.getChildNodes().item(1);
                            southwest = viewPort.getChildNodes().item(3);
                        }
                        /* Extract data from viewport field */
                        if (northeast.hasChildNodes()) {
                            lat_northeast = northeast.getChildNodes().item(1);
                            lng_northeast = northeast.getChildNodes().item(3);
                        }
                        if (southwest.hasChildNodes()) {
                            lat_southwest = southwest.getChildNodes().item(1);
                            lng_southwest = southwest.getChildNodes().item(3);
                        }
                    }
                }
                double[] coordValues = new double[] { Double.parseDouble(lat.getTextContent()),
                        Double.parseDouble(lng.getTextContent()) };
                double[] coordValuesNortheast = new double[] {
                        Double.parseDouble(lat_northeast.getTextContent()),
                        Double.parseDouble(lng_northeast.getTextContent()) };
                double[] coordValuesSouthwest = new double[] {
                        Double.parseDouble(lat_southwest.getTextContent()),
                        Double.parseDouble(lng_southwest.getTextContent()) };
                double distance = FixData.getDistance(coordValuesNortheast, coordValuesSouthwest);
                // Distance - km between Northeast and Southeast                    
                if (distance <= uncertainty)
                    a = new Location(coordValues[0], coordValues[1], distance);
                else {
                    RepositoryGoogle.db.put(key, a);
                    throw new Exception("Exceede uncertainty. " + "Uncertainty: " + distance + " THRESHOLD: "
                            + Configuration.getParameter("geocoding_threshold"));
                }

            }
        }
        RepositoryGoogle.db.put(key, a);
    } catch (NoSuchAlgorithmException | InvalidKeyException | URISyntaxException | IOException
            | ParserConfigurationException | SAXException ex) {
        System.out.println(ex);
    } catch (Exception ex) {
        System.out.println(ex);
    }
    return a;
}

From source file:edu.stanford.muse.webapp.Accounts.java

/** does account setup and login (and look up default folder if well-known account) from the given request.
 * request params are loginName<N>, password<N>, etc (see loginForm for details).
 * returns an object with {status: 0} if success, or {status: <non-zero>, errorMessage: '... '} if failure.
 * if success and account has a well-known sent mail folder, the returned object also has something like: 
 * {defaultFolder: '[Gmail]/Sent Mail', defaultFolderCount: 1033}
 * accounts on the login page are numbered 0 upwards. */
public static JSONObject login(HttpServletRequest request, int accountNum) throws IOException, JSONException {
    JSONObject result = new JSONObject();

    HttpSession session = request.getSession();
    // allocate the fetcher if it doesn't already exist
    MuseEmailFetcher m = null;//from  ww  w. j  ava 2s  .  c om
    synchronized (session) // synchronize, otherwise may lose the fetcher when multiple accounts are specified and are logged in to simult.
    {
        m = (MuseEmailFetcher) JSPHelper.getSessionAttribute(session, "museEmailFetcher");
        boolean doIncremental = request.getParameter("incremental") != null;

        if (m == null || !doIncremental) {
            m = new MuseEmailFetcher();
            session.setAttribute("museEmailFetcher", m);
        }
    }

    // note: the same params get posted with every accountNum
    // we'll update for all account nums, because sometimes account #0 may not be used, only #1 onwards. This should be harmless.
    // we used to do only altemailaddrs, but now also include the name.
    updateUserInfo(request);

    String accountType = request.getParameter("accountType" + accountNum);
    if (Util.nullOrEmpty(accountType)) {
        result.put("status", 1);
        result.put("errorMessage", "No information for account #" + accountNum);
        return result;
    }

    String loginName = request.getParameter("loginName" + accountNum);
    String password = request.getParameter("password" + accountNum);
    String protocol = request.getParameter("protocol" + accountNum);
    //   String port = request.getParameter("protocol" + accountNum);  // we don't support pop/imap on custom ports currently. can support server.com:port syntax some day
    String server = request.getParameter("server" + accountNum);
    String defaultFolder = request.getParameter("defaultFolder" + accountNum);

    if (server != null)
        server = server.trim();

    if (loginName != null)
        loginName = loginName.trim();

    // for these ESPs, the user may have typed in the whole address or just his/her login name
    if (accountType.equals("gmail") && loginName.indexOf("@") < 0)
        loginName = loginName + "@gmail.com";
    if (accountType.equals("yahoo") && loginName.indexOf("@") < 0)
        loginName = loginName + "@yahoo.com";
    if (accountType.equals("live") && loginName.indexOf("@") < 0)
        loginName = loginName + "@live.com";
    if (accountType.equals("stanford") && loginName.indexOf("@") < 0)
        loginName = loginName + "@stanford.edu";
    if (accountType.equals("gmail"))
        server = "imap.gmail.com";

    // add imapdb stuff here.
    boolean imapDBLookupFailed = false;
    String errorMessage = "";
    int errorStatus = 0;

    if (accountType.equals("email") && Util.nullOrEmpty(server)) {
        log.info("accountType = email");

        defaultFolder = "Sent";

        {
            // ISPDB from Mozilla
            imapDBLookupFailed = true;

            String emailDomain = loginName.substring(loginName.indexOf("@") + 1);
            log.info("Domain: " + emailDomain);

            // from http://suhothayan.blogspot.in/2012/05/how-to-install-java-cryptography.html
            // to get around the need for installingthe unlimited strength encryption policy files.
            try {
                Field field = Class.forName("javax.crypto.JceSecurity").getDeclaredField("isRestricted");
                field.setAccessible(true);
                field.set(null, java.lang.Boolean.FALSE);
            } catch (Exception ex) {
                ex.printStackTrace();
            }

            //            URL url = new URL("https://live.mozillamessaging.com/autoconfig/v1.1/" + emailDomain);
            URL url = new URL("https://autoconfig.thunderbird.net/v1.1/" + emailDomain);
            try {
                URLConnection urlConnection = url.openConnection();
                InputStream in = new BufferedInputStream(urlConnection.getInputStream());

                DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
                DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
                Document doc = dBuilder.parse(in);

                NodeList configList = doc.getElementsByTagName("incomingServer");
                log.info("configList.getLength(): " + configList.getLength());

                int i;
                for (i = 0; i < configList.getLength(); i++) {
                    Node config = configList.item(i);
                    NamedNodeMap attributes = config.getAttributes();
                    if (attributes.getNamedItem("type").getNodeValue().equals("imap")) {
                        log.info("[" + i + "] type: " + attributes.getNamedItem("type").getNodeValue());
                        Node param = config.getFirstChild();
                        String nodeName, nodeValue;
                        String paramHostName = "";
                        String paramUserName = "";
                        do {
                            if (param.getNodeType() == Node.ELEMENT_NODE) {
                                nodeName = param.getNodeName();
                                nodeValue = param.getTextContent();
                                log.info(nodeName + "=" + nodeValue);
                                if (nodeName.equals("hostname")) {
                                    paramHostName = nodeValue;
                                } else if (nodeName.equals("username")) {
                                    paramUserName = nodeValue;
                                }
                            }
                            param = param.getNextSibling();
                        } while (param != null);

                        log.info("paramHostName = " + paramHostName);
                        log.info("paramUserName = " + paramUserName);

                        server = paramHostName;
                        imapDBLookupFailed = false;
                        if (paramUserName.equals("%EMAILADDRESS%")) {
                            // Nothing to do with loginName
                        } else if (paramUserName.equals("%EMAILLOCALPART%")
                                || paramUserName.equals("%USERNAME%")) {
                            // Cut only local part
                            loginName = loginName.substring(0, loginName.indexOf('@') - 1);
                        } else {
                            imapDBLookupFailed = true;
                            errorMessage = "Invalid auto configuration";
                        }

                        break; // break after find first IMAP host name
                    }
                }
            } catch (Exception e) {
                Util.print_exception("Exception trying to read ISPDB", e, log);
                errorStatus = 2; // status code = 2 => ispdb lookup failed
                errorMessage = "No automatic configuration available for " + emailDomain
                        + ", please use the option to provide a private (IMAP) server. \nDetails: "
                        + e.getMessage()
                        + ". \nRunning with java -Djavax.net.debug=all may provide more details.";
            }
        }
    }

    if (imapDBLookupFailed) {
        log.info("ISPDB Fail");
        result.put("status", errorStatus);
        result.put("errorMessage", errorMessage);
        // add other fields here if needed such as server name attempted to be looked up in case the front end wants to give a message to the user
        return result;
    }

    boolean isServerAccount = accountType.equals("gmail") || accountType.equals("email")
            || accountType.equals("yahoo") || accountType.equals("live") || accountType.equals("stanford")
            || accountType.equals("gapps") || accountType.equals("imap") || accountType.equals("pop")
            || accountType.startsWith("Thunderbird");

    if (isServerAccount) {
        boolean sentOnly = "on".equals(request.getParameter("sent-messages-only"));
        return m.addServerAccount(server, protocol, defaultFolder, loginName, password, sentOnly);
    } else if (accountType.equals("mbox") || accountType.equals("tbirdLocalFolders")) {
        try {
            String mboxDir = request.getParameter("mboxDir" + accountNum);
            String emailSource = request.getParameter("emailSource" + accountNum);
            // for non-std local folders dir, tbird prefs.js has a line like: user_pref("mail.server.server1.directory-rel", "[ProfD]../../../../../../tmp/tb");
            log.info("adding mbox account: " + mboxDir);
            errorMessage = m.addMboxAccount(emailSource, mboxDir, accountType.equals("tbirdLocalFolders"));
            if (!Util.nullOrEmpty(errorMessage)) {
                result.put("errorMessage", errorMessage);
                result.put("status", 1);
            } else
                result.put("status", 0);
        } catch (MboxFolderNotReadableException e) {
            result.put("errorMessage", e.getMessage());
            result.put("status", 1);
        }
    } else {
        result.put("errorMessage", "Sorry, unknown account type: " + accountType);
        result.put("status", 1);
    }
    return result;
}

From source file:com.github.sevntu.checkstyle.internal.ChecksTest.java

private static void validateSonarFile(Document document, Set<Class<?>> modules) {
    final NodeList rules = document.getElementsByTagName("rule");

    for (int position = 0; position < rules.getLength(); position++) {
        final Node rule = rules.item(position);
        final Set<Node> children = XmlUtil.getChildrenElements(rule);

        final String key = SevntuXmlUtil.findElementByTag(children, "key").getTextContent();

        final Class<?> module = findModule(modules, key);
        modules.remove(module);/*from  ww  w. ja v  a  2  s.  c  o  m*/

        Assert.assertNotNull("Unknown class found in sonar: " + key, module);

        final String moduleName = module.getName();
        final Node name = SevntuXmlUtil.findElementByTag(children, "name");

        Assert.assertNotNull(moduleName + " requires a name in sonar", name);
        Assert.assertFalse(moduleName + " requires a name in sonar", name.getTextContent().isEmpty());

        final Node categoryNode = SevntuXmlUtil.findElementByTag(children, "category");

        String expectedCategory = module.getCanonicalName();
        final int lastIndex = expectedCategory.lastIndexOf('.');
        expectedCategory = expectedCategory.substring(expectedCategory.lastIndexOf('.', lastIndex - 1) + 1,
                lastIndex);

        Assert.assertNotNull(moduleName + " requires a category in sonar", categoryNode);

        final Node categoryAttribute = categoryNode.getAttributes().getNamedItem("name");

        Assert.assertNotNull(moduleName + " requires a category name in sonar", categoryAttribute);
        Assert.assertEquals(moduleName + " requires a valid category in sonar", expectedCategory,
                categoryAttribute.getTextContent());

        final Node description = SevntuXmlUtil.findElementByTag(children, "description");

        Assert.assertNotNull(moduleName + " requires a description in sonar", description);

        final Node configKey = SevntuXmlUtil.findElementByTag(children, "configKey");
        final String expectedConfigKey = "Checker/TreeWalker/" + key;

        Assert.assertNotNull(moduleName + " requires a configKey in sonar", configKey);
        Assert.assertEquals(moduleName + " requires a valid configKey in sonar", expectedConfigKey,
                configKey.getTextContent());

        validateSonarProperties(module, SevntuXmlUtil.findElementsByTag(children, "param"));
    }

    for (Class<?> module : modules) {
        Assert.fail("Module not found in sonar: " + module.getCanonicalName());
    }
}

From source file:com.github.sevntu.checkstyle.internal.ChecksTest.java

private static void validateEclipseCsMetaXmlFile(File file, String pkg, Set<Class<?>> pkgModules)
        throws Exception {
    Assert.assertTrue("'checkstyle-metadata.xml' must exist in eclipsecs in inside " + pkg, file.exists());

    final String input = new String(Files.readAllBytes(file.toPath()), UTF_8);
    final Document document = XmlUtil.getRawXml(file.getAbsolutePath(), input, input);

    final NodeList ruleGroups = document.getElementsByTagName("rule-group-metadata");

    Assert.assertTrue(pkg + " checkstyle-metadata.xml must contain only one rule group",
            ruleGroups.getLength() == 1);

    for (int position = 0; position < ruleGroups.getLength(); position++) {
        final Node ruleGroup = ruleGroups.item(position);
        final Set<Node> children = XmlUtil.getChildrenElements(ruleGroup);

        validateEclipseCsMetaXmlFileRules(pkg, pkgModules, children);
    }//from w ww .  j  av  a2  s .c om

    for (Class<?> module : pkgModules) {
        Assert.fail("Module not found in " + pkg + " checkstyle-metadata.xml: " + module.getCanonicalName());
    }
}

From source file:org.apache.ofbiz.passport.user.LinkedInAuthenticator.java

public static String getLinkedInUserId(Document userInfo) {
    NodeList persons = userInfo.getElementsByTagName("person");
    if (UtilValidate.isEmpty(persons) || persons.getLength() <= 0) {
        return null;
    }/*  ww w.java 2  s .co  m*/
    Element standardProfileRequest = UtilXml.firstChildElement((Element) persons.item(0),
            "site-standard-profile-request");
    Element url = UtilXml.firstChildElement(standardProfileRequest, "url");
    if (UtilValidate.isNotEmpty(url)) {
        String urlContent = url.getTextContent();
        if (UtilValidate.isNotEmpty(urlContent)) {
            String id = urlContent.substring(urlContent.indexOf("?id="));
            id = id.substring(0, id.indexOf("&"));
            Debug.logInfo("LinkedIn user id: " + id, module);
            return id;
        }
    }
    return null;
}

From source file:org.openiot.gsn.utils.GSNMonitor.java

public static void parseXML(String s) {
    try {// www  . j  av  a  2s . co m

        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
        InputSource inputSource = new InputSource();
        inputSource.setCharacterStream(new StringReader(s));

        Document document = documentBuilder.parse(inputSource);
        NodeList nodes = document.getElementsByTagName("virtual-sensor");

        for (int i = 0; i < nodes.getLength(); i++) {
            Element element = (Element) nodes.item(i);

            String sensor_name = element.getAttribute("name");

            if (!sensorsUpdateDelay.containsKey(sensor_name))
                continue; // skip sensors that are not monitored

            logger.warn("Sensor: " + sensor_name);

            NodeList listOfField = element.getElementsByTagName("field");
            for (int j = 0; j < listOfField.getLength(); j++) {
                Element line = (Element) listOfField.item(j);

                if (line.getAttribute("name").indexOf("timed") >= 0) {
                    String last_updated_as_string = line.getTextContent();

                    try {
                        Long last_updated_as_Long = GregorianCalendar.getInstance().getTimeInMillis()
                                - VSensorMonitorConfig.datetime2timestamp(last_updated_as_string);
                        logger.warn(new StringBuilder(last_updated_as_string).append(" => ")
                                .append(VSensorMonitorConfig.ms2dhms(last_updated_as_Long)).toString());

                        sensorsUpdateDelay.put(sensor_name, last_updated_as_Long);
                    } catch (ParseException e) {
                        errorsBuffer.append("Last update time for sensor ").append(sensor_name)
                                .append(" cannot be read. Error while parsing > ")
                                .append(last_updated_as_string).append(" <\n");
                    }
                }
            }
        }
    } catch (Exception e) {
        logger.warn("Exception while parsing XML\n");
        e.printStackTrace();
    }
}

From source file:net.roboconf.target.azure.internal.AzureIaasHandler.java

private static boolean getExistResutlFromXML(String xmlStr, String nameOfNode)
        throws ParserConfigurationException, SAXException, IOException {

    DocumentBuilderFactory f = DocumentBuilderFactory.newInstance();
    DocumentBuilder b;// ww  w  .ja v a2s .  c  o m
    b = f.newDocumentBuilder();
    Document doc;
    doc = b.parse(new ByteArrayInputStream(xmlStr.getBytes("UTF-8")));
    NodeList nodes = doc.getElementsByTagName(nameOfNode);
    String result = "false";
    for (int i = 0; i < nodes.getLength(); i++) {
        Element node = (Element) nodes.item(i);
        result = node.getTextContent();
    }

    return Boolean.parseBoolean(result);
}

From source file:edu.illinois.cs.cogcomp.utils.Utils.java

/**
 * Used for reading data from the NEWS2015 dataset.
 * @param fname//from   w ww  . j a v a 2s.  c om
 * @return
 * @throws ParserConfigurationException
 * @throws IOException
 * @throws SAXException
 */
public static List<MultiExample> readNEWSData(String fname)
        throws ParserConfigurationException, IOException, SAXException {
    File file = new File(fname);
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    DocumentBuilder db = dbf.newDocumentBuilder();
    Document document = db.parse(file);

    NodeList nl = document.getElementsByTagName("Name");

    List<MultiExample> examples = new ArrayList<>();

    for (int i = 0; i < nl.getLength(); i++) {
        Node n = nl.item(i);

        NodeList sourceandtargets = n.getChildNodes();
        MultiExample me = null;
        for (int j = 0; j < sourceandtargets.getLength(); j++) {

            Node st = sourceandtargets.item(j);
            if (st.getNodeName().equals("SourceName")) {
                me = new MultiExample(st.getTextContent().toLowerCase(), new ArrayList<String>());
            } else if (st.getNodeName().equals("TargetName")) {
                if (me != null) {
                    me.addTransliteratedWord(st.getTextContent());
                }
            }
        }
        examples.add(me);
    }

    return examples;
}

From source file:eu.eidas.auth.engine.configuration.dom.DOMConfigurationParser.java

/**
 * Read configuration.//w  w w  .j a v  a 2s . c  o m
 *
 * @return the map< string, instance engine>
 * @throws SAMLEngineException the EIDASSAML engine runtime exception
 */
@Nonnull
public static InstanceMap parseConfiguration(@Nonnull String configurationFileName,
        @Nonnull InputStream inputStream) throws SamlEngineConfigurationException {
    Preconditions.checkNotNull(configurationFileName, "configurationFileName");
    Preconditions.checkNotNull(inputStream, "inputStream");
    try {
        Document document;
        try (InputStream engineConf = inputStream) {
            document = DocumentBuilderFactoryUtil.parse(engineConf);
        }
        // Read instance
        NodeList instanceTags = document.getElementsByTagName(InstanceTag.TAG_NAME);

        Map<String, InstanceEntry> instanceEntries = new LinkedHashMap<String, InstanceEntry>();

        for (int i = 0, n = instanceTags.getLength(); i < n; i++) {
            Element instanceTag = (Element) instanceTags.item(i);
            InstanceEntry instanceEntry = parseInstanceEntry(configurationFileName, instanceTag);

            // Add to the list of configurations.
            InstanceEntry previous = instanceEntries.put(instanceEntry.getName(), instanceEntry);

            if (null != previous) {
                String message = "Duplicate instance entry names \"" + instanceEntry.getName()
                        + "\" in SAML engine configuration file \"" + configurationFileName + "\"";
                LOG.error(message);
                throw new SamlEngineConfigurationException(message);
            }
        }

        return new InstanceMap(ImmutableMap.copyOf(instanceEntries));
    } catch (IOException | SAXException | ParserConfigurationException ex) {
        LOG.error(ex.getMessage(), ex);
        throw new SamlEngineConfigurationException(ex);
    }
}

From source file:it.osm.gtfs.input.OSMParser.java

public static List<Stop> readOSMStops(String fileName)
        throws ParserConfigurationException, SAXException, IOException {
    List<Stop> result = new ArrayList<Stop>();
    Multimap<String, Stop> refBuses = HashMultimap.create();
    Multimap<String, Stop> refRails = HashMultimap.create();

    File file = new File(fileName);
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    DocumentBuilder db = dbf.newDocumentBuilder();
    Document doc = db.parse(file);
    doc.getDocumentElement().normalize();

    NodeList nodeLst = doc.getElementsByTagName("node");

    for (int s = 0; s < nodeLst.getLength(); s++) {
        Node fstNode = nodeLst.item(s);
        Stop st = new Stop(null, null,
                Double.valueOf(fstNode.getAttributes().getNamedItem("lat").getNodeValue()),
                Double.valueOf(fstNode.getAttributes().getNamedItem("lon").getNodeValue()), null);
        st.originalXMLNode = fstNode;//from  w  w w.  j  a  va2  s .  c  o m
        NodeList att = fstNode.getChildNodes();
        for (int t = 0; t < att.getLength(); t++) {
            Node attNode = att.item(t);
            if (attNode.getAttributes() != null) {
                if (attNode.getAttributes().getNamedItem("k").getNodeValue().equals("ref"))
                    st.setCode(attNode.getAttributes().getNamedItem("v").getNodeValue());
                if (attNode.getAttributes().getNamedItem("k").getNodeValue().equals("name"))
                    st.setName(attNode.getAttributes().getNamedItem("v").getNodeValue());
                if (attNode.getAttributes().getNamedItem("k").getNodeValue().equals("gtfs_id"))
                    st.setGtfsId(attNode.getAttributes().getNamedItem("v").getNodeValue());
                if (attNode.getAttributes().getNamedItem("k").getNodeValue().equals("highway")
                        && attNode.getAttributes().getNamedItem("v").getNodeValue().equals("bus_stop"))
                    st.setIsRailway(false);
                if (attNode.getAttributes().getNamedItem("k").getNodeValue().equals("railway")
                        && attNode.getAttributes().getNamedItem("v").getNodeValue().equals("tram_stop"))
                    st.setIsRailway(true);
                if (attNode.getAttributes().getNamedItem("k").getNodeValue().equals("railway")
                        && attNode.getAttributes().getNamedItem("v").getNodeValue().equals("station"))
                    st.setIsRailway(true);
                if (attNode.getAttributes().getNamedItem("k").getNodeValue().equals("public_transport")
                        && attNode.getAttributes().getNamedItem("v").getNodeValue().equals("stop_position")
                        && st.isRailway() == null)
                    st.setIsStopPosition(true);
                if (attNode.getAttributes().getNamedItem("k").getNodeValue().equals("train")
                        && attNode.getAttributes().getNamedItem("v").getNodeValue().equals("yes"))
                    st.setIsRailway(true);
                if (attNode.getAttributes().getNamedItem("k").getNodeValue().equals("tram")
                        && attNode.getAttributes().getNamedItem("v").getNodeValue().equals("yes"))
                    st.setIsRailway(true);
                if (attNode.getAttributes().getNamedItem("k").getNodeValue().equals("bus")
                        && attNode.getAttributes().getNamedItem("v").getNodeValue().equals("yes"))
                    st.setIsRailway(false);
            }
        }

        if (st.isRailway() == null)
            if (st.isStopPosition())
                continue; //ignore unsupported stop positions (like ferries)
            else
                throw new IllegalArgumentException("Unknow node type for node: " + st.getOSMId()
                        + ". We support only highway=bus_stop, public_transport=stop_position, railway=tram_stop and railway=station");

        //Check duplicate ref in osm
        if (st.getCode() != null) {
            if (st.isStopPosition() == null || st.isStopPosition() == false) {
                if (st.isRailway()) {
                    if (refRails.containsKey(st.getCode())) {
                        for (Stop existingStop : refRails.get(st.getCode())) {
                            if (OSMDistanceUtils.distVincenty(st.getLat(), st.getLon(), existingStop.getLat(),
                                    existingStop.getLon()) < 500)
                                System.err.println("Warning: The ref " + st.getCode()
                                        + " is used in more than one node within 500m this may lead to bad import."
                                        + " (nodes ids:" + st.getOSMId() + "," + existingStop.getOSMId() + ")");
                        }
                    }

                    refRails.put(st.getCode(), st);
                } else {
                    if (refBuses.containsKey(st.getCode())) {
                        for (Stop existingStop : refBuses.get(st.getCode())) {
                            if (OSMDistanceUtils.distVincenty(st.getLat(), st.getLon(), existingStop.getLat(),
                                    existingStop.getLon()) < 500)
                                System.err.println("Warning: The ref " + st.getCode()
                                        + " is used in more than one node within 500m this may lead to bad import."
                                        + " (nodes ids:" + st.getOSMId() + "," + existingStop.getOSMId() + ")");
                        }
                    }
                    refBuses.put(st.getCode(), st);
                }
            }
        }
        result.add(st);
    }

    return result;
}