Example usage for org.dom4j Node valueOf

List of usage examples for org.dom4j Node valueOf

Introduction

In this page you can find the example usage for org.dom4j Node valueOf.

Prototype

String valueOf(String xpathExpression);

Source Link

Document

valueOf evaluates an XPath expression and returns the textual representation of the results the XPath string-value of this node.

Usage

From source file:com.noterik.bart.fs.script.ActionSet.java

License:Open Source License

/**
 * Parses the input document for actions
 * /*from   w  w  w .  j  a  va2 s. c  o  m*/
 * @param doc
 */
private void parseActions(Document doc) {
    logger.debug("parsing actions");

    // get action nodes
    List<Node> actionlist = doc.selectNodes("//action");

    // loop through nodes
    Node node;
    Action action;
    Properties properties;
    String refer;
    String jarName;
    String className = "";
    Class<?> actionClass = null;
    for (Iterator<Node> iter1 = actionlist.iterator(); iter1.hasNext();) {
        node = iter1.next();
        action = null;

        // init action class
        refer = node.valueOf("@referid");

        try {
            refer = refer.substring(ReferUriType.JAVA_URI.getProtocol().length());

            //check if we need to load from additional jar
            if (refer.indexOf("@") != -1) {
                className = refer.substring(0, refer.indexOf("@"));
                jarName = refer.substring(refer.indexOf("@") + 1);

                logger.info("Loading jar " + jarName + " for class " + className);
                actionClass = loadJar(jarName, className);
            } else {
                className = refer;
                actionClass = Class.forName(className);
            }

            if (actionClass != null) {
                action = (Action) actionClass.newInstance();
            }
        } catch (Exception e) {
            logger.error("Error while initiating class: " + className + ", for id: " + id + " " + e);
        }

        if (action != null) {
            // TODO: get and set properties of action
            properties = null;
            action.setProperties(properties);

            // set uri
            String uri = id + "/action/" + node.valueOf("@id");
            action.setID(uri);

            // set script
            action.setScript(script);

            logger.debug("adding action: " + className + ", uri=" + uri);

            // add to list of actions
            addAction(action);
        }
    }
}

From source file:com.taobao.tddl.common.sequence.Config.java

License:Open Source License

public static Config createConfig(Node generator) throws ConfigException {
    Config config = new Config();

    String typeStr = generator.valueOf("@type");
    if (typeStr == null || "".equals(typeStr) || "default".equals(typeStr)) {
        config.setType(DEFAULT);/*from www .ja  va 2 s  .  c  o  m*/
    } else if ("long2date".equals(typeStr)) {
        config.setType(Long2DATE);
    } else {
        throw new Config.ConfigException("unsupported generator type!");
    }

    Node route = generator.selectSingleNode("route");
    if (route != null) {
        String position = route.valueOf("@position");
        if ("right".equals(position) || "".equals(position)) {
            config.setPositionRight(true);
        } else if ("left".equals(position)) {
            config.setPositionRight(false);
        } else {
            throw new Config.ConfigException();
        }
        String overFlowCheckStr = route.valueOf("@overflowcheck");
        if ("on".equals(overFlowCheckStr) || "".equals(overFlowCheckStr)) {
            config.setOverFlowCheck(true);
        } else if ("off".equals(overFlowCheckStr)) {
            config.setOverFlowCheck(false);
        } else {
            throw new Config.ConfigException();
        }
        String totalSizeStr = route.valueOf("@size");
        if (totalSizeStr != null && !"".equals(totalSizeStr)) {
            try {
                config.setTotalSize(Integer.parseInt(totalSizeStr));
            } catch (NumberFormatException e) {
                throw new Config.ConfigException();
            }
        }

        Node database = route.selectSingleNode("database");
        int routeSize = 0;
        if (database != null) {
            Route dbRoute = new Route();
            try {
                dbRoute.setSize(Integer.parseInt(database.valueOf("@size")));
                routeSize += dbRoute.getSize();
            } catch (NumberFormatException e) {
                throw new Config.ConfigException();
            }
            dbRoute.setExpression(ExpressionFactory.create(database.selectSingleNode("*")));
            config.setDatabaseRoute(dbRoute);
        }

        Node table = route.selectSingleNode("table");
        if (table != null) {
            Route tableRoute = new Route();
            try {
                tableRoute.setSize(Integer.parseInt(table.valueOf("@size")));
                routeSize += tableRoute.getSize();
            } catch (NumberFormatException e) {
                throw new Config.ConfigException();
            }
            tableRoute.setExpression(ExpressionFactory.create(table.selectSingleNode("*")));
            config.setTablerRoute(tableRoute);
        }

        if (config.isOverFlowCheck() && routeSize > 8) {
            throw new Config.ConfigException("id()8");
        }
        if (config.getTotalSize() != 0 && routeSize != 0 && config.getTotalSize() != routeSize) {
            throw new Config.ConfigException();
        }
    }
    return config;
}

