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:edu.umass.cs.gigapaxos.PaxosInstanceStateMachine.java

protected static int roundRobinCoordinator(String paxosID, int[] members, int ballotnum) {
    // to load balance coordinatorship across groups
    int randomOffset = paxosID.hashCode();
    return members[(Math.abs(ballotnum + randomOffset)) % members.length];
}

From source file:com.chinamobile.bcbsp.comm.MessageQueuesForDisk.java

@Override
public int getIncomingQueueSize(String dstVertexID) {
    ConcurrentLinkedQueue<IMessage> incomingQueue = null;
    // Get the hash bucket index.
    int hashCode = dstVertexID.hashCode();
    int hashIndex = hashCode % this.hashBucketNumber; // bucket index
    hashIndex = (hashIndex < 0 ? hashIndex + this.hashBucketNumber : hashIndex);
    BucketMeta meta = this.incomingQueues.get(hashIndex);
    incomingQueue = meta.queueMap.get(dstVertexID);
    if (incomingQueue != null) {
        return incomingQueue.size();
    } else {//from   w  w w  .java 2  s  . c om
        return 0;
    }
}

From source file:com.chinamobile.bcbsp.comm.MessageQueuesForDisk.java

@Override
public ConcurrentLinkedQueue<IMessage> removeIncomingQueue(String dstVerID) {
    ConcurrentLinkedQueue<IMessage> incomingQueue = null;
    // Get the hash bucket index.
    int hashCode = dstVerID.hashCode();
    int hashIndex = hashCode % this.hashBucketNumber; // bucket index
    hashIndex = (hashIndex < 0 ? hashIndex + this.hashBucketNumber : hashIndex);
    BucketMeta meta = this.incomingQueues.get(hashIndex);
    // The bucket is on disk.
    if (meta.onDiskFlag) {
        this.incomingFileLocks[hashIndex].lock();
        /** Lock */
        try {/*w  w w  .j av  a  2 s  .  c o m*/
            loadBucket(this.incomingQueues, hashIndex, "incoming");
        } catch (IOException e) {
            throw new RuntimeException("[MessageQueuesForDisk:removeIncomingQueue]", e);
        } finally {
            this.incomingFileLocks[hashIndex].unlock();
            /** Unlock */
        }
    }
    meta = this.incomingQueues.get(hashIndex);
    incomingQueue = meta.queueMap.remove(dstVerID);
    if (incomingQueue == null) {
        incomingQueue = new ConcurrentLinkedQueue<IMessage>();
    }
    int removedCount = incomingQueue.size();
    long removedLength = removedCount * this.sizeOfMessage;
    // Update the meta data.
    meta.count = meta.count - removedCount;
    meta.countInMemory = meta.countInMemory - removedCount;
    meta.length = meta.length - removedLength;
    meta.lengthInMemory = meta.lengthInMemory - removedLength;
    this.sizeOfMessagesDataInMem = this.sizeOfMessagesDataInMem - removedLength;
    this.countOfMessagesDataInMem = this.countOfMessagesDataInMem - removedCount;
    this.sizeOfHashMapsInMem = this.sizeOfHashMapsInMem
            - (sizeOfRef * 2 + (dstVerID.length() * sizeOfChar) + sizeOfEmptyMessageQueue);
    return incomingQueue;
}

From source file:com.chinamobile.bcbsp.comm.MessageQueuesForDisk.java

