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:uk.ac.ebi.eva.pipeline.io.mappers.VariantVcfFactory.java

/**
 * Intern the genotype String into the String pool to avoid storing lots of "0/0". In case that the variant is
 * multiallelic and we are currently processing one of the secondary alternates (T is the only secondary alternate
 * in a variant like A -> C,T), change the allele codes to represent the current alternate as allele 1. For details
 * on changing this indexes, see {@link VariantVcfFactory#mapToMultiallelicIndex(int, int)}
 *
 * @param alternateAlleleIdx current alternate being processed. 0 for first alternate, 1 or more for a secondary alternate.
 * @param genotype first field in the samples column, e.g. "0/0"
 * @return the processed genotype string, as described above (interned and changed if multiallelic).
 *///from   www.  j a  v a  2s . c om
private String processGenotypeField(int alternateAlleleIdx, String genotype) {
    boolean isNotTheFirstAlternate = alternateAlleleIdx >= 1;
    if (isNotTheFirstAlternate) {
        Genotype parsedGenotype = new Genotype(genotype);

        StringBuilder genotypeStr = new StringBuilder();
        for (int allele : parsedGenotype.getAllelesIdx()) {
            if (allele < 0) { // Missing
                genotypeStr.append(".");
            } else {
                // Replace numerical indexes when they refer to another alternate allele
                genotypeStr.append(String.valueOf(mapToMultiallelicIndex(allele, alternateAlleleIdx)));
            }
            genotypeStr.append(parsedGenotype.isPhased() ? "|" : "/");
        }
        genotype = genotypeStr.substring(0, genotypeStr.length() - 1);
    }

    return genotype.intern();
}

From source file:org.apache.kylin.common.persistence.JDBCResourceDAO.java

public void checkAndPutResource(final String resPath, final byte[] content, final long oldTS, final long newTS)
        throws SQLException, WriteConflictException {
    logger.trace(/* w w  w  . j  a  va  2  s .co m*/
            "execute checkAndPutResource method. resPath : {} , oldTs : {} , newTs : {} , content null ? : {} ",
            resPath, oldTS, newTS, content == null);
    executeSql(new SqlOperation() {
        @Override
        public void execute(Connection connection) throws SQLException {
            synchronized (resPath.intern()) {
                String tableName = getMetaTableName(resPath);
                if (!existResource(resPath)) {
                    if (oldTS != 0) {
                        throw new IllegalStateException(
                                "For not exist file. OldTS have to be 0. but Actual oldTS is : " + oldTS);
                    }
                    if (isContentOverflow(content, resPath)) {
                        logger.debug("Overflow! resource path: {}, content size: {}", resPath, content.length);
                        pstat = connection.prepareStatement(getInsertSqlWithoutContent(tableName));
                        pstat.setString(1, resPath);
                        pstat.setLong(2, newTS);
                        writeLargeCellToHdfs(resPath, content);
                        try {
                            int result = pstat.executeUpdate();
                            if (result != 1)
                                throw new SQLException();
                        } catch (SQLException e) {
                            rollbackLargeCellFromHdfs(resPath);
                            throw e;
                        }
                    } else {
                        pstat = connection.prepareStatement(getInsertSql(tableName));
                        pstat.setString(1, resPath);
                        pstat.setLong(2, newTS);
                        pstat.setBlob(3, new BufferedInputStream(new ByteArrayInputStream(content)));
                        pstat.executeUpdate();
                    }
                } else {
                    // Note the checkAndPut trick:
                    // update {0} set {1}=? where {2}=? and {3}=?
                    pstat = connection.prepareStatement(getUpdateSqlWithoutContent(tableName));
                    pstat.setLong(1, newTS);
                    pstat.setString(2, resPath);
                    pstat.setLong(3, oldTS);
                    int result = pstat.executeUpdate();
                    if (result != 1) {
                        long realTime = getResourceTimestamp(resPath);
                        throw new WriteConflictException("Overwriting conflict " + resPath + ", expect old TS "
                                + oldTS + ", but it is " + realTime);
                    }
                    PreparedStatement pstat2 = null;
                    try {
                        // "update {0} set {1}=? where {3}=?"
                        pstat2 = connection.prepareStatement(getUpdateContentSql(tableName));
                        if (isContentOverflow(content, resPath)) {
                            logger.debug("Overflow! resource path: {}, content size: {}", resPath,
                                    content.length);
                            pstat2.setNull(1, Types.BLOB);
                            pstat2.setString(2, resPath);
                            writeLargeCellToHdfs(resPath, content);
                            try {
                                int result2 = pstat2.executeUpdate();
                                if (result2 != 1)
                                    throw new SQLException();
                            } catch (SQLException e) {
                                rollbackLargeCellFromHdfs(resPath);
                                throw e;
                            }
                            cleanOldLargeCellFromHdfs(resPath);
                        } else {
                            pstat2.setBinaryStream(1,
                                    new BufferedInputStream(new ByteArrayInputStream(content)));
                            pstat2.setString(2, resPath);
                            pstat2.executeUpdate();
                        }
                    } finally {
                        JDBCConnectionManager.closeQuietly(pstat2);
                    }
                }
            }
        }
    });
}