From source file:com.tonbeller.jpivot.tags.MondrianModelFactory.java

License:Common Public License

static String makeConnectString(String filers, Config cfg, IEngUserProfile profile) {

    // for an external datasource, we do not need JdbcUrl *and* data source

    // if ((cfg.getJdbcUrl() == null) == (cfg.getDataSource() == null))
    // throw new IllegalArgumentException("exactly one of jdbcUrl or dataSource must be specified");

    // provider=Mondrian;Jdbc=jdbc:odbc:MondrianFoodMart;Catalog=file:///c:/dev/mondrian/demo/FoodMart.xml
    StringBuffer sb = new StringBuffer("provider=Mondrian");
    if (cfg.getJdbcUrl() != null) {
        String jdbcUrl = cfg.getJdbcUrl();
        sb.append(";Jdbc=");
        // if the url contains a semicolon, it must be in quotes
        if (jdbcUrl.indexOf(';') >= 0) {
            char c = jdbcUrl.charAt(0);
            if (c != '"' && c != '\'') {
                char escape = '"';
                if (jdbcUrl.indexOf('"') >= 0) {
                    if (jdbcUrl.indexOf('\'') >= 0) {
                        // this is not valid
                        throw new IllegalArgumentException(
                                "jdbcUrl is not valid - contains single and double quotes");
                    }//from w  w w .j ava  2  s.  c om
                    escape = '\'';
                }
                sb.append(escape);
                sb.append(jdbcUrl);
                sb.append(escape);
            } else
                sb.append(jdbcUrl); // already quoted
        } else
            sb.append(jdbcUrl); // no quotes neccessary

        if (cfg.getJdbcUser() != null)
            sb.append(";JdbcUser=").append(cfg.getJdbcUser());
        if (cfg.getJdbcPassword() != null && cfg.getJdbcPassword().length() > 0)
            sb.append(";JdbcPassword=").append(cfg.getJdbcPassword());
    } else if (cfg.getDataSource() != null) {
        //sb.append(";DataSource=java:comp/env/").append(cfg.getDataSource());
        sb.append(";DataSource=").append(cfg.getDataSource());
        testDataSource(cfg.getDataSource());
    }
    sb.append(";Catalog=").append(cfg.getSchemaUrl());
    /* risultato: 'provider=Mondrian;DataSource=java:comp/env/jdbc/foodmart;
     *             Catalog="file:D:/Progetti/DEMO_SPAGOBI_20/Resources/Olap/FoodMart_RoleDSP.xml"Drink;
     *             DynamicSchemaProcessor=it.eng.spagobi.jpivotaddins.roles.SpagoBIFilterDynamicSchemaProcessor;UseSchemaPool=true;
     *             family=Drink'
     * */
    /*
    try {
     sb.append(";Catalog=").append(cfg.getSchemaUrl()+profile.getUserAttribute("family"));
    } catch (EMFInternalError e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }
     */
    if (cfg.getDynLocale() != null)
        sb.append(";Locale=").append(cfg.getDynLocale());

    // debug
    if (cfg.getRole() != null) {
        sb.append(";Role=").append(cfg.getRole());
    }
    if (cfg.getDataSourceChangeListener() != null) {
        sb.append(";dataSourceChangeListener=").append(cfg.getDataSourceChangeListener());
    }
    sb.append(";DynamicSchemaProcessor=it.eng.spagobi.jpivotaddins.roles.SpagoBIFilterDynamicSchemaProcessor");
    // cache control: if filtering by user profile attributes with queries inside schema definition, UseSchemaPool must be false
    //orig: sb.append(";UseSchemaPool=true");
    sb.append(";UseSchemaPool=true;UseContentChecksum=true");

    // there could be more than one attribute
    if (filers != null) {
        logger.debug("Data Access is ACTIVE!!!");
        try {
            InputStream is = new java.io.ByteArrayInputStream(filers.getBytes());
            org.dom4j.io.SAXReader reader = new org.dom4j.io.SAXReader();
            org.dom4j.Document document = reader.read(is);

            //org.dom4j.Node attribute = document.selectSingleNode("//DATA-ACCESS/ATTRIBUTE");
            List<Node> attributes = document.selectNodes("//DATA-ACCESS/ATTRIBUTE");
            if (attributes != null) {
                for (Iterator<Node> iterator = attributes.iterator(); iterator.hasNext();) {
                    Node attribute = iterator.next();
                    String attributeName = attribute.valueOf("@name");
                    if (attributeName != null) {
                        // if no value is found put null 
                        String value = profile.getUserAttribute(attributeName) != null
                                ? profile.getUserAttribute(attributeName).toString()
                                : null;
                        logger.debug("add profile attribute " + attributeName + " with value " + value);
                        // put attribute not with filter name but with attribute name!

                        // encoding value in Base64 
                        String valueBase64 = null;
                        if (value != null) {
                            try {
                                valueBase64 = ENCODER.encode(value.getBytes("UTF-8"));
                            } catch (UnsupportedEncodingException e) {
                                logger.error("UTF-8 encoding not supported!!!!!", e);
                                valueBase64 = ENCODER.encode(value.getBytes());
                            }
                        }
                        logger.debug("Attribute value in Base64 encoding is " + valueBase64);
                        sb.append(";" + attributeName + "=" + valueBase64);
                        //sb.append(";filter=" + profile.getUserAttribute(attributeName));

                    } else {
                        logger.warn("Filter attribute name not found!!");
                    }
                }
            } else {
                logger.warn("//DATA-ACCESS/ATTRIBUTE not found!!");
            }
        } catch (EMFInternalError e) {
            logger.error("", e);
        } catch (DocumentException e) {
            logger.error("", e);
        }
    }
    // sb.append(";Role=California manager");
    return sb.toString();
}