@Override
@SuppressWarnings("unchecked")
public ConcurrentLinkedQueue<IMessage> removeIncomedQueue(String dstVertID) {
    ConcurrentLinkedQueue<IMessage> incomedQueue = null;
    // Get the hash bucket index.
    int hashCode = dstVertID.hashCode();
    int hashIndex = hashCode % this.hashBucketNumber; // bucket index
    hashIndex = (hashIndex < 0 ? hashIndex + this.hashBucketNumber : hashIndex);
    BucketMeta meta = this.incomedQueues.get(hashIndex);
    // The bucket is on disk.
    if (meta.onDiskFlag) {
        this.incomedFileLocks[hashIndex].lock();
        /** Lock */
        try {/*from   w ww.j a v a2s.c  o m*/
            loadBucket(this.incomedQueues, hashIndex, "incomed");
        } catch (IOException e) {
            LOG.info("==> bucket-" + hashIndex + ", VertexID = " + dstVertID);
            LOG.info("size = " + meta.queueMap.get(dstVertID).size());
            throw new RuntimeException("==> bucket-" + hashIndex + ", VertexID = " + dstVertID, e);
        } finally {
            this.incomedFileLocks[hashIndex].unlock();
            /** Unlock */
        }
    }
    meta = this.incomedQueues.get(hashIndex);
    this.currentBucket = hashIndex;
    incomedQueue = meta.queueMap.remove(dstVertID);
    if (incomedQueue == null) {
        incomedQueue = new ConcurrentLinkedQueue<IMessage>();
    }
    int removedCount = incomedQueue.size();
    long removedLength = removedCount * this.sizeOfMessage;
    // Update the meta data.
    meta.count = meta.count - removedCount;
    meta.countInMemory = meta.countInMemory - removedCount;
    meta.length = meta.length - removedLength;
    meta.lengthInMemory = meta.lengthInMemory - removedLength;
    this.sizeOfMessagesDataInMem = this.sizeOfMessagesDataInMem - removedLength;
    this.countOfMessagesDataInMem = this.countOfMessagesDataInMem - removedCount;
    this.sizeOfHashMapsInMem = this.sizeOfHashMapsInMem
            - (sizeOfRef * 2 + (dstVertID.length() * sizeOfChar) + sizeOfEmptyMessageQueue);
    return incomedQueue;
}

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

@RequestMapping(value = "/companyRegister")
public String registerCompany(ModelMap model, HttpServletRequest req) throws Exception {
    // company details //TODO
    String name = req.getParameter("name");
    String industry = req.getParameter("industry");
    String employees = req.getParameter("employees");
    String location = req.getParameter("location");

    //manager details
    String firstname = req.getParameter("firstname");
    String lastname = req.getParameter("lastname");
    String manageremail = req.getParameter("email");
    String password = req.getParameter("password");
    String role = "app-manager";

    if (manageremail == null || manageremail.isEmpty() || password == null || password.isEmpty()
            || firstname == null || firstname.isEmpty() || lastname == null || lastname.isEmpty()
            || name == null || name.isEmpty() || industry == null || industry.isEmpty() || employees == null
            || employees.isEmpty() || location == null || location.isEmpty()) {
        model.addAttribute("emptyparam", 1);
        return "companyRegisterForm";
    }//www .jav  a2s  .c o  m

    RegisteredUsersDao dao = new RegisteredUsersDao();
    RegisteredUsers users = dao.getRegisteredUsers();
    dao.getRegisteredUsers();

    if (!dao.isUserRegistered(manageremail)) {
        RegisteredUser newUser = new RegisteredUser(manageremail, password, "manager");
        users.addUser(newUser);
        dao.setRegisteredUsers(users);

        req.getSession().setAttribute("companyid", Math.abs(manageremail.hashCode()));
        req.getSession().setAttribute("role", role);

        String queryString = "/company";
        WebClient client = WebClient.create(REST_URI + queryString);
        System.out.println("create company: " + REST_URI + queryString);

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

        Form form = new Form();
        form.param("email", manageremail);
        form.param("name", name);
        form.param("industry", industry);
        form.param("employees", employees);
        form.param("location", location);
        client.post(form);

        WebClient userclient = WebClient.create(REST_URI + "/user");
        System.out.println("create user: " + REST_URI + "/user");

        userclient.header("SecurityKey", SECURITY_KEY);
        userclient.header("ShortKey", role);

        Form userform = new Form();
        userform.param("email", manageremail);
        userform.param("password", password);
        userform.param("firstname", firstname);
        userform.param("lastname", lastname);
        userclient.post(userform);

        return processCompanyLogin(model, req);
    } else {
        model.addAttribute("userexist", 1);
        return "registerForm";
    }
}

From source file:com.strider.datadefender.functions.CoreFunctions.java

/**
 * Sets up a map, mapping a list of values to a list of shuffled values.
 * /*from   w  w  w  .j  a  v  a  2 s.  c  om*/
 * If the value is not mapped, the function guarantees returning the same
 * randomized value for a given column value - however it does not guarantee
 * that more than one column value do not have the same randomized value.
 * 
 * @param params
 * @return 
 */
