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.mayo.cts2.framework.plugin.service.bprdf.model.modifier.NamespaceModifier.java

/**
 * Gets the namespace.// w  w w. j  av a  2s .c o  m
 *
 * @param uri the uri
 * @return the namespace
 */
public String getNamespace(String uri) {

    String acronym = this.idService.getAcronymForUri(uri);
    if (acronym != null) {
        return acronym;
    }

    if (!this.knownNamespaces.containsKey(uri)) {

        String prefix = this.namespaceLookupService.getPreferredPrefixForUri(uri);

        if (StringUtils.isNotBlank(prefix)) {
            this.knownNamespaces.put(uri, prefix);

        } else {
            String hashString = Integer.toString(uri.hashCode());

            hashString = "ns" + hashString;

            this.knownNamespaces.put(uri, hashString);

            log.warn("Generating prefix for Namespace URI: " + uri);
        }
    }

    return this.knownNamespaces.get(uri);
}

From source file:com.lastorder.pushnotifications.data.ImageDownloader.java

/**
 * Adds this bitmap to the cache.// www  .j a  va 2  s .c  o m
 * @param bitmap The newly downloaded bitmap.
 * @param resized 
 */
private void addBitmapToCache(String url, Bitmap bitmap, Bitmap resized) {
    if (bitmap != null) {
        String name = cacheDir + "/" + url.hashCode() + ".jpg";
        String rname = cacheDir + "/" + url.hashCode() + "-t.jpg";
        hasExternalStoragePublicPicture(name);
        saveToSDCard(bitmap, name, url.hashCode() + ".jpg");
        saveToSDCard(resized, rname, url.hashCode() + "-t.jpg");
        sHardBitmapCache.put(url, resized);
    }
}

From source file:ai.susi.mind.SusiSkill.java

/**
 * Create a skill by parsing of the skill description
 * @param json the skill description/*from   w  ww  . ja  v  a  2 s  . c om*/
 * @throws PatternSyntaxException
 */
private SusiSkill(JSONObject json) throws PatternSyntaxException {

    // extract the phrases and the phrases subscore
    if (!json.has("phrases"))
        throw new PatternSyntaxException("phrases missing", "", 0);
    JSONArray p = (JSONArray) json.remove("phrases");
    this.phrases = new ArrayList<>(p.length());
    p.forEach(q -> this.phrases.add(new SusiPhrase((JSONObject) q)));

    // extract the actions and the action subscore
    if (!json.has("actions"))
        throw new PatternSyntaxException("actions missing", "", 0);
    p = (JSONArray) json.remove("actions");
    this.actions = new ArrayList<>(p.length());
    p.forEach(q -> this.actions.add(new SusiAction((JSONObject) q)));

    // extract the inferences and the process subscore; there may be no inference at all
    if (json.has("process")) {
        p = (JSONArray) json.remove("process");
        this.inferences = new ArrayList<>(p.length());
        p.forEach(q -> this.inferences.add(new SusiInference((JSONObject) q)));
    } else {
        this.inferences = new ArrayList<>(0);
    }

    // extract (or compute) the keys; there may be none key given, then they will be computed
    this.keys = new HashSet<>();
    JSONArray k;
    if (json.has("keys")) {
        k = json.getJSONArray("keys");
        if (k.length() == 0 || (k.length() == 1 && k.getString(0).length() == 0))
            k = computeKeysFromPhrases(this.phrases);
    } else {
        k = computeKeysFromPhrases(this.phrases);
    }

    k.forEach(o -> this.keys.add((String) o));

    this.user_subscore = json.has("score") ? json.getInt("score") : DEFAULT_SCORE;
    this.score = null; // calculate this later if required

    // extract the comment
    this.comment = json.has("comment") ? json.getString("comment") : "";

    // calculate the id
    String ids0 = this.actions.toString();
    String ids1 = this.phrases.toString();
    this.id = ids0.hashCode() + ids1.hashCode();
}

From source file:com.opengamma.component.factory.provider.DelegatingHistoricalTimeSeriesProviderComponentFactory.java