From source file:Controller.Controller.java

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException, SQLException, NoSuchAlgorithmException {
    response.setContentType("text/html;charset=UTF-8");

    FlightDAO otherDAO = new FlightDAO();
    ResultSet rs = null;//  w  w  w . j a va  2 s .  c  om
    String service = request.getParameter("service");
    if (service == null) {
        service = "-1";
    }
    final String userManager = "cp_user_manager.jsp?current_page=user_manager";

    RequestDispatcher rd;
    if (service.equalsIgnoreCase("add_new_location")) {
        String location = request.getParameter("location");
        try {
            SAXReader reader = new SAXReader();
            String webAppPath = getServletContext().getRealPath("/");
            Document document = reader.read(webAppPath + "/xml/Locations.xml");
            Element rootElement = document.getRootElement();
            Node node = document.selectSingleNode("/Locations/Location[not(../Location/LocationId > Id)]");
            String id = node.valueOf("LocationId");
            System.out.println(id);
        } catch (DocumentException ex) {
            System.out.println("Add New Location Failed!");
            Logger.getLogger(Controller.class.getName()).log(Level.SEVERE, null, ex);
        }
    } else if (service.equalsIgnoreCase("user_manager")) {
        rd = request.getRequestDispatcher(userManager);
        rd.forward(request, response);
        return;

    } else if (service.equalsIgnoreCase("login")) {
        String username1 = request.getParameter("username");
        String password1 = request.getParameter("password");
        SAXReader reader = new SAXReader();
        Document document;
        boolean found = false;
        String webAppPath = getServletContext().getRealPath("/");
        try {
            document = reader.read(webAppPath + "/xml/Customers.xml");
            Element root = document.getRootElement();
            for (Iterator i = root.elementIterator("Customer"); i.hasNext();) {
                Element elt = (Element) i.next();
                String username = elt.element("Name").getText();
                String password = elt.element("Password").getText();
                if (username.equalsIgnoreCase(username1) && password.equalsIgnoreCase(password1)) {
                    String role = elt.element("Role").getText();
                    String userid = elt.element("CustomerId").getText();
                    HttpSession session = request.getSession(true);
                    session.setAttribute("role", role);
                    session.setAttribute("username", username);
                    session.setAttribute("userid", userid);
                    rd = request.getRequestDispatcher("index.jsp");
                    rd.forward(request, response);
                    found = true;
                }
            }
            if (!found) {
                rd = request.getRequestDispatcher("login.jsp?errorCode=1");
                rd.forward(request, response);
            }
        } catch (DocumentException ex) {
            System.out.println("Login Failed!");
            Logger.getLogger(Controller.class.getName()).log(Level.SEVERE, null, ex);
        }

    } else if (service.equalsIgnoreCase("logout")) {
        String errorCode = "3";//(String) request.getParameter("errorCode");
        HttpSession session = request.getSession();
        if (session != null) {
            session.invalidate();
        }
        rd = request.getRequestDispatcher("login.jsp?errorCode=" + errorCode);
        rd.forward(request, response);

    } else {
        response.sendRedirect("notification.jsp?errorCode=2");
    }
}