From source file:org.ambraproject.article.service.BrowseServiceImpl.java

/**
 * Get articles in the given category. One "page" of articles will be returned, i.e. articles pageNum * pageSize ..
 * (pageNum + 1) * pageSize - 1 . Note that less than a pageSize articles may be returned, either because it's the end
 * of the list or because some articles are not accessible.
 *
 * @param params A collection filters / parameters to browse by
 * @return the articles./* w ww.  j  a  v  a2 s  .  co  m*/
 */
@Transactional(readOnly = true)
public BrowseResult getArticlesBySubject(final BrowseParameters params) {
    BrowseResult result;

    if (this.useCache) {
        final String cacheKey = ARTBYCAT_LIST_KEY + params.getJournalKey() + "-"
                + StringUtils.join(params.getSubjects(), "-") + "-" + params.getSort() + "-" + "-"
                + params.getPageNum() + "-" + params.getPageSize();

        result = browseSolrCache.get(cacheKey, this.cacheTimeToLive,
                new Cache.SynchronizedLookup<BrowseResult, RuntimeException>(cacheKey.intern()) {
                    @Override
                    public BrowseResult lookup() throws RuntimeException {
                        return getArticlesBySubjectViaSolr(params);
                    }
                });
    } else {
        result = getArticlesBySubjectViaSolr(params);
    }

    return result;
}

From source file:org.opendaylight.netvirt.elan.utils.ElanUtils.java

public static String getElanMacKey(long elanTag, String macAddress) {
    String elanMacKey = "MAC-" + macAddress + " ELAN_TAG-" + elanTag;
    return elanMacKey.intern();
}

From source file:org.wso2.carbon.registry.core.caching.CacheBackedRegistry.java

@SuppressWarnings("unchecked")
public Resource get(String path) throws RegistryException {
    if (registry.getRegistryContext().isNoCachePath(path) || isCommunityFeatureRequest(path)) {
        return registry.get(path);
    }/* w w w  .  ja va2s. c om*/

    Resource resource;
    if (!AuthorizationUtils.authorize(path, ActionConstants.GET)) {
        StringBuilder builder = new StringBuilder();
        builder.append("User ").append(CurrentSession.getUser())
                .append(" is not authorized to read the resource ").append(path).append(".");
        String msg = builder.toString();
        audit.warn(msg);
        throw new AuthorizationFailedException(msg);
    }

    GhostResource<Resource> ghostResource = getGhostResourceFromCache(path);

    resource = ghostResource.getResource();
    if (resource == null) {
        synchronized (path.intern()) {
            resource = registry.get(path);
            if (resource.getProperty(RegistryConstants.REGISTRY_LINK) == null
                    || resource.getProperty(RegistryConstants.REGISTRY_MOUNT) != null) {
                ghostResource.setResource(resource);
            }
        }
    }

    return resource;
}

From source file:org.openstreetmap.josm.data.osm.KeyValuePerformanceTest.java

/**
 * See if there is a big difference between Strings that are interned and those that are not.
 *//*from  w  w  w .  j  a v a2s .  com*/