@Override
protected Object propertyGet(String propertyName, boolean quiet) {
    switch (propertyName.hashCode()) {
    case -281470431: // classifier
        return getClassifier();
    case -614707837: // publishRest
        return isPublishRest();
    case -547571616: // provider1
        return getProvider1();
    case -547571615: // provider2
        return getProvider2();
    case -547571614: // provider3
        return getProvider3();
    case -547571613: // provider4
        return getProvider4();
    case -547571612: // provider5
        return getProvider5();
    }/*  w w  w.ja v  a2s  .  co m*/
    return super.propertyGet(propertyName, quiet);
}

From source file:com.android.build.gradle.integration.application.ExternalBuildPluginTest.java

@Before
public void setUp() throws IOException {
    IAndroidTarget target = SdkHelper.getTarget(23);
    assertThat(target).isNotNull();/*from   www  .  j a  va  2 s . c om*/

    ApkManifest.Builder apkManifest = ApkManifest.newBuilder()
            .setAndroidSdk(ExternalBuildApkManifest.AndroidSdk.newBuilder()
                    .setAndroidJar(target.getFile(IAndroidTarget.ANDROID_JAR).getAbsolutePath())
                    // TODO: Start putting dx.jar in the proto
                    .setDx(SdkHelper.getDxJar().getAbsolutePath())
                    .setAapt(target.getBuildToolInfo().getPath(BuildToolInfo.PathId.AAPT)))
            .setResourceApk(ExternalBuildApkManifest.Artifact.newBuilder().setExecRootPath("resources.ap_"))
            .setAndroidManifest(
                    ExternalBuildApkManifest.Artifact.newBuilder().setExecRootPath("AndroidManifest.xml"));

    List<String> jarFiles = new FileNameFinder().getFileNames(mProject.getTestDir().getAbsolutePath(),
            "**/*.jar");
    Path projectPath = mProject.getTestDir().toPath();
    for (String jarFile : jarFiles) {
        Path jarFilePath = new File(jarFile).toPath();
        Path relativePath = projectPath.relativize(jarFilePath);
        apkManifest
                .addJars(ExternalBuildApkManifest.Artifact.newBuilder().setExecRootPath(relativePath.toString())
                        .setHash(ByteString.copyFromUtf8(String.valueOf(jarFile.hashCode()))));
    }

    manifestFile = mProject.file("apk_manifest.tmp");
    try (OutputStream os = new BufferedOutputStream(new FileOutputStream(manifestFile))) {
        CodedOutputStream cos = CodedOutputStream.newInstance(os);
        apkManifest.build().writeTo(cos);
        cos.flush();
    }
}

From source file:com.pivotal.gemfire.tools.pulse.tests.TomcatHelper.java

public static Tomcat startTomcat(String bindAddress, int port, String context, String path) throws Exception {

    Tomcat tomcat = new Tomcat();

    // Set up logging - first we're going to remove all existing handlers. Don't do this before Tomcat is
    // instantiated otherwise there isn't anything to remove.
    /*/*from   w w w.  j  av  a 2s . c o m*/
            
    Logger globalLogger = Logger.getLogger("");
    for (Handler handler : globalLogger.getHandlers()) {
      globalLogger.removeHandler(handler);
    }
            
    // Now let's add our handler
    Handler gfHandler = new GemFireHandler((LogWriterImpl) log);
    Logger logger = Logger.getLogger("");
    logger.addHandler(gfHandler);
            
    */

    // Set up for commons-logging which is used by Spring.
    // This forces JCL to use the JDK logger otherwise it defaults to trying to
    // use Log4J.
    if (System.getProperty("org.apache.commons.logging.Log") == null) {
        System.setProperty("org.apache.commons.logging.Log", "org.apache.commons.logging.impl.Jdk14Logger");
    }

    if (bindAddress != null && bindAddress.length() > 0) {
        Connector c = tomcat.getConnector();
        IntrospectionUtils.setProperty(c, "address", bindAddress);
    }
    tomcat.setPort(port);

    // Working (scratch) dir
    String scratch = System.getProperty("java.io.tmpdir") + System.getProperty("file.separator") + "Pulse_"
            + ((bindAddress == null || bindAddress.length() == 0) ? "0.0.0.0" : bindAddress) + "_" + port + "_"
            + String.format("%x", path.hashCode());

    tomcat.setBaseDir(scratch);
    StandardHost stdHost = (StandardHost) tomcat.getHost();
    // stdHost.setUnpackWARs(false);
    // tomcat.addContext(context, path);
    tomcat.addWebapp(stdHost, context, path);
    stdHost.setDeployOnStartup(true);
    tomcat.start();

    return tomcat;
}

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