From source file:cz.dasnet.dasik.plugin.URLInfo.java

License:Open Source License

@Override
public void onMessage(String channel, String sender, String login, String hostname, String message, Dasik bot) {
    Matcher m = youtube.matcher(message);
    String ytId = null;//from w ww  . j a  v  a 2  s  . com
    if (m.find()) {
        ytId = m.group(2);
    }
    if (ytId == null) {
        m = youtubeShort.matcher(message);
        if (m.find()) {
            ytId = m.group(2);
        }
    }
    if (ytId != null) {
        try {
            // pull info from youtube api
            org.dom4j.Document document = reader
                    .read(new URL("http://gdata.youtube.com/feeds/api/videos/" + ytId + "?v=2"));
            Node titleNode = document.selectSingleNode("//entry/media:group/media:title");
            Node descNode = document.selectSingleNode("//entry/media:group/media:description");
            Node statNode = document.selectSingleNode("//entry/yt:statistics");
            Node ratingNode = document.selectSingleNode("//entry/yt:rating");
            Node durNode = document.selectSingleNode("//entry/media:group/yt:duration");

            String title = decodeEntities(titleNode.getText());
            String desc = decodeEntities(descNode.getText());
            String views = statNode.valueOf("@viewCount");
            String likes = ratingNode.valueOf("@numLikes");
            String dislikes = ratingNode.valueOf("@numDislikes");
            String dur = durNode.valueOf("@seconds");

            bot.send(channel,
                    "Title: " + shorten(title, 200) + " [" + addMagSeparator(views, ",") + " views; Rating: "
                            + addMagSeparator(likes, ",") + "/" + addMagSeparator(dislikes, ",") + "; Length: "
                            + toMS(dur) + "]");
            //bot.send(channel, "Description: " + shorten(desc, 300));
        } catch (DocumentException ex) {
        } catch (MalformedURLException ex) {
        }
        return;
    }

    m = generalUrl.matcher(message);
    if (m.find()) {
        // general URL
        String mURL = m.group(1);
        if (!mURL.startsWith("http://")) {
            mURL = "http://" + mURL;
        }

        URLConnection httpConn = null;
        try {
            URL url = new URL(mURL);
            httpConn = url.openConnection();
            httpConn.setDoInput(true);
            httpConn.connect();
            String mime = httpConn.getContentType();

            if (mime.contains("text")) {
                org.jsoup.nodes.Document document = Jsoup.connect(url.toString()).get();
                String title = document.select("title").first().text();
                bot.send(channel, shorten("Title: " + title, 350) + " (at " + url.getHost() + ")");
            }
        } catch (IOException ex) {
            log.error("Error while downloading url: " + mURL, ex);
        } finally {
            if (httpConn != null) {
                try {
                    httpConn.getInputStream().close();
                } catch (IOException exx) {
                    log.error("Error closing connection to: " + mURL, exx);
                }
            }
        }
        return;
    }
}

