Example usage for java.lang String intern

List of usage examples for java.lang String intern

Introduction

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

Prototype

public native String intern();

Source Link

Document

Returns a canonical representation for the string object.

Usage

From source file:org.apache.synapse.commons.throttle.core.RoleBasedAccessRateController.java

/**
 * To check whether caller can access not not base on the controlling  policy
 *
 * @param throttleContext - current states of throttle - RunTime Data
 * @param roleID          - Identifier for remote caller - ex: ip or domainname
 * @return access information//from w  ww.  j  a  v  a  2  s  .  c  om
 * @throws ThrottleException
 */
public AccessInformation canAccess(ThrottleContext throttleContext, String consumerKey, String roleID)
        throws ThrottleException {

    String type = "role";

    ThrottleConfiguration throttleConfigurationBean = throttleContext.getThrottleConfiguration();
    AccessInformation accessInformation = new AccessInformation();

    if (throttleConfigurationBean == null) {
        if (debugOn) {
            log.debug("Couldn't find Throttle Configuration!! - Throttling will not occur");
        }
        accessInformation.setAccessAllowed(true);
        return accessInformation;
    }

    if (roleID == null) {
        String msg = "Couldn't find consumer role!! - Access will be denied ";
        if (debugOn) {
            log.debug(msg);
        }
        accessInformation.setAccessAllowed(false);
        accessInformation.setFaultReason(msg);
        return accessInformation;
    }

    CallerConfiguration configuration = throttleConfigurationBean.getCallerConfiguration(roleID);
    if (configuration == null) {
        if (debugOn) {
            log.debug("Caller configuration couldn't find for " + type + " and for caller " + roleID);
        }
        accessInformation.setAccessAllowed(true);
        return accessInformation;
    }
    if (configuration.getAccessState() == ThrottleConstants.ACCESS_DENIED) {
        log.info(ACCESS_DENIED);
        accessInformation.setAccessAllowed(false);
        accessInformation.setFaultReason(ACCESS_DENIED);
        return accessInformation;
    } else if (configuration.getAccessState() == ThrottleConstants.ACCESS_ALLOWED) {
        accessInformation.setAccessAllowed(true);
        return accessInformation;
    } else if (configuration.getAccessState() == ThrottleConstants.ACCESS_CONTROLLED) {
        synchronized (consumerKey.intern()) {
            CallerContext caller = throttleContext.getCallerContext(consumerKey);
            if (caller == null) {
                log.debug("Caller for " + consumerKey + " is not present , Thread : "
                        + Thread.currentThread().getName());
                //if caller has not already registered ,then create new caller description and
                //set it in throttle
                caller = throttleContext.getCallerContext(consumerKey);
                if (caller == null) {
                    log.debug("Caller for " + consumerKey + " is not present for a second time , Thread : "
                            + Thread.currentThread().getName());
                    caller = CallerContextFactory.createCaller(ThrottleConstants.ROLE_BASE, consumerKey);
                }
            }
            if (caller != null) {
                long currentTime = System.currentTimeMillis();

                if (!caller.canAccess(throttleContext, configuration, currentTime)) {
                    //if current caller cannot access , then perform cleaning
                    log.info(ACCESS_DENIED_TEMPORALLY);
                    throttleContext.processCleanList(currentTime);
                    accessInformation.setAccessAllowed(false);
                    accessInformation.setFaultReason(ACCESS_DENIED_TEMPORALLY);
                    return accessInformation;
                } else {
                    if (debugOn) {
                        log.debug("Access  from " + type + " " + roleID + " is successful.");
                    }
                    accessInformation.setAccessAllowed(true);
                    return accessInformation;
                }
            } else {
                if (debugOn) {
                    log.debug("Caller " + type + " not found! " + roleID);
                }
                accessInformation.setAccessAllowed(true);
                return accessInformation;
            }
        }
    }
    accessInformation.setAccessAllowed(true);
    return accessInformation;
}

From source file:com.tao.realweb.util.StringUtil.java

/**
 * Hashes a byte array using the specified algorithm and returns the result as a
 * String of hexadecimal numbers. This method is synchronized to avoid
 * excessive MessageDigest object creation. If calling this method becomes
 * a bottleneck in your code, you may wish to maintain a pool of
 * MessageDigest objects instead of using this method.
 * <p/>//  w w w.j a v  a2s .c  o  m
 * A hash is a one-way function -- that is, given an
 * input, an output is easily computed. However, given the output, the
 * input is almost impossible to compute. This is useful for passwords
 * since we can store the hash and a hacker will then have a very hard time
 * determining the original password.
 * <p/>
 * In Jive, every time a user logs in, we simply
 * take their plain text password, compute the hash, and compare the
 * generated hash to the stored hash. Since it is almost impossible that
 * two passwords will generate the same hash, we know if the user gave us
 * the correct password or not. The only negative to this system is that
 * password recovery is basically impossible. Therefore, a reset password
 * method is used instead.
 *
 * @param bytes the byte array to compute the hash of.
 * @param algorithm the name of the algorithm requested.
 * @return a hashed version of the passed-in String
 */