@Override
protected Object propertyGet(String propertyName, boolean quiet) {
    switch (propertyName.hashCode()) {
    case -266326457: // optionExerciseType
        return getOptionExerciseType();
    case 1373587791: // optionType
        return getOptionType();
    case -891985998: // strike
        return getStrike();
    case -1289159373: // expiry
        return getExpiry();
    case 575402001: // currency
        return getCurrency();
    case -661485980: // tradingExchange
        return getTradingExchange();
    case 389497452: // settlementExchange
        return getSettlementExchange();
    case 1257391553: // pointValue
        return getPointValue();
    case -1770633379: // underlying
        return getUnderlying();
    }//  w  w  w  .jav  a2s .  co  m
    return super.propertyGet(propertyName, quiet);
}

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

@Override
protected Object propertyGet(String propertyName, boolean quiet) {
    switch (propertyName.hashCode()) {
    case -266326457: // optionExerciseType
        return getOptionExerciseType();
    case 1373587791: // optionType
        return getOptionType();
    case -891985998: // strike
        return getStrike();
    case -1289159373: // expiry
        return getExpiry();
    case 575402001: // currency
        return getCurrency();
    case 1989774883: // exchange
        return getExchange();
    case 243392205: // margined
        return getMargined();
    case 1257391553: // pointValue
        return getPointValue();
    case -1770633379: // underlying
        return getUnderlying();
    }//from  ww  w  . ja  va 2  s  . c o m
    return super.propertyGet(propertyName, quiet);
}

From source file:maspack.fileutil.vfs.EncryptedUserAuthenticator.java

/**
 * {@inheritDoc}//from w w  w .  j ava 2 s . c  o  m
 */
@Override
public int hashCode() {
    String str = "";
    if (username != null) {
        str += username + ":";
    }
    if (domain != null) {
        str += domain + ":";
    }
    if (encryptedPassword != null) {
        try {
            str += getCryptor().decrypt(encryptedPassword) + ":";
        } catch (Exception e) {
        }
    }

    return str.hashCode();
}

From source file:net.kayateia.lifestream.StreamService.java