From source file:cz.dasnet.dasik.plugin.WeatherService.java

License:Open Source License

@Override
public void onMessage(String channel, String sender, String login, String hostname, String message, Dasik bot) {
    String[] token = message.split("\\s+", 3);
    String command = bot.getCommand(message);
    if (command != null) {
        if ("addalias".equals(command) && token.length >= 3) {
            boolean save = false;
            String a = aliases.getProperty(token[1]);
            if (a == null) {
                aliases.put(token[1], token[2]);
                save = true;//  www .  j a  v  a 2 s . c om
            } else {
                User u = bot.getUserDao().find(login + "@" + hostname);
                if (u == null || u.getAccess() < 70) {
                    bot.send(channel, "You need at least level 70 access to overwrite this alias.");
                } else {
                    aliases.put(token[1], token[2]);
                    save = true;
                }
            }

            if (save) {
                FileWriter fw = null;
                try {
                    fw = new FileWriter("weather_aliases.properties");
                    aliases.store(fw, "");
                    bot.send(channel, "Alias added and saved");
                } catch (IOException ex) {
                } finally {
                    if (fw != null) {
                        try {
                            fw.close();
                        } catch (IOException ex) {
                        }
                    }
                }
            }
        }
        return;
    }

    token = message.split("\\s+", 2);

    if (".w".equals(token[0])) {
        String loc = "Brno";
        if (token.length >= 2) {
            loc = token[1];
        }

        if (expand(loc) != null) {
            loc = expand(loc);
        }

        try {
            Document document = reader
                    .read(new URL("http://www.google.com/ig/api?weather=" + URLEncoder.encode(loc, "UTF-8")));
            Node forecastInfo = document.selectSingleNode("//xml_api_reply/weather/forecast_information");
            Node current = document.selectSingleNode("//xml_api_reply/weather/current_conditions");

            String location = forecastInfo.valueOf("city/@data");
            String date = forecastInfo.valueOf("current_date_time/@data");

            String condition = current.valueOf("condition/@data");
            String temp = current.valueOf("temp_c/@data");
            String hum = current.valueOf("humidity/@data");
            String wind = current.valueOf("wind_condition/@data");
            Matcher m = Pattern.compile("(\\d.*?)\\s").matcher(wind);
            if (m.find()) {
                double ws = Integer.parseInt(m.group(1)) * 0.44704;
                wind += " (" + String.format("%.1f", ws) + " m/s)";
            }
            String out = "Location: " + location + " | Date: " + date + " | Condition: " + condition
                    + " | Temp: " + temp + " | " + hum + " | " + wind;
            bot.send(channel, out);

        } catch (UnsupportedEncodingException ex) {
        } catch (MalformedURLException ex) {
        } catch (DocumentException ex) {
        }
    }
}

From source file:data.IsbndbWS.java