@Test
@SuppressFBWarnings(value = "DM_STRING_CTOR", justification = "test Strings that are interned and those that are not")
public void testMeasureStringEqualsIntern() {
    String str1Interned = "string1";
    String str1InternedB = "string1";
    String str1 = new String(str1Interned);
    String str1B = new String(str1Interned);
    String str2Interned = "string2";
    String str2 = new String(str2Interned);

    for (int i = 0; i < STRING_INTERN_TESTS; i++) {
        // warm up
        assertEquals(str1, str1B);
    }

    PerformanceTestTimer timer = PerformanceTestUtils.startTimer("Assertion overhead.");
    for (int i = 0; i < STRING_INTERN_TESTS; i++) {
        assertTrue(true);
    }
    timer.done();

    timer = PerformanceTestUtils.startTimer("str1.equals(str2) succeeds (without intern)");
    for (int i = 0; i < STRING_INTERN_TESTS; i++) {
        assertEquals(str1, str1B);
    }
    timer.done();

    timer = PerformanceTestUtils.startTimer("str1 == str2 succeeds");
    for (int i = 0; i < STRING_INTERN_TESTS; i++) {
        assertSame(str1Interned, str1InternedB);
    }
    timer.done();

    timer = PerformanceTestUtils.startTimer("str1 == str2.intern() succeeds");
    for (int i = 0; i < STRING_INTERN_TESTS; i++) {
        assertSame(str1Interned, str1.intern());
    }
    timer.done();

    timer = PerformanceTestUtils.startTimer("str1 == str2.intern() succeeds for interned string");
    for (int i = 0; i < STRING_INTERN_TESTS; i++) {
        assertSame(str1Interned, str1InternedB.intern());
    }
    timer.done();

    timer = PerformanceTestUtils.startTimer("str1.equals(str2) = fails (without intern)");
    for (int i = 0; i < STRING_INTERN_TESTS; i++) {
        assertFalse(str1.equals(str2));
    }
    timer.done();

    timer = PerformanceTestUtils.startTimer("str1 == str2 fails");
    for (int i = 0; i < STRING_INTERN_TESTS; i++) {
        assertNotSame(str1Interned, str2Interned);
    }
    timer.done();

    timer = PerformanceTestUtils.startTimer("str1 == str2.intern() fails");
    for (int i = 0; i < STRING_INTERN_TESTS; i++) {
        assertNotSame(str1Interned, str2.intern());
    }
    timer.done();
}

From source file:org.opendaylight.netvirt.elan.utils.ElanUtils.java

public static String getElanMacDPNKey(long elanTag, String macAddress, BigInteger dpnId) {
    String elanMacDmacDpnKey = "MAC-" + macAddress + " ELAN_TAG-" + elanTag + "DPN_ID-" + dpnId;
    return elanMacDmacDpnKey.intern();
}

From source file:org.wso2.carbon.registry.core.caching.CacheBackedRegistry.java

@SuppressWarnings("unchecked")
public Collection get(String path, int start, int pageSize) throws RegistryException {
    if (registry.getRegistryContext().isNoCachePath(path) || isCommunityFeatureRequest(path)) {
        return registry.get(path, start, pageSize);
    }/*from w  w w. jav a  2  s .c  o m*/
    if (!AuthorizationUtils.authorize(path, ActionConstants.GET)) {
        StringBuilder builder = new StringBuilder();
        builder.append("User ").append(CurrentSession.getUser())
                .append(" is not authorized to read the resource ").append(path).append(".");
        String msg = builder.toString();
        audit.warn(msg);
        throw new AuthorizationFailedException(msg);
    }

    GhostResource<Resource> ghostResource = getGhostCollectionFromCache(path, start, pageSize);
    Collection collection = (Collection) ghostResource.getResource();
    if (collection == null) {
        synchronized (path.intern()) {
            collection = registry.get(path, start, pageSize);
            if (collection.getProperty(RegistryConstants.REGISTRY_LINK) == null) {
                ghostResource.setResource(collection);
            }
        }
    }
    return collection;
}

From source file:org.apache.axiom.om.impl.builder.StAXOMBuilder.java

/**
 * Method processNamespaceData.// w  w  w.j  a v  a 2 s. co m
 *
 * @param node
 */
