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.bdval.cache.TableCache.java

/**
 * Check if a table has been saved to the cache.
 *
 * @param splitId     The split id/*from  w  w w. ja  v  a2s. c  om*/
 * @param splitType   The Split type
 * @param datasetName The dataset name
 * @return true if table a table with the specified paramters has been cached
 */
public boolean isTableCached(final int splitId, final String splitType, final String datasetName) {
    final File cachedTableFile = getCachedTableFile(splitId, splitType, datasetName);
    final String filename;
    try {
        filename = cachedTableFile.getCanonicalPath();
    } catch (IOException e) {
        return false;
    }
    synchronized (filename.intern()) {
        return cachedTableFile.exists();
    }
}

From source file:org.protempa.valueset.ValueSet.java

/**
 * Instantiates a new value set with the specified values (value set
 * elements).//w ww .java 2s  .  c om
 *
 * @param valueSetElements a {@link ValueSetElement[]}. No duplicate
 * {@link ValueSetElement}s are allowed.
 */
public ValueSet(String id, String displayName, ValueSetElement[] valueSetElements, boolean ordered,
        SourceId sourceId) {
    if (id == null) {
        throw new IllegalArgumentException("id cannot be null");
    }
    ProtempaUtil.checkArray(valueSetElements, "valueSetElements");

    this.id = id.intern();
    this.displayName = displayName;
    this.valueSetElements = valueSetElements.clone();
    this.ordered = ordered;

    this.values = new HashMap<>();
    for (ValueSetElement vse : this.valueSetElements) {
        if (this.values.containsKey(vse.getValue())) {
            if (LOGGER.isLoggable(Level.WARNING)) {
                LOGGER.log(Level.WARNING, "Ignoring duplicate value {0} for id {1}",
                        new Object[] { vse.getValue().getFormatted(), id });
            }
        } else {
            this.values.put(vse.getValue(), vse);
        }
    }
    this.valuesKeySet = this.values.keySet();
    this.lowerBound = null;
    this.upperBound = null;
    if (sourceId == null) {
        this.sourceId = NotRecordedSourceId.getInstance();
    } else {
        this.sourceId = sourceId;
    }
}

From source file:org.wso2.carbon.appfactory.core.dao.ApplicationDAO.java

/**
 * Method to update a new value for a given attribute of an application
 *
 * @param applicationId id of the application
 * @param key the attribute, which needs to be updated
 * @param newValue the new value of the given attribute key
 * @throws AppFactoryException//from  w w  w. j  a v  a2s  .c o  m
 */
public void updateAppInfoRxt(String applicationId, String key, String newValue, String tenantDomain)
        throws AppFactoryException {
    // creating a unique key for an application in a tenant
    String tenant_appLock = tenantDomain.concat("_").concat(applicationId);

    synchronized (tenant_appLock.intern()) {
        GenericArtifactImpl artifact = getAppInfoArtifact(applicationId, tenantDomain);
        if (log.isDebugEnabled()) {
            log.debug("Updating application information rxt with key : " + key + " value : " + newValue
                    + " applicationId : " + applicationId + " in tenant domain : " + tenantDomain);
        }

        try {
            artifact.setAttribute(key, newValue);
            UserRegistry userRegistry = GovernanceUtil.getUserRegistry();
            GovernanceUtils.loadGovernanceArtifacts(userRegistry);
            GenericArtifactManager artifactManager = new GenericArtifactManager(userRegistry,
                    AppFactoryConstants.RXT_KEY_APPINFO_APPLICATION);
            artifactManager.updateGenericArtifact(artifact);
            JDBCApplicationCacheManager.getApplicationArtifactCache().remove(applicationId);
        } catch (RegistryException e) {
            String errorMsg = "Error while updating the artifact " + applicationId;
            log.error(errorMsg, e);
            throw new AppFactoryException(errorMsg, e);
        }
    }
}

From source file:org.compass.core.lucene.engine.store.AbstractLuceneSearchEngineStore.java