@Override
public void parse(String tekst) throws Exception {
    try {//  w ww  .j a  v a 2 s .c o  m

        //List<Book> lista=new ArrayList<>();

        Document document = DocumentHelper.parseText(tekst);

        List list = document.selectNodes("//BookData");

        if (list == null || list.size() == 0) {
            System.out.println("Doslo do kraja");
            kraj = true;
        } else {
            System.out.println("ISBNDB, Trenutni broj strane " + trenutniBrojStrane);
            for (int i = 0; i < list.size(); i++) {
                Book b = new Book();
                b.setUri(URIGenerator.generateUri(b));
                Node node = (Node) list.get(i);
                b.setTitle(node.selectSingleNode("Title").getText());
                b.setIsbn(node.valueOf("@isbn13"));
                Person p = new Person();
                p.setUri(URIGenerator.generateUri(p));
                p.setName(node.selectSingleNode("AuthorsText").getText());
                b.getAuthors().add(p);
                Organization o = new Organization();
                o.setUri(URIGenerator.generateUri(o));
                o.setName(node.selectSingleNode("PublisherText").getText());
                b.setPublisher(o);

                lista.add(b);

            }

            trenutniBrojStrane++;
            //kraj=true;
        }

    } catch (Exception e) {
        e.printStackTrace();
        throw e;
    }
}

From source file:de.ingrid.portal.interfaces.impl.WMSInterfaceImpl.java

License:EUPL

/**
 * @see de.ingrid.portal.interfaces.WMSInterface#getWMSServices(java.lang.String)
 *//*from   w  w  w  .ja  va2s .  c  om*/
public Collection getWMSServices(String sessionID) {
    URL url;
    SAXReader reader = new SAXReader(false);
    ArrayList result = new ArrayList();

    try {

        // workaround for wrong dtd location

        EntityResolver resolver = new EntityResolver() {
            public InputSource resolveEntity(String publicId, String systemId) {
                if (systemId.indexOf("portalCommunication.dtd") > 0) {

                    InputStream in = getClass().getResourceAsStream("wms_interface.dtd");

                    return new InputSource(in);
                }
                return null;
            }
        };
        reader.setEntityResolver(resolver);

        // END workaround for wrong dtd location

        url = new URL(config
                .getString("interface_url", "http://localhost/mapbender/php/mod_portalCommunication_gt.php")
                .concat("?PREQUEST=getWMSServices").concat("&PHPSESSID=" + sessionID));

        reader.setValidation(false);
        Document document = reader.read(url);

        // check for valid server response
        if (document.selectSingleNode("//portal_communication") == null) {
            throw new Exception("WMS Server Response is not valid!");
        }
        // check for valid server response
        String error = document.valueOf("//portal_communication/error");
        if (error != null && error.length() > 0) {
            throw new Exception("WMS Server Error: " + error);
        }
        // get the wms services
        List nodes = document.selectNodes("//portal_communication/wms_services/wms");
        String serviceURL = null;
        for (Iterator i = nodes.iterator(); i.hasNext();) {
            Node node = (Node) i.next();
            serviceURL = node.valueOf("url");
            if (mapBenderVersion.equals(MAPBENDER_VERSION_2_1)) {
                serviceURL = serviceURL.replace(',', '&');
            }
            WMSServiceDescriptor wmsServiceDescriptor = new WMSServiceDescriptor(node.valueOf("name"),
                    serviceURL);
            result.add(wmsServiceDescriptor);
        }

        return result;

    } catch (Exception e) {
        log.error(e.toString());
    }

    return null;
}

From source file:de.tudarmstadt.ukp.dkpro.wsd.io.reader.MASCReader.java

License:Apache License