private void checkNewImages() {
    Log.i(LOG_TAG, "Checking for new images on server");
    if (!initStorage())
        return;/*ww  w  .  ja  v  a2s .c  om*/

    // Retrieve our auth token and user parameters. If they're not there, we can't do anything.
    Settings settings = new Settings(this);
    String authToken = settings.getAuthToken();
    if (authToken.isEmpty() || !settings.getEnabled()) {
        Log.i(LOG_TAG, "Not doing download check: not configured, or disabled");
        return;
    }

    // Allow a week back to make sure we didn't miss some due to crashes/race conditions/etc.
    int lastCheck = settings.getLastCheckInt() - (60 * 60 * 24 * 7);
    if (lastCheck < 0)
        lastCheck = ((int) ((new Date()).getTime() / 1000)) - (60 * 60 * 24 * 7);

    final Resources res = getResources();
    final StreamService us = this;
    MediaScannerWrapper scanner = new MediaScannerWrapper(this) {
        @Override
        protected void scanned(String path, Uri uri) {
            // The user directory will be the last path component. We can hash
            // that and make a unique notification ID. This isn't guaranteed to be
            // unique, but for our test purposes, it should work.

            // Convolution: Java has it. This pulls the last component of the path, and then
            // further pulls the "Lifestream_" prefix to get the actual user name.
            File pathFile = new File(path);
            File withoutFilenameFile = pathFile.getParentFile();
            String withoutParentDir = withoutFilenameFile.getParent();
            String userDir = path.substring(withoutParentDir.length() + 1,
                    withoutFilenameFile.getPath().length());
            userDir = userDir.substring(USERDIR_PREFIX.length());

            // Make a hash of it.
            int hash = userDir.hashCode() % 100000;
            int notifyId = NOTIFY_ID + 100 + hash;

            Notifications.NotifyDownload(us, notifyId, true, res.getString(R.string.download_ticker),
                    /*res.getString(R.string.download_title)*/ "From " + userDir, getMessage(path), uri);
        }
    };
    try {
        HashMap<String, String> params = new HashMap<String, String>();
        params.put("auth", authToken);
        params.put("date", "" + lastCheck);

        // Save the current time as a cutoff for future checks. We do it here so as
        // to be conservative when setting the cutoff for the next check.
        Date newLastCheck = new Date();

        String notificationMsg = res.getString(R.string.download_detail);

        String baseUrl = Settings.GetBaseUrl();
        URL url = new URL(baseUrl + "check-images.php");
        String result = HttpMultipartUpload.DownloadString(url, params, this);
        String[] users, files, paths;
        try {
            JSONObject root = new JSONObject(result);
            JSONArray images = root.getJSONArray("images");
            users = new String[images.length()];
            files = new String[images.length()];
            paths = new String[images.length()];

            for (int i = 0; i < images.length(); ++i) {
                JSONObject obj = images.getJSONObject(i);
                users[i] = obj.getString("user");
                files[i] = obj.getString("file");
                paths[i] = obj.getString("path");
            }

            String nmsg = root.optString("message");
            if (!nmsg.equals(""))
                notificationMsg = nmsg;
        } catch (JSONException e) {
            if (settings.getVerbose()) {
                Notifications.NotifyError(this, NOTIFY_ID, true, res.getString(R.string.fail_ticker),
                        res.getString(R.string.fail_title), res.getString(R.string.fail_download));
            }
            Log.w(LOG_TAG, "Can't parse download response: " + result);
            return;
        }

        // We'll just save the last one so that it will open the top image in the stack.
        String galleryPath = null;
        for (int i = 0; i < users.length; ++i) {
            // We're expecting here: user, image name, relative URL path
            String user = users[i];
            String imageName = files[i];
            String urlPath = paths[i];

            // Turn the file.jpg into file_user.jpg.
            // http://stackoverflow.com/questions/4545937/java-splitting-the-filename-into-a-base-and-extension
            String[] fileParts = imageName.split("\\.(?=[^\\.]+$)");
            String localFileName = fileParts[0] + "_" + user + "." + fileParts[1];
            String localPath = getStorageForUser(user).concat(File.separator).concat(localFileName);

            // Does it exist already?
            File localFile = new File(localPath);
            if (localFile.exists()) {
                Log.i(LOG_TAG, "Skipping " + urlPath + " because it already exists");
            } else {
                Log.i(LOG_TAG, "Download file: " + urlPath + " to " + localFileName);
                URL dlurl = new URL(baseUrl + urlPath);
                HttpMultipartUpload.DownloadFile(dlurl, localFile, null, this);
                scanner.addFile(localFile.getAbsolutePath(), notificationMsg);
                galleryPath = localFile.getAbsolutePath();
            }
        }
        scanner.scan();
        Log.i(LOG_TAG, "Download check complete");

        // Success! Update the last check time.
        settings.setLastCheck(newLastCheck);
        settings.commit();
    } catch (IOException e) {
        if (settings.getVerbose()) {
            Notifications.NotifyError(this, NOTIFY_ID, true, res.getString(R.string.fail_ticker),
                    res.getString(R.string.fail_title), res.getString(R.string.fail_download));
        }
        Log.w(LOG_TAG, "Download failed", e);
    }
}