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.lenskit.data.entities.TypedName.java

/**
 * Create a typed name object.//  w  ww  . j  a v  a 2 s  . c o m
 *
 * @param name The name.
 * @param type The type.
 * @return An object encapsulating the specified name and type.
 */
@SuppressWarnings("unchecked")
@Nonnull
public static <T> TypedName<T> create(String name, Class<T> type) {
    Preconditions.checkNotNull(name, "name");
    Preconditions.checkNotNull(type, "type");
    if (type.isPrimitive()) {
        type = (Class<T>) ClassUtils.primitiveToWrapper(type);
    }
    TypedName<T> attribute = new TypedName<>(name.intern(), type);
    return (TypedName<T>) FIELD_CACHE.intern(attribute);
}

From source file:de.tudarmstadt.ukp.dkpro.core.corenlp.internal.CoreNlp2DKPro.java

public static void convertPOSs(JCas aJCas, Annotation document, MappingProvider mappingProvider,
        boolean internStrings) {
    for (CoreMap s : document.get(SentencesAnnotation.class)) {
        for (CoreLabel t : s.get(TokensAnnotation.class)) {
            Token token = t.get(TokenKey.class);
            String tag = t.get(PartOfSpeechAnnotation.class);
            Type tagType = mappingProvider.getTagType(tag);
            POS anno = (POS) aJCas.getCas().createAnnotation(tagType, token.getBegin(), token.getEnd());
            anno.setPosValue(internStrings ? tag.intern() : tag);
            anno.setCoarseValue(/*w w  w .ja va  2  s .  co  m*/
                    anno.getClass().equals(POS.class) ? null : anno.getType().getShortName().intern());
            anno.addToIndexes();
            token.setPos(anno);
        }
    }
}

From source file:com.opengamma.engine.value.ValueRequirement.java

public static String getInterned(final String valueName) {
    //This has been observed to be faster if a large proportion of valueNames are already interned and we have a large number of cores
    String interned = s_interned.get(valueName);
    if (interned != null) {
        return interned;
    }//from  www  .  jav  a 2  s  .  co m
    interned = valueName.intern();
    s_interned.putIfAbsent(interned, interned); //NOTE: use interned for keys too
    return interned;
}

From source file:de.tudarmstadt.ukp.dkpro.core.corenlp.internal.CoreNlp2DKPro.java

public static void convertDependencies(JCas aJCas, Annotation document, MappingProvider mappingProvider,
        boolean internStrings) {
    for (CoreMap s : document.get(SentencesAnnotation.class)) {
        SemanticGraph graph = s.get(CollapsedDependenciesAnnotation.class);
        //SemanticGraph graph = s.get(EnhancedDependenciesAnnotation.class);

        // If there are no dependencies for this sentence, skip it. Might well mean we
        // skip all sentences because normally either there are dependencies for all or for
        // none.//  ww  w.  j  a  va 2 s.c  o m
        if (graph == null) {
            continue;
        }

        for (IndexedWord root : graph.getRoots()) {
            Dependency dep = new ROOT(aJCas);
            dep.setDependencyType("root");
            dep.setDependent(root.get(TokenKey.class));
            dep.setGovernor(root.get(TokenKey.class));
            dep.setBegin(dep.getDependent().getBegin());
            dep.setEnd(dep.getDependent().getEnd());
            dep.setFlavor(DependencyFlavor.BASIC);
            dep.addToIndexes();
        }

        for (SemanticGraphEdge edge : graph.edgeListSorted()) {
            Token dependent = edge.getDependent().get(TokenKey.class);
            Token governor = edge.getGovernor().get(TokenKey.class);

            // For the type mapping, we use getShortName() instead, because the <specific>
            // actually doesn't change the relation type
            String labelUsedForMapping = edge.getRelation().getShortName();

            // The nndepparser may produce labels in which the shortName contains a colon.
            // These represent language-specific labels of the UD, cf: 
            // http://universaldependencies.github.io/docs/ext-dep-index.html
            labelUsedForMapping = StringUtils.substringBefore(labelUsedForMapping, ":");

            // Need to use toString() here to get "<shortname>_<specific>"
            String actualLabel = edge.getRelation().toString();

            Type depRel = mappingProvider.getTagType(labelUsedForMapping);
            Dependency dep = (Dependency) aJCas.getCas().createFS(depRel);
            dep.setDependencyType(internStrings ? actualLabel.intern() : actualLabel);
            dep.setDependent(dependent);
            dep.setGovernor(governor);
            dep.setBegin(dep.getDependent().getBegin());
            dep.setEnd(dep.getDependent().getEnd());
            dep.setFlavor(edge.isExtra() ? DependencyFlavor.ENHANCED : DependencyFlavor.BASIC);
            dep.addToIndexes();
        }
    }
}