@SuppressWarnings("unchecked")
private HashSet<String> resolveIAA(List<Node> senseNodes, String id) {
    HashSet<String> senseSet = new HashSet<String>();
    List<String> senseList = new ArrayList<String>(senseNodes.size());
    for (Node node : senseNodes) {
        String sense = node.valueOf("@" + ATTR_VALUE);
        senseSet.add(sense);/*from   ww w  .  j a v  a  2  s  . c om*/

        Element e = (Element) node;
        Element parent = e.getParent();
        List<Element> children = parent.elements();
        sense += "#" + children.get(1).attributeValue(ATTR_VALUE);
        senseList.add(sense);
    }
    targetItems2senses.put(id, senseList);

    if (interannotatorAgreement.equals("first_sense")) {
        senseSet.clear();
        String firstSense = senseNodes.get(0).valueOf("@" + ATTR_VALUE);
        senseSet.add(firstSense);
        return senseSet;
    }

    // all annotators agree on a single sense or the user want all senses
    // back
    if (senseSet.size() == 1 || interannotatorAgreement.equals("all_senses")) {
        return senseSet;
    }

    senseSet.clear();

    if (interannotatorAgreement.equals("majority_vote")) {
        HashMap<String, Integer> senseFreq = new HashMap<String, Integer>();
        for (Node node : senseNodes) {
            String nextSense = node.valueOf("@" + ATTR_VALUE);
            Integer count = senseFreq.get(nextSense);
            senseFreq.put(nextSense, count == null ? 1 : count + 1);
        }

        List<Integer> values = new ArrayList<Integer>(senseFreq.values());
        Collections.sort(values); // sort in ascending order
        int max = values.get(values.size() - 1);
        int second = values.get(values.size() - 2);

        // there is a tie
        if (max == second && ignoreTies) {
            return null;
        } else {
            for (String key : senseFreq.keySet()) {
                int count = senseFreq.get(key);
                if (count == max) {
                    senseSet.add(key);
                    return senseSet;
                }
            }
        }
    } else if (interannotatorAgreement.matches(".*\\d+")) {
        for (Node node : senseNodes) {
            String sense = node.valueOf("@" + ATTR_VALUE);
            Element e = (Element) node;
            Element parent = e.getParent();
            List<Element> children = parent.elements();
            for (Element child : children) {
                if (child.attributeValue(ATTR_VALUE).equals(interannotatorAgreement)) {
                    senseSet.add(sense);
                    return senseSet;
                }
            }
        }
    }

    return senseSet;
}

From source file:dkpro.similarity.algorithms.sound.dict.PLS.java

License:Apache License

/**
 *
 * @param dictionaryFilename/*from  ww w.  j ava  2s  .c o  m*/
 *            The filename of the PLS dictionary to read in.
 * @throws DocumentException
 */
@SuppressWarnings("unchecked")
public PLS(String dictionaryFilename) throws DocumentException {
    SAXReader reader = new SAXReader();
    Document document = reader.read(dictionaryFilename);
    dict = new MultiValueMap();

    // Get dictionary alphabet and language
    Element lexicon = document.getRootElement();
    alphabetId = lexicon.attributeValue("alphabet");
    dictionaryLanguage = lexicon.attributeValue("lang");

    // Extract dictionary name from metadata
    Map<String, String> namespaceMap = new HashMap<String, String>();
    namespaceMap.put("rdf", "http://www.w3.org/1999/02/22-rdf-syntax-ns#");
    namespaceMap.put("dc", "http://purl.org/dc/elements/1.1/");
    XPath xpath = document.createXPath("//rdf:Description");
    xpath.setNamespaceURIs(namespaceMap);
    Node node = xpath.selectSingleNode(lexicon);
    if (node != null) {
        dictionaryId = node.valueOf("@dc:title");
    } else {
        dictionaryId = "";
    }

    for (Iterator<Element> lexemeIterator = lexicon.elementIterator("lexeme"); lexemeIterator.hasNext();) {
        Element lexeme = lexemeIterator.next();
        List<Element> graphemes = lexeme.selectNodes("grapheme");
        List<Element> phonemes = lexeme.selectNodes("phoneme");
        for (Element grapheme : graphemes) {
            for (Element phoneme : phonemes) {
                dict.put(grapheme.getText(), phoneme.getText());
            }
        }
    }
}