Example usage for java.lang String hashCode

List of usage examples for java.lang String hashCode

Introduction

In this page you can find the example usage for java.lang String hashCode.

Prototype

public int hashCode() 

Source Link

Document

Returns a hash code for this string.

Usage

From source file:lv.semti.morphology.analyzer.Word.java

@Override
    public int hashCode() {
        //return 0;
        String signature = "1117 " + token + " " + wordforms;
        // TODO: Ilmaar, paskaties.
        // It's a kind of magic: adding the lower one makes Word-s unfindable in 
        // LinkedHashMap, even there exists an key to which .equals gives true
        // and .hashCode gives the same value as for the searched object. 
        //      signature = signature + " " + correctWordform + " ";
        return signature.hashCode();
    }/*  www. j  a  va2 s.c o  m*/

From source file:edu.stanford.mobisocial.dungbeetle.feed.objects.AppStateObj.java

public void render(final Context context, final ViewGroup frame, Obj obj, boolean allowInteractions) {
    JSONObject content = obj.getJson();//from   w w  w  .  j  av  a 2s .c  o m
    // TODO: hack to show object history in app feeds
    JSONObject appState = getAppState(context, content);
    if (appState != null) {
        content = appState;
    } else {
        Log.e(TAG, "Missing inner content, probably because of format changes");
    }

    boolean rendered = false;
    AppState ref = new AppState(content);
    String thumbnail = ref.getThumbnailImage();
    if (thumbnail != null) {
        rendered = true;
        ImageView imageView = new ImageView(context);
        imageView.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,
                LinearLayout.LayoutParams.WRAP_CONTENT));
        App.instance().objectImages.lazyLoadImage(thumbnail.hashCode(), thumbnail, imageView);
        frame.addView(imageView);
    }

    thumbnail = ref.getThumbnailText();
    if (thumbnail != null) {
        rendered = true;
        TextView valueTV = new TextView(context);
        valueTV.setText(thumbnail);
        valueTV.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,
                LinearLayout.LayoutParams.WRAP_CONTENT));
        valueTV.setGravity(Gravity.TOP | Gravity.LEFT);
        frame.addView(valueTV);
    }

    thumbnail = ref.getThumbnailHtml();
    if (thumbnail != null) {
        rendered = true;
        WebView webview = new WebView(context);
        webview.loadData(thumbnail, "text/html", "UTF-8");
        webview.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,
                LinearLayout.LayoutParams.WRAP_CONTENT));
        Object o = frame.getTag(R.id.object_entry);
        webview.setOnTouchListener(new WebViewClickListener(frame, (Integer) o));
        frame.addView(webview);
    }

    if (!rendered) {
        String appName = content.optString(PACKAGE_NAME);
        if (appName.contains(".")) {
            appName = appName.substring(appName.lastIndexOf(".") + 1);
        }
        String text = "Welcome to " + appName + "!";
        TextView valueTV = new TextView(context);
        valueTV.setText(text);
        valueTV.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,
                LinearLayout.LayoutParams.WRAP_CONTENT));
        valueTV.setGravity(Gravity.TOP | Gravity.LEFT);
        frame.addView(valueTV);
    }
}

From source file:org.loklak.geo.GeoNames.java