public static String hash(byte[] bytes, String algorithm) {
    synchronized (algorithm.intern()) {
        MessageDigest digest = digests.get(algorithm);
        if (digest == null) {
            try {
                digest = MessageDigest.getInstance(algorithm);
                digests.put(algorithm, digest);
            } catch (NoSuchAlgorithmException nsae) {
                Log.error("Failed to load the " + algorithm + " MessageDigest. "
                        + "Jive will be unable to function normally.", nsae);
                return null;
            }
        }
        // Now, compute hash.
        digest.update(bytes);
        return encodeHex(digest.digest());
    }
}

From source file:SymbolTable.java

/**
 * Similar to to {@link #findSymbol(char[],int,int,int)}; used to either
 * do potentially cheap intern() (if table already has intern()ed version),
 * or to pre-populate symbol table with known values.
 *///from  ww w.  j a v a2 s .c  o  m
public String findSymbol(String str) {
    int len = str.length();
    // Sanity check:
    if (len < 1) {
        return EMPTY_STRING;
    }

    int index = calcHash(str) & mIndexMask;
    String sym = mSymbols[index];

    // Optimal case; checking existing primary symbol for hash index:
    if (sym != null) {
        // Let's inline primary String equality checking:
        if (sym.length() == len) {
            int i = 0;
            for (; i < len; ++i) {
                if (sym.charAt(i) != str.charAt(i)) {
                    break;
                }
            }
            // Optimal case; primary match found
            if (i == len) {
                return sym;
            }
        }
        // How about collision bucket?
        Bucket b = mBuckets[index >> 1];
        if (b != null) {
            sym = b.find(str);
            if (sym != null) {
                return sym;
            }
        }
    }

    // Need to expand?
    if (mSize >= mSizeThreshold) {
        rehash();
        /* Need to recalc hash; rare occurence (index mask has been
         * recalculated as part of rehash)
         */
        index = calcHash(str) & mIndexMask;
    } else if (!mDirty) {
        // Or perhaps we need to do copy-on-write?
        copyArrays();
        mDirty = true;
    }
    ++mSize;

    if (mInternStrings) {
        str = str.intern();
    }
    // Ok; do we need to add primary entry, or a bucket?
    if (mSymbols[index] == null) {
        mSymbols[index] = str;
    } else {
        int bix = index >> 1;
        mBuckets[bix] = new Bucket(str, mBuckets[bix]);
    }

    return str;
}

From source file:org.apache.axiom.om.impl.llom.OMStAXWrapper.java

/**
 * @return Returns String.//from w  w  w .  ja v  a2s.com
 * @see javax.xml.stream.XMLStreamReader#getNamespaceURI()
 */
public String getNamespaceURI() {
    String returnStr = null;
    if (parser != null) {
        returnStr = parser.getNamespaceURI();
    } else {
        if ((currentEvent == START_ELEMENT) || (currentEvent == END_ELEMENT) || (currentEvent == NAMESPACE)) {
            OMNamespace ns = ((OMElement) getNode()).getNamespace();
            returnStr = (ns == null) ? null : ns.getNamespaceURI();
        }
    }

    // By default most parsers don't intern the namespace.
    // Unfortunately the property to detect interning on the delegate parsers is hard to detect.
    // Woodstox has a proprietary property on the XMLInputFactory.
    // IBM has a proprietary property on the XMLStreamReader.
    // For now only force the interning if requested.
    if (this.isNamespaceURIInterning()) {
        returnStr = (returnStr != null) ? returnStr.intern() : null;
    }
    return returnStr;
}

From source file:ubic.basecode.bio.geneset.GeneAnnotations.java

/**
 * Constructor designed for use when a file is not the immediate input of the data.
 * //from  w w  w . j  a v  a  2 s  . co m
 * @param probes A List of probes
 * @param geneSymbols A List of gene symbols (e.g., ACTB), corresponding to the probes (in the same order)
 * @param geneNames A List of gene names (e.g., "Actin"), corresponding to the probes (in the same order). This can
 *        be null.
 * @param goTerms A List of Collections of Strings corresponding to the GO terms for each probe.
 * @throws IllegaArgumentException if any of the required arguments are null, don't have sizes that match, etc.
 */