public void configure(LuceneSearchEngineFactory searchEngineFactory, CompassSettings settings,
        CompassMapping mapping) {/*ww  w . ja  v  a2 s  . c  o  m*/
    template = new LuceneStoreTemplate(this);

    this.luceneSettings = searchEngineFactory.getLuceneSettings();

    HashSet<String> subIndexesSet = new HashSet<String>();
    for (ResourceMapping resourceMapping : mapping.getRootMappings()) {
        String alias = resourceMapping.getAlias();
        String[] tempSubIndexes = resourceMapping.getSubIndexHash().getSubIndexes();
        for (String subIndex : tempSubIndexes) {
            subIndexesSet.add(subIndex.intern());

            List<String> list = subIndexesByAlias.get(alias);
            if (list == null) {
                list = new ArrayList<String>();
                subIndexesByAlias.put(alias, list);
            }
            list.add(subIndex);

            list = aliasesBySubIndex.get(subIndex);
            if (aliasesBySubIndex.get(subIndex) == null) {
                list = new ArrayList<String>();
                aliasesBySubIndex.put(subIndex, list);
            }
            list.add(alias);
        }
    }
    subIndexes = subIndexesSet.toArray(new String[subIndexesSet.size()]);

    // set up directory wrapper providers
    Map<String, CompassSettings> dwSettingGroups = settings
            .getSettingGroups(LuceneEnvironment.DirectoryWrapper.PREFIX);
    if (dwSettingGroups.size() > 0) {
        ArrayList<DirectoryWrapperProvider> dws = new ArrayList<DirectoryWrapperProvider>();
        for (Map.Entry<String, CompassSettings> entry : dwSettingGroups.entrySet()) {
            String dwName = entry.getKey();
            if (log.isInfoEnabled()) {
                log.info("Building directory wrapper [" + dwName + "]");
            }
            CompassSettings dwSettings = entry.getValue();
            String dwType = dwSettings.getSetting(LuceneEnvironment.DirectoryWrapper.TYPE);
            if (dwType == null) {
                throw new ConfigurationException(
                        "Directory wrapper [" + dwName + "] has no type associated with it");
            }
            DirectoryWrapperProvider dw;
            try {
                dw = (DirectoryWrapperProvider) ClassUtils.forName(dwType, settings.getClassLoader())
                        .newInstance();
            } catch (Exception e) {
                throw new ConfigurationException("Failed to create directory wrapper [" + dwName + "]", e);
            }
            if (dw instanceof CompassConfigurable) {
                ((CompassConfigurable) dw).configure(dwSettings);
            }
            dws.add(dw);
        }
        directoryWrapperProviders = dws.toArray(new DirectoryWrapperProvider[dws.size()]);
    }

    this.localDirectoryCacheManager = new LocalDirectoryCacheManager(searchEngineFactory);
    localDirectoryCacheManager.configure(settings);
}

From source file:org.flowerplatform.util.servlet.ImageComposerServlet.java

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
    String requestedFile = request.getPathInfo();
    if (requestedFile.startsWith(UtilConstants.IMAGE_COMPOSER_PATH_PREFIX)) {
        requestedFile = requestedFile.substring(UtilConstants.IMAGE_COMPOSER_PATH_PREFIX.length());
    }/* w ww. j a  v a 2 s .  c  o  m*/

    String mapValue = null;
    String mapKey;
    if (useFilesFromTemporaryDirectory) {
        mapKey = requestedFile.intern();
    } else {
        // we don't need synchronization if useFilesFromTempProperty is false (so we don't use .intern)
        mapKey = requestedFile;
    }

    synchronized (mapKey) {
        if (useFilesFromTemporaryDirectory) {
            mapValue = tempFilesMap.get(requestedFile);
            if (mapValue != null) {
                if (getTempFile(mapValue).exists()) {
                    InputStream result = new FileInputStream(getTempFilePath(mapValue));
                    OutputStream output = response.getOutputStream();
                    IOUtils.copy(result, output);
                    logger.debug("File {} served from temp", mapValue);
                    result.close();
                    output.close();
                    return;
                } else { // the temporary file was deleted from disk. 
                    logger.debug("File {} found to be missing from temp", mapValue);
                }
            } else {
                synchronized (this) {
                    counter++;
                    mapValue = counter + "";
                    tempFilesMap.put(requestedFile, mapValue);
                    logger.debug("mapValue {} added", mapValue);
                }
            }
        }

        int indexOfSecondSlash = requestedFile.indexOf('/', 1); // 1, i.e. skip the first index
        if (indexOfSecondSlash < 0) {
            send404(request, response);
            return;
        }
        String[] paths = requestedFile.split("\\" + UtilConstants.RESOURCE_PATH_SEPARATOR);

        int width = 0;
        int height = 0;
        List<BufferedImage> images = new ArrayList<BufferedImage>();

        for (String path : paths) {
            if (!path.startsWith("/")) {
                path = "/" + path;
            }
            indexOfSecondSlash = path.indexOf('/', 1);
            String plugin = path.substring(0, indexOfSecondSlash);
            path = path.substring(indexOfSecondSlash);
            requestedFile = "platform:/plugin" + plugin + "/" + UtilConstants.PUBLIC_RESOURCES_DIR + path;
            try {
                URL url = new URL(requestedFile);
                BufferedImage image = ImageIO.read(url);
                images.add(image);
                if (width < image.getWidth()) {
                    width = image.getWidth();
                }
                if (height < image.getHeight()) {
                    height = image.getHeight();
                }
            } catch (Exception e) {
                // one of the images was not found; skip it
            }
        }

        BufferedImage result = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
        Graphics2D graphics = result.createGraphics();
        for (BufferedImage image : images) {
            graphics.drawImage(image, null, 0, 0);
        }
        graphics.dispose();
        // write image into the Temp folder
        if (!UtilConstants.TEMP_FOLDER.exists()) {
            UtilConstants.TEMP_FOLDER.mkdir();
        }

        FileOutputStream tempOutput = null;
        if (useFilesFromTemporaryDirectory) {
            tempOutput = new FileOutputStream(getTempFilePath(mapValue));
        }
        OutputStream output = response.getOutputStream();

        try {
            if (tempOutput != null) {
                ImageIO.write(result, "png", tempOutput);
                logger.debug("file {} written in temp", mapValue);
            }
            ImageIO.write(result, "png", output);
        } finally {
            if (tempOutput != null) {
                tempOutput.close();
            }
            output.close();
        }
    }
}