public GeoNames(final File cities1000_zip, final File iso3166json, long minPopulation) throws IOException {

    // load iso3166 info
    this.iso3166toCountry = new HashMap<>();
    try {//from   ww  w .  jav a  2 s .  co m
        //String jsonString = new String(Files.readAllBytes(iso3166json.toPath()), StandardCharsets.UTF_8);
        ObjectMapper jsonMapper = new ObjectMapper(DAO.jsonFactory);
        JsonNode j = jsonMapper.readTree(iso3166json);
        for (JsonNode n : j) {
            // contains name,alpha-2,alpha-3,country-code,iso_3166-2,region-code,sub-region-code
            String name = n.get("name").textValue();
            String cc = n.get("alpha-2").textValue();
            this.iso3166toCountry.put(cc, name);
        }
    } catch (IOException e) {
        this.iso3166toCountry = new HashMap<String, String>();
    }

    // this is a processing of the cities1000.zip file from http://download.geonames.org/export/dump/

    this.id2loc = new HashMap<>();
    this.hash2ids = new HashMap<>();
    this.stopwordHashes = new HashSet<>();
    this.countryCenter = new HashMap<>();
    Map<String, CountryBounds> countryBounds = new HashMap<>();

    if (cities1000_zip == null || !cities1000_zip.exists()) {
        throw new IOException("GeoNames: file does not exist!");
    }
    ZipFile zf = null;
    BufferedReader reader = null;
    try {
        zf = new ZipFile(cities1000_zip);
        String entryName = cities1000_zip.getName();
        entryName = entryName.substring(0, entryName.length() - 3) + "txt";
        final ZipEntry ze = zf.getEntry(entryName);
        final InputStream is = zf.getInputStream(ze);
        reader = new BufferedReader(new InputStreamReader(is, StandardCharsets.UTF_8));
    } catch (final IOException e) {
        throw new IOException("GeoNames: Error when decompressing cities1000.zip!", e);
    }

    /* parse this fields:
    ---------------------------------------------------
    00 geonameid         : integer id of record in geonames database
    01 name              : name of geographical point (utf8) varchar(200)
    02 asciiname         : name of geographical point in plain ascii characters, varchar(200)
    03 alternatenames    : alternatenames, comma separated varchar(5000)
    04 latitude          : latitude in decimal degrees (wgs84)
    05 longitude         : longitude in decimal degrees (wgs84)
    06 feature class     : see http://www.geonames.org/export/codes.html, char(1)
    07 feature code      : see http://www.geonames.org/export/codes.html, varchar(10)
    08 country code      : ISO-3166 2-letter country code, 2 characters
    09 cc2               : alternate country codes, comma separated, ISO-3166 2-letter country code, 60 characters
    10 admin1 code       : fipscode (subject to change to iso code), see exceptions below, see file admin1Codes.txt for display names of this code; varchar(20)
    11 admin2 code       : code for the second administrative division, a county in the US, see file admin2Codes.txt; varchar(80)
    12 admin3 code       : code for third level administrative division, varchar(20)
    13 admin4 code       : code for fourth level administrative division, varchar(20)
    14 population        : bigint (8 byte int)
    15 elevation         : in meters, integer
    16 dem               : digital elevation model, srtm3 or gtopo30, average elevation of 3''x3'' (ca 90mx90m) or 30''x30'' (ca 900mx900m) area in meters, integer. srtm processed by cgiar/ciat.
    17 timezone          : the timezone id (see file timeZone.txt) varchar(40)
    18 modification date : date of last modification in yyyy-MM-dd format
    */
    try {
        String line;
        String[] fields;
        while ((line = reader.readLine()) != null) {
            if (line.isEmpty()) {
                continue;
            }
            fields = CommonPattern.TAB.split(line);
            final long population = Long.parseLong(fields[14]);
            if (minPopulation > 0 && population < minPopulation)
                continue;
            final int geonameid = Integer.parseInt(fields[0]);
            Set<String> locnames = new LinkedHashSet<>();
            locnames.add(fields[1]);
            locnames.add(fields[2]);
            for (final String s : CommonPattern.COMMA.split(fields[3]))
                locnames.add(s);
            ArrayList<String> locnamess = new ArrayList<>(locnames.size());
            locnamess.addAll(locnames);
            String cc = fields[8]; //ISO-3166

            final GeoLocation geoLocation = new GeoLocation(Float.parseFloat(fields[4]),
                    Float.parseFloat(fields[5]), locnamess, cc);
            geoLocation.setPopulation(population);
            this.id2loc.put(geonameid, geoLocation);
            for (final String name : locnames) {
                if (name.length() < 4)
                    continue;
                String normalized = normalize(name);
                int lochash = normalized.hashCode();
                List<Integer> locs = this.hash2ids.get(lochash);
                if (locs == null) {
                    locs = new ArrayList<Integer>(1);
                    this.hash2ids.put(lochash, locs);
                }
                if (!locs.contains(geonameid))
                    locs.add(geonameid);
            }

            // update the country bounds
            CountryBounds bounds = countryBounds.get(cc);
            if (bounds == null) {
                bounds = new CountryBounds();
                countryBounds.put(cc, bounds);
            }
            bounds.extend(geoLocation);
        }
        if (reader != null)
            reader.close();
        if (zf != null)
            zf.close();
    } catch (final IOException e) {
    }

    // calculate the center of the countries
    for (Map.Entry<String, CountryBounds> country : countryBounds.entrySet()) {
        this.countryCenter.put(country.getKey(),
                new double[] { (country.getValue().lon_west - country.getValue().lon_east) / 2.0,
                        (country.getValue().lat_north - country.getValue().lat_south) / 2.0 }); // [longitude, latitude]
    }

    // finally create a statistic which names appear very often to have fill-word heuristic
    TreeMap<Integer, Set<Integer>> stat = new TreeMap<>(); // a mapping from number of occurrences of location name hashes to a set of location name hashes
    for (Map.Entry<Integer, List<Integer>> entry : this.hash2ids.entrySet()) {
        int occurrences = entry.getValue().size();
        Set<Integer> hashes = stat.get(occurrences);
        if (hashes == null) {
            hashes = new HashSet<Integer>();
            stat.put(occurrences, hashes);
        }
        hashes.add(entry.getKey());
    }
    // we consider 3/4 of this list as fill-word (approx 300): those with the most occurrences
    int good = stat.size() / 4;
    Iterator<Map.Entry<Integer, Set<Integer>>> i = stat.entrySet().iterator();
    for (int j = 0; j < good; j++)
        i.next(); // 'eat away' the good entries.
    while (i.hasNext()) {
        Set<Integer> morehashes = i.next().getValue();
        this.stopwordHashes.addAll(morehashes);
    }
}