public GeneAnnotations(List<String> probes, List<String> geneSymbols, List<String> geneNames,
        List<Collection<String>> goTerms) {
    checkValidData(probes, geneSymbols, geneNames, goTerms);
    assert probes != null;
    setUpdataStructures();

    this.activeProbes = probes;
    activeProbesDirty();

    Collection<String> probeIds = new ArrayList<String>();
    for (int i = 0; i < probes.size(); i++) {
        String probe = probes.get(i);
        String geneSymbol = geneSymbols.get(i);
        String geneName = null;
        if (geneNames != null) {
            geneName = geneNames.get(i);
        }
        Collection<String> goTermsForProbe = goTerms.get(i);

        storeProbeAndGene(probeIds, probe, geneSymbol);

        if (geneName != null) {
            probeToDescription.put(probe.intern(), geneName.intern());
        } else {
            probeToDescription.put(probe.intern(), NO_DESCRIPTION);
        }

        for (String string : goTermsForProbe) {
            String go = string.intern();
            probeToGeneSetMap.get(probe).add(go);

            if (!geneSetToProbeMap.containsKey(go)) {
                geneSetToProbeMap.put(go, new HashSet<String>());
            }
            geneSetToProbeMap.get(go).add(probe);
        }

        if (messenger != null && i % 500 == 0) {
            messenger.showStatus("Read " + i + " probes");
            try {
                Thread.sleep(10);
            } catch (InterruptedException e) {
                throw new RuntimeException("Interrupted");
            }
        }
    }
    resetSelectedProbes();
    this.setUp(null);
}

From source file:org.bdval.DAVMode.java

protected void setupOutput(final JSAPResult result, final DAVOptions options) {
    final String output;
    options.overwriteOutput = result.getBoolean("overwrite-output");
    if (result.getBoolean("output-stats-from-gene-list")) {
        output = makeStatsFileFromGeneListsFile(options.geneLists, result.getString("output"));
    } else {/*from  ww  w  .jav a  2 s.  c  o m*/
        output = result.getString("output");
    }
    System.out.println(">>> DAVMode.Output (stats) file is " + output);

    if (output == null || output.equals("-")) {
        options.output = new PrintWriter(System.out);
        System.err.println("Output will be written to stdout");
    } else {
        try {
            // Make sure the path of the output file exists.
            final String path = FilenameUtils.getFullPath(output);
            if (StringUtils.isNotBlank(path)) {
                FileUtils.forceMkdir(new File(path));
            }
            synchronized (output.intern()) {
                final File outputFile = new File(output);
                options.outputFilePreexist = options.overwriteOutput ? false : outputFile.exists();
                options.output = new PrintWriter(new FileWriter(output, !options.overwriteOutput));
                System.out.println("Output will be written to file " + output);
            }
        } catch (IOException e) {
            System.err.println("Cannot create output file for filename " + output);
            //   e.printStackTrace();
        }
    }
}

From source file:com.cloud.storage.resource.VmwareStorageProcessor.java

private String deleteDir(String dir) {
    synchronized (dir.intern()) {
        Script command = new Script(false, "rm", _timeout, s_logger);
        command.add("-rf");
        command.add(dir);//from  ww  w .j  av  a  2  s  .  co  m
        return command.execute();
    }
}

From source file:ubic.basecode.bio.geneset.GeneAnnotations.java

/**
 * @param bis//from w  ww .jav a  2 s.c om
 * @param activeGenes
 * @throws IOException
 */