From source file:org.apache.hadoop.mapreduce.v2.jobhistory.JobHistoryUtils.java

/**Extracts the timstamp component from the path.
 * @param path//from  www .  j  a  va  2s .  c  o  m
 * @return the timestamp component from the path
 */
public static String getTimestampPartFromPath(String path) {
    Matcher matcher = TIMESTAMP_DIR_PATTERN.matcher(path);
    if (matcher.find()) {
        String matched = matcher.group();
        String ret = matched.intern();
        return ret;
    } else {
        return null;
    }
}

From source file:org.wso2.carbon.core.multitenancy.utils.TenantAxisUtils.java

/**
 * Create Tenant Axis2 ConfigurationContexts & add them to the main Axis2 ConfigurationContext
 *
 * @param mainConfigCtx Super-tenant Axis2 ConfigurationContext
 * @param tenantDomain  Tenant domain (e.g. foo.com)
 * @return The newly created Tenant ConfigurationContext
 * @throws Exception If an error occurs while creating tenant ConfigurationContext
 *///from   w ww  .j  a  va  2  s.c om
private static ConfigurationContext createTenantConfigurationContext(ConfigurationContext mainConfigCtx,
        String tenantDomain) throws Exception {
    synchronized (tenantDomain.intern()) { // lock based on tenant domain
        Map<String, ConfigurationContext> tenantConfigContexts = getTenantConfigurationContexts(mainConfigCtx);
        ConfigurationContext tenantConfigCtx = tenantConfigContexts.get(tenantDomain);
        if (tenantConfigCtx != null) {
            return tenantConfigCtx;
        }
        long tenantLoadingStartTime = System.currentTimeMillis();
        int tenantId = getTenantId(tenantDomain);
        if (tenantId == MultitenantConstants.SUPER_TENANT_ID
                || tenantId == MultitenantConstants.INVALID_TENANT_ID) {
            throw new Exception("Tenant " + tenantDomain + " does not exist");
        }
        PrivilegedCarbonContext carbonContext = PrivilegedCarbonContext.getThreadLocalCarbonContext();
        carbonContext.setTenantId(tenantId);
        carbonContext.setTenantDomain(tenantDomain);

        tenantConfigCtx = tenantConfigContexts.get(tenantDomain);
        if (tenantConfigCtx != null) {
            return tenantConfigCtx;
        }

        AxisConfiguration mainAxisConfig = mainConfigCtx.getAxisConfiguration();

        dataHolder.getTenantRegistryLoader().loadTenantRegistry(tenantId);

        try {
            UserRegistry tenantConfigRegistry = dataHolder.getRegistryService()
                    .getConfigSystemRegistry(tenantId);
            UserRegistry tenantLocalUserRegistry = dataHolder.getRegistryService().getLocalRepository(tenantId);
            TenantAxisConfigurator tenantAxisConfigurator = new TenantAxisConfigurator(mainAxisConfig,
                    tenantDomain, tenantId, tenantConfigRegistry, tenantLocalUserRegistry);
            doPreConfigContextCreation(tenantId);
            tenantConfigCtx = ConfigurationContextFactory.createConfigurationContext(tenantAxisConfigurator);

            AxisConfiguration tenantAxisConfig = tenantConfigCtx.getAxisConfiguration();

            tenantConfigCtx.setServicePath(CarbonUtils.getAxis2ServicesDir(tenantAxisConfig));
            tenantConfigCtx.setContextRoot("local:/");

            TenantTransportSender transportSender = new TenantTransportSender(mainConfigCtx);
            // Adding transport senders
            HashMap<String, TransportOutDescription> transportSenders = mainAxisConfig.getTransportsOut();
            if (transportSenders != null && !transportSenders.isEmpty()) {
                for (String strTransport : transportSenders.keySet()) {
                    TransportOutDescription outDescription = new TransportOutDescription(strTransport);
                    outDescription.setSender(transportSender);
                    tenantAxisConfig.addTransportOut(outDescription);
                }
            }

            // Set the work directory
            tenantConfigCtx.setProperty(ServerConstants.WORK_DIR,
                    mainConfigCtx.getProperty(ServerConstants.WORK_DIR));
            PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantId(tenantId);
            new TransportPersistenceManager(tenantAxisConfig).updateEnabledTransports(
                    tenantAxisConfig.getTransportsIn().values(), tenantAxisConfig.getTransportsOut().values());

            // Notify all observers
            BundleContext bundleContext = dataHolder.getBundleContext();
            if (bundleContext != null) {
                ServiceTracker tracker = new ServiceTracker(bundleContext,
                        Axis2ConfigurationContextObserver.class.getName(), null);
                tracker.open();
                Object[] services = tracker.getServices();
                if (services != null) {
                    for (Object service : services) {
                        ((Axis2ConfigurationContextObserver) service)
                                .createdConfigurationContext(tenantConfigCtx);
                    }
                }
                tracker.close();
            }
            tenantConfigCtx.setProperty(MultitenantConstants.LAST_ACCESSED, System.currentTimeMillis());

            // Register Capp deployer for this tenant
            Utils.addCAppDeployer(tenantAxisConfig);

            //deploy the services since all the deployers are initialized by now.
            tenantAxisConfigurator.deployServices();

            //tenant config context must only be made after the tenant is fully loaded, and all its artifacts
            //are deployed.
            // -- THIS SHOULD BE THE LAST OPERATION OF THIS METHOD --
            tenantConfigContexts.put(tenantDomain, tenantConfigCtx);

            log.info("Loaded tenant " + tenantDomain + " in "
                    + (System.currentTimeMillis() - tenantLoadingStartTime) + " ms");

            return tenantConfigCtx;
        } catch (Exception e) {
            String msg = "Error occurred while running deployment for tenant ";
            log.error(msg + tenantDomain, e);
            throw new Exception(msg, e);
        }
    }
}