private String getPredictableShuffledValueFor(final String name, final String value) {
    if (!predictableShuffle.containsKey(name)) {
        final List<String> list = stringLists.get(name);
        final List<String> shuffled = new ArrayList<>(list);
        Collections.shuffle(shuffled);

        final Map<String, String> smap = new HashMap<>();
        final Iterator<String> lit = list.iterator();
        final Iterator<String> sit = shuffled.iterator();
        while (lit.hasNext()) {
            smap.put(lit.next(), sit.next());
        }
        predictableShuffle.put(name, smap);
    }

    final Map<String, String> map = predictableShuffle.get(name);
    if (!map.containsKey(value)) {
        final String[] vals = map.values().toArray(new String[map.size()]);
        final int index = (int) Math.abs((long) value.hashCode()) % vals.length;
        return vals[index];
    }
    return map.get(value);
}

From source file:com.ning.maven.plugins.duplicatefinder.DuplicateFinderMojo.java

/**
 * Calculates the SHA256 Hash of a class in a file.
 * //from   w w  w . ja  v  a 2 s. c  o  m
 * @param file the archive contains the class
 * @param resourcePath the name of the class
 * @return the MD% Hash as Hex-Value
 * @throws IOException if any error occurs on reading class in archive
 */
private String getSHA256HexOfElement(final File file, final String resourcePath) throws IOException {
    class Sha256CacheKey {
        final File file;
        final String resourcePath;

        Sha256CacheKey(File file, String resourcePath) {
            this.file = file;
            this.resourcePath = resourcePath;
        }

        public boolean equals(Object o) {
            if (this == o)
                return true;
            if (o == null || getClass() != o.getClass())
                return false;

            Sha256CacheKey key = (Sha256CacheKey) o;

            return file.equals(key.file) && resourcePath.equals(key.resourcePath);
        }

        public int hashCode() {
            return 31 * file.hashCode() + resourcePath.hashCode();
        }
    }

    final Sha256CacheKey key = new Sha256CacheKey(file, resourcePath);
    if (CACHED_SHA256.containsKey(key)) {
        return (String) CACHED_SHA256.get(key);
    }

    ZipFile zip = new ZipFile(file);
    ZipEntry zipEntry = zip.getEntry(resourcePath);
    if (zipEntry == null) {
        throw new IOException("Could not found Zip-Entry for " + resourcePath + " in file " + file);
    }

    String sha256;

    InputStream in = zip.getInputStream(zipEntry);
    try {
        sha256 = DigestUtils.sha256Hex(in);
    } finally {
        IOUtils.closeQuietly(in);
    }

    CACHED_SHA256.put(key, sha256);

    return sha256;
}

From source file:fusion.Fusion.java

private static void getINASameAsLinks(File file) throws FileNotFoundException, IOException, URISyntaxException {
    try (BufferedReader br = new BufferedReader(new FileReader(file))) {
        StringBuilder sb = new StringBuilder();
        String line = br.readLine();

        while (line != null) {
            if (line.contains("owl:sameAs")) {
                sb.append(line);/*from  w w  w  .  j  a va 2s  .  com*/
                sb.append(System.lineSeparator());
            }
            line = br.readLine();

        }
        String linksString = sb.toString();
        String[] linksArray = linksString.split("\n");

        for (int i = 0; i < linksArray.length; i++) {

            String value1 = linksArray[i].substring(0, linksArray[i].indexOf(" owl:sameAs"));
            String value2 = linksArray[i].substring(linksArray[i].lastIndexOf("owl:sameAs ") + 11,
                    linksArray[i].length() - 1);

            value1 = StringUtils.removeStart(value1, "<");
            value2 = StringUtils.removeStart(value2, "<");
            value1 = StringUtils.removeStart(value1, "http://www.ina.fr/thesaurus/pp/");
            value2 = StringUtils.removeStart(value2, "http://www.ina.fr/thesaurus/pp/");
            value1 = StringUtils.removeStart(value1, "http://fr.dbpedia.org/resource/"); //
            value2 = StringUtils.removeStart(value2, "http://fr.dbpedia.org/resource/"); //
            value1 = StringUtils.removeEnd(value1, ".");
            value2 = StringUtils.removeEnd(value2, ".");
            value1 = StringUtils.removeEnd(value1, ">");
            value2 = StringUtils.removeEnd(value2, ">");

            if (!distinctURLs.containsKey(value1.hashCode()))
                distinctURLs.put(value1.hashCode(), new URI(value1));
            if (!distinctURLs.containsKey(value2.hashCode()))
                distinctURLs.put(value2.hashCode(), new URI(value2));

            links.add(new SameAsLink(distinctURLs.get(value1.hashCode()), distinctURLs.get(value2.hashCode()))); // adding same as links
        }

        for (Integer name : distinctURLs.keySet()) {
            Instance instance = new Instance(distinctURLs.get(name), null);
            if (distinctURLs.get(name).toString().contains("dbpedia"))
                instance.setSource(sources.get("fr.dbpedia.org"));

            else
                instance.setSource(sources.get("www.ina.fr"));
            instances.put(instance.getUri(), instance);
        }
    }
}