From source file:org.diorite.chat.placeholder.PlaceholderType.java

/**
 * Construct new placeholder type for given id and class with possible super types
 *
 * @param id         id of placeholder./*from w  w  w  .  j  a v  a  2 s .co m*/
 * @param type       type of placeholder object.
 * @param superTypes super types of placeholder, this placeholder may use placeholder items from this types.
 */
@SafeVarargs
public PlaceholderType(final String id, final Class<T> type, final PlaceholderType<? super T>... superTypes) {
    this.id = id.intern();
    this.type = type;
    this.superTypes = Sets.newHashSet(superTypes);
}

From source file:org.protempa.proposition.AbstractProposition.java

/**
 * Assigns fields specified in the constructor. This is pulled into a method
 * so that deserialization can initialize those fields correctly.
 *
 * @param id the proposition id./*from ww  w  .j  av  a2 s. c o m*/
 * @param uniqueId the proposition's unique id.
 */
protected final void initializeAbstractProposition(String id, UniqueId uniqueId) {
    this.uniqueId = uniqueId;
    if (id == null) {
        this.id = "";
    } else {
        this.id = id.intern();
    }
}

From source file:org.dkpro.core.io.nif.internal.Nif2DKPro.java

public void convert(Statement aContext, JCas aJCas) {
    Model m = aContext.getModel();// w ww  .  jav  a 2 s.  c  om

    final Resource tSentence = m.createResource(NIF.TYPE_SENTENCE);
    final Resource tWord = m.createResource(NIF.TYPE_WORD);
    final Resource tTitle = m.createResource(NIF.TYPE_TITLE);
    final Resource tParagraph = m.createResource(NIF.TYPE_PARAGRAPH);

    final Property pReferenceContext = m.createProperty(NIF.PROP_REFERENCE_CONTEXT);
    final Property pIsString = m.createProperty(NIF.PROP_IS_STRING);
    final Property pBeginIndex = m.createProperty(NIF.PROP_BEGIN_INDEX);
    final Property pEndIndex = m.createProperty(NIF.PROP_END_INDEX);
    final Property pLemma = m.createProperty(NIF.PROP_LEMMA);
    final Property pStem = m.createProperty(NIF.PROP_STEM);
    final Property pPosTag = m.createProperty(NIF.PROP_POS_TAG);
    final Property pTaIdentRef = m.createProperty(ITS.PROP_TA_IDENT_REF);
    final Property pTaClassRef = m.createProperty(ITS.PROP_TA_CLASS_REF);

    // Convert context node -> document text
    String text = m.getProperty(aContext.getSubject(), pIsString).getString();
    aJCas.setDocumentText(text);

    // Convert headings/titles
    Iterator<Resource> headingIterator = m.listResourcesWithProperty(RDF.type, tTitle)
            .filterKeep(res -> res.getProperty(pReferenceContext).getResource().equals(aContext.getSubject()));
    for (Resource nifTitle : new IteratorIterable<Resource>(headingIterator)) {
        int begin = nifTitle.getProperty(pBeginIndex).getInt();
        int end = nifTitle.getProperty(pEndIndex).getInt();
        Heading uimaHeading = new Heading(aJCas, begin, end);
        uimaHeading.addToIndexes();

        assert assertSanity(nifTitle, uimaHeading);
    }

    // Convert paragraphs
    Iterator<Resource> paragraphIterator = m.listResourcesWithProperty(RDF.type, tParagraph)
            .filterKeep(res -> res.getProperty(pReferenceContext).getResource().equals(aContext.getSubject()));
    for (Resource nifParagraph : new IteratorIterable<Resource>(paragraphIterator)) {
        int begin = nifParagraph.getProperty(pBeginIndex).getInt();
        int end = nifParagraph.getProperty(pEndIndex).getInt();
        Paragraph uimaParagraph = new Paragraph(aJCas, begin, end);
        uimaParagraph.addToIndexes();

        assert assertSanity(nifParagraph, uimaParagraph);
    }

    // Convert sentences
    List<Resource> nifSentences = m.listResourcesWithProperty(RDF.type, tSentence)
            .filterKeep(res -> res.getProperty(pReferenceContext).getResource().equals(aContext.getSubject()))
            .toList();
    nifSentences.sort((a, b) -> a.getProperty(pBeginIndex).getInt() - b.getProperty(pBeginIndex).getInt());
    for (Resource nifSentence : nifSentences) {
        int begin = nifSentence.getProperty(pBeginIndex).getInt();
        int end = nifSentence.getProperty(pEndIndex).getInt();
        Sentence uimaSentence = new Sentence(aJCas, begin, end);
        uimaSentence.addToIndexes();

        assert assertSanity(nifSentence, uimaSentence);
    }

    // Convert tokens
    Iterator<Resource> tokenIterator = m.listResourcesWithProperty(RDF.type, tWord)
            .filterKeep(res -> res.getProperty(pReferenceContext).getResource().equals(aContext.getSubject()));
    for (Resource nifWord : new IteratorIterable<Resource>(tokenIterator)) {
        int begin = nifWord.getProperty(pBeginIndex).getInt();
        int end = nifWord.getProperty(pEndIndex).getInt();
        Token uimaToken = new Token(aJCas, begin, end);
        uimaToken.addToIndexes();

        assert assertSanity(nifWord, uimaToken);

        // Convert lemma
        if (nifWord.hasProperty(pLemma)) {
            Lemma uimaLemma = new Lemma(aJCas, uimaToken.getBegin(), uimaToken.getEnd());
            uimaLemma.setValue(nifWord.getProperty(pLemma).getString());
            uimaLemma.addToIndexes();
            uimaToken.setLemma(uimaLemma);
        }

        // Convert stem
        if (nifWord.hasProperty(pLemma)) {
            Stem uimaStem = new Stem(aJCas, uimaToken.getBegin(), uimaToken.getEnd());
            uimaStem.setValue(nifWord.getProperty(pStem).getString());
            uimaStem.addToIndexes();
            uimaToken.setStem(uimaStem);
        }

        // Convert posTag (this is discouraged, the better alternative should be oliaLink)
        if (nifWord.hasProperty(pPosTag)) {
            String tag = nifWord.getProperty(pStem).getString();
            Type posTag = posMappingProvider.getTagType(tag);
            POS uimaPos = (POS) aJCas.getCas().createAnnotation(posTag, uimaToken.getBegin(),
                    uimaToken.getEnd());
            uimaPos.setPosValue(tag.intern());
            uimaPos.setCoarseValue(
                    uimaPos.getClass().equals(POS.class) ? null : uimaPos.getType().getShortName().intern());
            uimaPos.addToIndexes();
            uimaToken.setPos(uimaPos);
        }
    }

    // Convert named entities
    //
    // NIF uses taIdentRef to link to a unique instance of an entity and taClassRef to identify
    // the category of the entity. Named entity recognizers in DKPro Core just categorizes the
    // entity, e.g. as a person, location, or whatnot. For what NIF uses, we'd need a named
    // entity linker, not just a recognizer. Furthermore, the DKPro Core named entity
    // recognizers are not mapped to a common tag set (unlike e.g. POS which is mapped to 
    // the universal POS tags).
    // 
    // So, what we do here is treating the URI of the taClassRef in NIF simply as the
    // named entity category and store it. 
    //
    // Here we use duck-typing, i.e. it has a taClassRef property then it is likely a named
    // entity. NIF 2.1 [1] appears to introduce a representation of named entities using the
    // class "EntityOccurrence", but e.g. kore50 [2] doesn't seem to use that - it uses "Phrase"
    // instead.
    //
    // [1] http://nif.readthedocs.io/en/2.1-rc/prov-and-conf.html
    // [2] https://datahub.io/dataset/kore-50-nif-ner-corpus
    Set<Resource> nifNamedEntities1 = m.listResourcesWithProperty(pTaIdentRef)
            .filterKeep(res -> res.getProperty(pReferenceContext).getResource().equals(aContext.getSubject()))
            .toSet();
    Set<Resource> nifNamedEntities2 = m.listResourcesWithProperty(pTaIdentRef)
            .filterKeep(res -> res.getProperty(pReferenceContext).getResource().equals(aContext.getSubject()))
            .toSet();
    Set<Resource> nifNamedEntities = new HashSet<Resource>();
    nifNamedEntities.addAll(nifNamedEntities1);
    nifNamedEntities.addAll(nifNamedEntities2);
    for (Resource nifNamedEntity : nifNamedEntities) {
        int begin = nifNamedEntity.getProperty(pBeginIndex).getInt();
        int end = nifNamedEntity.getProperty(pEndIndex).getInt();
        NamedEntity uimaNamedEntity = new NamedEntity(aJCas, begin, end);
        if (nifNamedEntity.hasProperty(pTaClassRef)) {
            uimaNamedEntity.setValue(nifNamedEntity.getProperty(pTaClassRef).getResource().getURI());
        }
        if (nifNamedEntity.hasProperty(pTaIdentRef)) {
            uimaNamedEntity.setIdentifier(nifNamedEntity.getProperty(pTaIdentRef).getResource().getURI());
        }
        uimaNamedEntity.addToIndexes();

        assert assertSanity(nifNamedEntity, uimaNamedEntity);
    }
}