From source file:com.opengamma.masterdb.security.hibernate.option.FXBarrierOptionSecurityBean.java

@Override
protected Object propertyGet(String propertyName, boolean quiet) {
    switch (propertyName.hashCode()) {
    case -984864697: // putAmount
        return getPutAmount();
    case 1066661974: // callAmount
        return getCallAmount();
    case -1289159373: // expiry
        return getExpiry();
    case 516393024: // putCurrency
        return getPutCurrency();
    case 643534991: // callCurrency
        return getCallCurrency();
    case -295948169: // settlementDate
        return getSettlementDate();
    case 1029043089: // barrierType
        return getBarrierType();
    case 502579592: // barrierDirection
        return getBarrierDirection();
    case -1483652190: // monitoringType
        return getMonitoringType();
    case 1178782005: // samplingFrequency
        return getSamplingFrequency();
    case 1827586573: // barrierLevel
        return getBarrierLevel();
    case 116685664: // longShort
        return isLongShort();
    }/*from   w  w w .  ja va  2  s  .c  o  m*/
    return super.propertyGet(propertyName, quiet);
}

From source file:it.unipi.di.acube.batframework.systemPlugins.ERDSystem.java

@Override
public HashSet<Tag> solveC2W(String text) throws AnnotationException {
    lastTime = Calendar.getInstance().getTimeInMillis();
    HashSet<Tag> res = new HashSet<Tag>();
    try {//from  w  w  w.  j ava2s .  c o m
        URL erdApi = new URL(url);

        HttpURLConnection connection = (HttpURLConnection) erdApi.openConnection();
        connection.setDoOutput(true);
        connection.setRequestMethod("POST");

        MultipartEntity multipartEntity = new MultipartEntity(HttpMultipartMode.STRICT);
        multipartEntity.addPart("runID", new StringBody(this.run));
        multipartEntity.addPart("TextID", new StringBody("" + text.hashCode()));
        multipartEntity.addPart("Text", new StringBody(text));

        connection.setRequestProperty("Content-Type", multipartEntity.getContentType().getValue());
        OutputStream out = connection.getOutputStream();
        try {
            multipartEntity.writeTo(out);
        } finally {
            out.close();
        }

        int status = ((HttpURLConnection) connection).getResponseCode();
        if (status != 200) {
            BufferedReader br = new BufferedReader(new InputStreamReader(connection.getErrorStream()));
            String line = null;
            while ((line = br.readLine()) != null)
                System.err.println(line);
            throw new RuntimeException();
        }

        BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        String line = null;
        while ((line = br.readLine()) != null) {
            String mid = line.split("\t")[2];
            String title = freebApi.midToTitle(mid);
            int wid;
            if (title == null || (wid = wikiApi.getIdByTitle(title)) == -1)
                System.err.println("Discarding mid=" + mid);
            else
                res.add(new Tag(wid));
        }

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

    lastTime = Calendar.getInstance().getTimeInMillis() - lastTime;
    return res;
}

From source file:au.edu.unsw.soacourse.controller.CompanyController.java

@RequestMapping(value = "/processCompanyLogin")
public String processCompanyLogin(ModelMap model, HttpServletRequest req) throws Exception {
    //login details
    String email = req.getParameter("email");
    String password = req.getParameter("password");

    RegisteredUsersDao dao = new RegisteredUsersDao();
    dao.getRegisteredUsers();/*from  www .  j  av  a 2s .co m*/
    RegisteredUser user = dao.getUser(email, password);

    if (user != null && !user.getRole().equalsIgnoreCase("app-candidate")) {
        req.getSession().setAttribute("user", user);
        String role = user.getRole();
        req.getSession().setAttribute("companyid", Math.abs(email.hashCode()));
        req.getSession().setAttribute("role", role);

        String queryString = "/company/" + Math.abs(email.hashCode());
        WebClient client = WebClient.create(REST_URI + queryString);
        System.out.println(REST_URI + queryString);

        client.header("SecurityKey", SECURITY_KEY);
        client.header("ShortKey", role);
        client.accept(MediaType.APPLICATION_JSON);

        Response response = client.get();
        ObjectMapper mapper = new ObjectMapper();
        JsonNode node = mapper.readTree(response.readEntity(String.class));

        Company c = new Company();

        c.setEmail(node.get("email").getTextValue());
        c.setEmployees(node.get("employees").getTextValue());
        c.setIndustry(node.get("industry").getTextValue());
        c.setLocation(node.get("location").getTextValue());
        c.setName(node.get("name").getTextValue());
        c.setPassword(node.get("password").getTextValue());
        c.setProfileId(node.get("profileId").getIntValue());

        req.getSession().setAttribute("company", c);

        return "companyHome";

    } else {
        model.addAttribute("loginfail", 1);
    }

    return "companyLogin";
}

From source file:ch.rgw.tools.StringTool.java

/**
 * Gibt eine zufllige und eindeutige Zeichenfolge zurck
 * /*from w  w w .  j a  va2s.c o  m*/
 * @param salt
 *            Ein beliebiger String oder null
 */
public static String unique(final String salt) {
    if (ipHash == 0) {
        Iterator<String> it = NetTool.IPs.iterator();
        while (it.hasNext()) {
            ipHash += (it.next()).hashCode();
        }
    }

    long t = System.currentTimeMillis();
    int t1 = System.getProperty("user.name").hashCode();
    long t2 = ((long) ipHash) << 32;
    long t3 = Math.round(Math.random() * Long.MAX_VALUE);
    long t4 = t + t1 + t2 + t3;
    if (salt != null) {
        long t0 = salt.hashCode();
        t4 ^= t0;
    }
    t4 += sequence++;
    if (sequence > 99999) {
        sequence = 0;
    }
    long idx = sequence % salties.length;
    char start = salties[(int) idx];
    return new StringBuilder().append(start).append(Long.toHexString(t4))
            .append(Long.toHexString((long) Math.random() * 1000)).append(sequence).toString();
}

From source file:eu.musesproject.windowsclient.usercontexteventhandler.UserContextEventHandler.java

/**
 * Info SS//w w w . j a  va2s  .c  o  m
 *
 * Method to send a request to the server
 *
 * @param requestJSON {@link JSONObject}
 */
public void sendRequestToServer(JSONObject requestJSON) {
    if (requestJSON != null && !requestJSON.toString().isEmpty()) {
        if (serverStatus == Statuses.ONLINE) {
            logger.debug("send request to server: " + requestJSON.toString());
            String sendData = requestJSON.toString();

            int jsonRequestID = sendData.hashCode();
            pendingJSONRequest.put(jsonRequestID, requestJSON);
            connectionManager.sendData(sendData, jsonRequestID);
        }
    }
}

From source file:com.buaa.cfs.security.ShellBasedIdMapping.java

public int getUidAllowingUnknown(String user) {
    checkAndUpdateMaps();/*from  w w w  .  j a  v a 2  s .com*/
    int uid;
    try {
        uid = getUid(user);
    } catch (IOException e) {
        uid = user.hashCode();
        LOG.info("Can't map user " + user + ". Use its string hashcode:" + uid);
    }
    return uid;
}

From source file:com.buaa.cfs.security.ShellBasedIdMapping.java

public int getGidAllowingUnknown(String group) {
    checkAndUpdateMaps();/*from   www .j  ava  2s  .  com*/
    int gid;
    try {
        gid = getGid(group);
    } catch (IOException e) {
        gid = group.hashCode();
        LOG.info("Can't map group " + group + ". Use its string hashcode:" + gid);
    }
    return gid;
}