From source file:it.eng.spagobi.tools.scheduler.jobs.CopyOfExecuteBIDocumentJob.java

private void saveAsDocument(DispatchContext sInfo, BIObject biobj, JobExecutionContext jex, byte[] response,
        String fileExt, IDataStore dataStore, String toBeAppendedToName, String toBeAppendedToDescription) {
    logger.debug("IN");
    try {//from www.jav a2s . co m
        String docName = sInfo.getDocumentName();
        if ((docName == null) || docName.trim().equals("")) {
            throw new Exception(" Document name not specified");
        }
        docName += toBeAppendedToName;
        String docDesc = sInfo.getDocumentDescription() + toBeAppendedToDescription;

        // recover office document sbidomains
        IDomainDAO domainDAO = DAOFactory.getDomainDAO();
        Domain officeDocDom = domainDAO.loadDomainByCodeAndValue("BIOBJ_TYPE", "OFFICE_DOC");
        // recover development sbidomains
        Domain relDom = domainDAO.loadDomainByCodeAndValue("STATE", "REL");
        // recover engine
        IEngineDAO engineDAO = DAOFactory.getEngineDAO();
        List engines = engineDAO.loadAllEnginesForBIObjectType(officeDocDom.getValueCd());
        if (engines.isEmpty()) {
            throw new Exception(" No suitable engines for the new document");
        }
        Engine engine = (Engine) engines.get(0);
        // load the template
        ObjTemplate objTemp = new ObjTemplate();
        objTemp.setActive(new Boolean(true));
        objTemp.setContent(response);
        objTemp.setName(docName + fileExt);
        // load all functionality
        /*orig
        List storeInFunctionalities = new ArrayList();
        String functIdsConcat = sInfo.getFunctionalityIds();
        String[] functIds =  functIdsConcat.split(",");
        for(int i=0; i<functIds.length; i++) {
           String functIdStr = functIds[i];
           if(functIdStr.trim().equals(""))
              continue;
           Integer functId = Integer.valueOf(functIdStr);
           storeInFunctionalities.add(functId);
        }*/
        List storeInFunctionalities = findFolders(sInfo, biobj, dataStore);
        if (storeInFunctionalities.isEmpty()) {
            throw new Exception(" No functionality specified where store the new document");
        }
        // create biobject

        String jobName = jex.getJobDetail().getName();
        String completeLabel = "scheduler_" + jobName + "_" + docName;
        String label = "sched_" + String.valueOf(Math.abs(completeLabel.hashCode()));

        BIObject newbiobj = new BIObject();
        newbiobj.setDescription(docDesc);
        newbiobj.setCreationUser("scheduler");
        newbiobj.setLabel(label);
        newbiobj.setName(docName);
        newbiobj.setEncrypt(new Integer(0));
        newbiobj.setEngine(engine);
        newbiobj.setDataSourceId(biobj.getDataSourceId());
        newbiobj.setRelName("");
        newbiobj.setBiObjectTypeCode(officeDocDom.getValueCd());
        newbiobj.setBiObjectTypeID(officeDocDom.getValueId());
        newbiobj.setStateCode(relDom.getValueCd());
        newbiobj.setStateID(relDom.getValueId());
        newbiobj.setVisible(new Integer(1));
        newbiobj.setFunctionalities(storeInFunctionalities);
        IBIObjectDAO objectDAO = DAOFactory.getBIObjectDAO();
        Timestamp aoModRecDate;
        BIObject biobjexist = objectDAO.loadBIObjectByLabel(label);
        if (biobjexist == null) {
            objectDAO.insertBIObject(newbiobj, objTemp);
        } else {
            newbiobj.setId(biobjexist.getId());
            objectDAO.modifyBIObject(newbiobj, objTemp);
        }
    } catch (Throwable t) {
        logger.error("Error while saving schedule result as new document", t);
    } finally {
        logger.debug("OUT");
    }
}

From source file:github.daneren2005.dsub.service.RESTMusicService.java

private String getCachedMusicFoldersFilename(Context context) {
    String s = Util.getRestUrl(context, null);
    return "musicFolders-" + Math.abs(s.hashCode()) + ".ser";
}