protected void readAgilent(InputStream bis, Set<String> activeGenes) throws IOException {
    if (bis == null) {
        throw new IOException("Inputstream was null");
    }
    BufferedReader dis = new BufferedReader(new InputStreamReader(bis));
    Collection<String> probeIds = new ArrayList<String>();
    String classIds = null;

    String header = dis.readLine();
    int numFields = getAgilentNumFields(header);
    int probeIndex = getAgilentProbeIndex(header);
    int goIndex = getAgilentGoIndex(header);
    int geneNameIndex = getAgilentGeneNameIndex(header);
    int geneSymbolIndex = getAgilentGeneSymbolIndex(header);

    tick();
    assert (numFields > probeIndex + 1 && numFields > geneSymbolIndex + 1);
    Pattern pat = Pattern.compile("[0-9]+");
    // loop through rows. Makes hash map of probes to go, and map of go to
    // probes.
    int n = 0;
    String line = "";
    while ((line = dis.readLine()) != null) {

        if (Thread.currentThread().isInterrupted()) {
            dis.close();
            throw new CancellationException();
        }

        String[] fields = StringUtils.splitPreserveAllTokens(line, '\t');
        if (fields.length < probeIndex + 1 || fields.length < geneSymbolIndex + 1) {
            continue; // skip lines that don't meet criteria.
        }

        String probe = fields[probeIndex];
        String gene = fields[geneSymbolIndex];

        if (activeGenes != null && !activeGenes.contains(gene)) {
            continue;
        }

        storeProbeAndGene(probeIds, probe, gene);

        /* read gene description */

        String description = fields[geneNameIndex].intern();
        if (!description.startsWith("GO:")) {
            probeToDescription.put(probe.intern(), description.intern());
        } else {
            probeToDescription.put(probe.intern(), NO_DESCRIPTION);
        }

        if (fields.length < goIndex + 1) {
            continue;
        }

        classIds = fields[goIndex];

        if (StringUtils.isNotBlank(classIds)) {
            String[] goinfo = classIds.split("\\|");
            for (String element : goinfo) {
                String goi = element.intern();
                parseGoTerm(probe, pat, goi);
            }
        }

        if (messenger != null && n % 500 == 0) {
            messenger.showStatus("Read " + n + " probes");
            try {
                Thread.sleep(10);
            } catch (InterruptedException e) {
                dis.close();
                throw new RuntimeException("Interrupted");
            }
        }
        n++;

    }

    /* Fill in the genegroupreader and the classmap */
    dis.close();
    tick();
    resetSelectedProbes();

    if (probeToGeneName.size() == 0 || geneSetToProbeMap.size() == 0) {
        throw new IllegalArgumentException(
                "The gene annotations had invalid information. Please check the format.");
    }

}

From source file:com.cloud.storage.resource.VmwareStorageProcessor.java

private Pair<String, String[]> exportVolumeToSecondaryStroage(VirtualMachineMO vmMo, String volumePath,
        String secStorageUrl, String secStorageDir, String exportName, String workerVmName, Integer nfsVersion)
        throws Exception {

    String secondaryMountPoint = mountService.getMountPoint(secStorageUrl, nfsVersion);
    String exportPath = secondaryMountPoint + "/" + secStorageDir + "/" + exportName;

    synchronized (exportPath.intern()) {
        if (!new File(exportPath).exists()) {
            Script command = new Script(false, "mkdir", _timeout, s_logger);
            command.add("-p");
            command.add(exportPath);/*from  ww w  . ja v a 2s  .co  m*/
            if (command.execute() != null) {
                throw new Exception("unable to prepare snapshot backup directory");
            }
        }
    }

    VirtualMachineMO clonedVm = null;
    try {

        Pair<VirtualDisk, String> volumeDeviceInfo = vmMo.getDiskDevice(volumePath);
        if (volumeDeviceInfo == null) {
            String msg = "Unable to find related disk device for volume. volume path: " + volumePath;
            s_logger.error(msg);
            throw new Exception(msg);
        }

        // 4 MB is the minimum requirement for VM memory in VMware
        Pair<VirtualMachineMO, String[]> cloneResult = vmMo.cloneFromCurrentSnapshot(workerVmName, 0, 4,
                volumeDeviceInfo.second(), VmwareHelper.getDiskDeviceDatastore(volumeDeviceInfo.first()));
        clonedVm = cloneResult.first();
        String disks[] = cloneResult.second();

        clonedVm.exportVm(exportPath, exportName, false, false);
        return new Pair<String, String[]>(volumeDeviceInfo.second(), disks);
    } finally {
        if (clonedVm != null) {
            clonedVm.detachAllDisks();
            clonedVm.destroy();
        }
    }
}

From source file:ubic.basecode.bio.geneset.GeneAnnotations.java

/**
 * @param probeIds//from  ww  w.j av  a  2s .  c o m
 * @param probe
 * @param geneSymbol
 */
private void storeProbeAndGene(Collection<String> probeIds, String probe, String geneSymbol) {

    if (StringUtils.isBlank(geneSymbol)) {
        throw new IllegalArgumentException("Blank gene symbol");
    }
    if (StringUtils.isBlank(probe)) {
        throw new IllegalArgumentException("Blank probe name");
    }

    probeToGeneName.put(probe, geneSymbol);

    // create the list if need be.
    if (geneToProbeMap.get(geneSymbol) == null) {
        geneToProbeMap.put(geneSymbol, new HashSet<String>());
    }
    geneToProbeMap.get(geneSymbol).add(probe);

    probeIds.add(probe);
    if (!probeToGeneSetMap.containsKey(probe)) {
        probeToGeneSetMap.put(probe.intern(), new HashSet<String>());
    }
    geneToGeneSetMap.put(geneSymbol, probeToGeneSetMap.get(probe));
}