protected void processNamespaceData(OMElement node) {
    // set the own namespace
    String namespaceURI = parser.getNamespaceURI();
    String prefix = parser.getPrefix();

    int namespaceCount = parser.getNamespaceCount();
    for (int i = 0; i < namespaceCount; i++) {
        String nsprefix = parser.getNamespacePrefix(i);

        //if the namespace is not defined already when we write the start tag declare it
        // check whether this is the default namespace and make sure we have not declared that earlier
        String namespaceURIFromParser = parser.getNamespaceURI(i);
        if (nsprefix == null || "".equals(nsprefix)) {
            String nsuri = parser.getNamespaceURI(i);
            node.declareDefaultNamespace(nsuri == null ? "" : nsuri);
        } else {
            // NOTE_A:
            // 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 (isNamespaceURIInterning()) {
                namespaceURIFromParser = namespaceURIFromParser.intern();
            }
            node.declareNamespace(namespaceURIFromParser, nsprefix);
        }
    }

    if (namespaceURI != null && namespaceURI.length() > 0) {
        OMNamespace namespace = node.findNamespaceURI(prefix == null ? "" : prefix);
        if (namespace == null || !namespace.getNamespaceURI().equals(namespaceURI)) {
            // See NOTE_A above
            if (isNamespaceURIInterning()) {
                namespaceURI = namespaceURI.intern();
            }
            if (prefix == null || "".equals(prefix)) {
                namespace = node.declareDefaultNamespace(namespaceURI);
            } else {
                namespace = node.declareNamespace(namespaceURI, prefix);
            }
        }
        node.setNamespaceWithNoFindInCurrentScope(namespace);
    }
}

From source file:com.francetelecom.clara.cloud.environment.impl.ManageEnvironmentImpl.java

@Override
public String createEnvironment(String releaseUID, EnvironmentTypeEnum requestedType, String ownerSsoId,
        String label, List<String> configRoleUIDs) throws BusinessException {
    Validate.notNull(releaseUID, "cannot create TDI : releaseUid should not be null");
    long start = System.currentTimeMillis();
    EnvironmentTypeEnum type = requestedType;
    if (requestedType != EnvironmentTypeEnum.PRODUCTION && requestedType != EnvironmentTypeEnum.DEVELOPMENT) {
        type = EnvironmentTypeEnum.PRODUCTION;
        log.warn("Requested environment type " + requestedType
                + " is not currently supported; actual type will be " + type);
    }//from w ww. j a va 2 s  .  com
    String environmentUID;
    try {
        MDC.put(LOG_KEY_ENVNAME, label);
        log.debug("createEnvironment: releaseUID={} type={} label={}",
                new Object[] { releaseUID, type.name(), label });
        synchronized (releaseUID.intern()) {
            // Synchronized this part to avoid pultiple creation of the same
            // environment
            Validate.notNull(type, "cannot create TDI : environment type should not be null");
            environmentUID = utils.createTDI(releaseUID, DeploymentProfileEnum.valueOf(type.name()), ownerSsoId,
                    label, configRoleUIDs);
        }
        MDC.put(LOG_KEY_ENVUID, environmentUID);
        // this log is used by splunk dashboard
        log.info("[STATS] Duration : " + (System.currentTimeMillis() - start) + "ms for createEnvironment#1("
                + releaseUID + ", " + type + ", " + ownerSsoId + ", " + label + ")");
        start = System.currentTimeMillis();

        Environment justCreatedEnvironment = environmentRepository.findByUid(environmentUID);

        //
        // Start Activate Here
        //
        managePaasActivation.activate(justCreatedEnvironment.getTechnicalDeploymentInstance().getId());
        // this log is used by splunk dashboard
        log.info("[STATS] Duration : " + (System.currentTimeMillis() - start) + "ms for createEnvironment#2("
                + releaseUID + ", " + type + ", " + ownerSsoId + ", " + label + ")");
        log.info(justCreatedEnvironment.toLogString());
    } finally {
        MDC.remove(LOG_KEY_ENVNAME);
        MDC.remove(LOG_KEY_ENVUID);
    }
    return environmentUID;
}