From source file:org.wso2.carbon.core.multitenancy.utils.TenantAxisUtils.java

/**
 * Traverse the list of tenants and cleanup tenants which have been idling for longer than
 * <code>tenantIdleTimeMillis</code>
 *
 * @param tenantIdleTimeMillis The maximum tenant idle time in milliseconds
 *///  w ww.jav a 2  s .  c  om
public static void cleanupTenants(long tenantIdleTimeMillis) {
    ConfigurationContext mainServerConfigContext = CarbonCoreDataHolder.getInstance()
            .getMainServerConfigContext();
    if (mainServerConfigContext == null) {
        return;
    }
    Map<String, ConfigurationContext> tenantConfigContexts = getTenantConfigurationContexts(
            mainServerConfigContext);
    ArrayList<String> eagerLoadedTenants = TenantEagerLoader.getEagerLoadingTenantList();
    for (Map.Entry<String, ConfigurationContext> entry : tenantConfigContexts.entrySet()) {
        String tenantDomain = entry.getKey();
        // Only unload the tenant if it's not in EagerLoading tenant list
        if (!eagerLoadedTenants.contains(tenantDomain)) {
            synchronized (tenantDomain.intern()) {
                ConfigurationContext tenantCfgCtx = entry.getValue();
                Long lastAccessed = (Long) tenantCfgCtx.getProperty(MultitenantConstants.LAST_ACCESSED);
                if (System.currentTimeMillis() - lastAccessed >= tenantIdleTimeMillis) {
                    // Get the write lock.
                    Lock tenantWriteLock = tenantReadWriteLocks.get(tenantDomain).writeLock();
                    tenantWriteLock.lock();
                    try {
                        lastAccessed = (Long) tenantCfgCtx.getProperty(MultitenantConstants.LAST_ACCESSED);
                        if (System.currentTimeMillis() - lastAccessed >= tenantIdleTimeMillis) {
                            try {
                                PrivilegedCarbonContext.startTenantFlow();
                                // Creating CarbonContext object for these threads.
                                PrivilegedCarbonContext carbonContext = PrivilegedCarbonContext
                                        .getThreadLocalCarbonContext();
                                carbonContext.setTenantDomain(tenantDomain, true);

                                // Terminating idle tenant configuration contexts.
                                terminateTenantConfigContext(tenantCfgCtx);
                                tenantConfigContexts.remove(tenantDomain);
                            } finally {
                                PrivilegedCarbonContext.endTenantFlow();
                            }
                        }
                    } finally {
                        tenantWriteLock.unlock();
                    }
                }
            }
        }
    }
}