From source file:org.diorite.chat.placeholder.PlaceholderType.java

/**
 * Construct new placeholder type for given id and class with possible super types
 *
 * @param id         id of placeholder.//from  w ww.  j  a v  a2  s  . c  o m
 * @param type       type of placeholder object.
 * @param superTypes super types of placeholder, this placeholder may use placeholder items from this types.
 */
public PlaceholderType(final String id, final Class<T> type,
        final Collection<PlaceholderType<? super T>> superTypes) {
    this.id = id.intern();
    this.type = type;
    this.superTypes = new HashSet<>(superTypes);
}

From source file:org.apache.fop.fo.ElementMappingRegistry.java

/**
 * Finds the Maker used to create node objects of a particular type
 * @param namespaceURI URI for the namespace of the element
 * @param localName name of the Element/*from w w  w. j  av a2  s  .c o  m*/
 * @param locator the Locator instance for context information
 * @return the ElementMapping.Maker that can create an FO object for this element
 * @throws FOPException if a Maker could not be found for a bound namespace.
 */
public Maker findFOMaker(String namespaceURI, String localName, Locator locator) throws FOPException {
    Map<String, Maker> table = fobjTable.get(namespaceURI);
    Maker fobjMaker = null;
    if (table != null) {
        fobjMaker = table.get(localName);
        // try default
        if (fobjMaker == null) {
            fobjMaker = table.get(ElementMapping.DEFAULT);
        }
    }

    if (fobjMaker == null) {
        if (namespaces.containsKey(namespaceURI.intern())) {
            throw new FOPException(FONode.errorText(locator) + "No element mapping definition found for "
                    + FONode.getNodeString(namespaceURI, localName), locator);
        } else {
            fobjMaker = new UnknownXMLObj.Maker(namespaceURI);
        }
    }
    return fobjMaker;
}