From source file:de.tudarmstadt.ukp.dkpro.core.corenlp.internal.CoreNlp2DKPro.java

public static void convertNamedEntities(JCas aJCas, Annotation document, MappingProvider mappingProvider,
        boolean internStrings) {
    for (CoreMap s : document.get(SentencesAnnotation.class)) {
        for (CoreLabel t : s.get(TokensAnnotation.class)) {
            Token token = t.get(TokenKey.class);
            String tag = t.get(NamedEntityTagAnnotation.class);

            // "O" is the hard-coded tag in CoreNLP to indicate no NER on this token
            if ("O".equals(tag)) {
                continue;
            }/* w ww .j  a  va2s .  c  o  m*/

            Type tagType = mappingProvider.getTagType(tag);
            NamedEntity anno = (NamedEntity) aJCas.getCas().createAnnotation(tagType, token.getBegin(),
                    token.getEnd());
            anno.setValue(internStrings ? tag.intern() : tag);
            anno.addToIndexes();
        }
    }
}

From source file:org.opencms.i18n.CmsEncoder.java

/**
 * Creates a String out of a byte array with the specified encoding, falling back
 * to the system default in case the encoding name is not valid.<p>
 * /*from   ww  w  . j av  a2s .c om*/
 * Use this method as a replacement for <code>new String(byte[], encoding)</code>
 * to avoid possible encoding problems.<p>
 * 
 * @param bytes the bytes to decode 
 * @param encoding the encoding scheme to use for decoding the bytes
 * 
 * @return the bytes decoded to a String
 */
public static String createString(byte[] bytes, String encoding) {

    String enc = encoding.intern();
    if (enc != OpenCms.getSystemInfo().getDefaultEncoding()) {
        enc = lookupEncoding(enc, null);
    }
    if (enc != null) {
        try {
            return new String(bytes, enc);
        } catch (UnsupportedEncodingException e) {
            // this can _never_ happen since the charset was looked up first 
        }
    } else {
        if (LOG.isWarnEnabled()) {
            LOG.warn(Messages.get().getBundle().key(Messages.ERR_UNSUPPORTED_VM_ENCODING_1, encoding));
        }
        enc = OpenCms.getSystemInfo().getDefaultEncoding();
        try {
            return new String(bytes, enc);
        } catch (UnsupportedEncodingException e) {
            // this can also _never_ happen since the default encoding is always valid
        }
    }
    // this code is unreachable in practice
    LOG.error(Messages.get().getBundle().key(Messages.ERR_ENCODING_ISSUES_1, encoding));
    return null;
}

From source file:com.magic.util.StringUtil.java

public static String internString(String value) {
    return value != null ? value.intern() : null;
}