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.wso2.andes.kernel.slot.SlotManagerClusterMode.java

/**
 * Record Slot's last message ID related to a particular queue
 *
 * @param queueName               name of the queue which this message ID belongs to
 * @param lastMessageIdInTheSlot  last message ID of the slot
 * @param startMessageIdInTheSlot start message ID of the slot
 * @param nodeId                  Node ID of the node that is sending the request.
 * @param localSafeZone           Local safe zone of the requesting node.
 *///from  w  w w .  j  a  v a  2  s. c o  m
public void updateMessageID(String queueName, String nodeId, long startMessageIdInTheSlot,
        long lastMessageIdInTheSlot, long localSafeZone) throws AndesException {

    //setting up first message id of the slot
    if (firstMessageId > startMessageIdInTheSlot || firstMessageId == -1) {
        firstMessageId = startMessageIdInTheSlot;
    }

    if (slotRecoveryScheduled.get()) {
        queuesToRecover.remove(queueName);
    }

    // Read message Id set for slots from store
    TreeSet<Long> messageIdSet;
    messageIdSet = slotAgent.getSlotBasedMessageIds(queueName);

    String lockKey = queueName + SlotManagerClusterMode.class;
    synchronized (lockKey.intern()) {
        //Get last assigned message id from database
        long lastAssignedMessageId = slotAgent.getQueueToLastAssignedId(queueName);

        // Check if input slot's start message ID is less than last assigned message ID
        if (startMessageIdInTheSlot < lastAssignedMessageId) {
            if (log.isDebugEnabled()) {
                log.debug("Found overlapping slots during slot submit: " + startMessageIdInTheSlot + " to : "
                        + lastMessageIdInTheSlot + ". Comparing to lastAssignedID : " + lastAssignedMessageId);
            }
            // Find overlapping slots
            TreeSet<Slot> overlappingSlots = getOverlappedAssignedSlots(queueName, startMessageIdInTheSlot,
                    lastMessageIdInTheSlot);

            if (!(overlappingSlots.isEmpty())) {

                if (log.isDebugEnabled()) {
                    log.debug("Found " + overlappingSlots.size() + " overlapping slots.");
                }
                // Following means that we have a piece of the slot exceeding the earliest
                // assigned slot. breaking that piece and adding it as a new,unassigned slot.
                if (startMessageIdInTheSlot < overlappingSlots.first().getStartMessageId()) {
                    Slot leftExtraSlot = new Slot(startMessageIdInTheSlot,
                            overlappingSlots.first().getStartMessageId() - 1, queueName);
                    if (log.isDebugEnabled()) {
                        log.debug("Left Extra Slot in overlapping slots : " + leftExtraSlot);
                    }
                }
                // This means that we have a piece of the slot exceeding the latest assigned slot.
                // breaking that piece and adding it as a new,unassigned slot.
                if (lastMessageIdInTheSlot > overlappingSlots.last().getEndMessageId()) {
                    Slot rightExtraSlot = new Slot(overlappingSlots.last().getEndMessageId() + 1,
                            lastMessageIdInTheSlot, queueName);

                    if (log.isDebugEnabled()) {
                        log.debug("RightExtra in overlapping slot : " + rightExtraSlot);
                    }
                    //Update last message ID - expand ongoing slot to cater this leftover part.
                    slotAgent.addMessageId(queueName, lastMessageIdInTheSlot);

                    if (log.isDebugEnabled()) {
                        log.debug(lastMessageIdInTheSlot + " added to store "
                                + "(RightExtraSlot). Current values in " + "store " + messageIdSet);
                    }
                }
            } else {
                /*
                 * The fact that the slot ended up in this condition means that, all previous slots within this
                * range have been already processed and deleted. This is a very rare scenario.
                */
                if (log.isDebugEnabled()) {
                    log.debug("A submit slot request has come from the past after deletion of any "
                            + "possible overlapping slots. nodeId : " + nodeId + " StartMessageID : "
                            + startMessageIdInTheSlot + " EndMessageID : " + lastMessageIdInTheSlot);
                }

                slotAgent.addMessageId(queueName, lastMessageIdInTheSlot);
            }
        } else {
            //Update the store only if the last assigned message ID is less than the new start message ID
            slotAgent.addMessageId(queueName, lastMessageIdInTheSlot);

            if (log.isDebugEnabled()) {
                log.debug("No overlapping slots found during slot submit " + startMessageIdInTheSlot + " to : "
                        + lastMessageIdInTheSlot + ". Added msgID " + lastMessageIdInTheSlot + " to store");
            }
        }
        //record local safe zone
        slotAgent.setLocalSafeZoneOfNode(nodeId, localSafeZone);
    }
}

From source file:org.opennms.netmgt.xml.eventconf.Maskelement.java

/**
 * //from www .  j  av a2  s  . c o m
 * 
 * @param index
 * @param vMevalue
 * @throws IndexOutOfBoundsException if the index
 * given is outside the bounds of the collection
 */
public void setMevalue(final int index, final String vMevalue) throws IndexOutOfBoundsException {
    // check bounds for index
    if (index < 0 || index >= this.m_mevalueList.size()) {
        throw new IndexOutOfBoundsException("setMevalue: Index value '" + index + "' not in range [0.."
                + (this.m_mevalueList.size() - 1) + "]");
    }

    this.m_mevalueList.set(index, vMevalue.intern());
}

From source file:org.apache.axis.utils.NSStack.java

/**
 * Return an active prefix for the given namespaceURI.  NOTE : This
 * may return null even if the namespaceURI was actually mapped further
 * up the stack IF the prefix which was used has been repeated further
 * down the stack.  I.e.:/*w  ww.j a  va  2  s.com*/
 * 
 * <pre:outer xmlns:pre="namespace">
 *   <pre:inner xmlns:pre="otherNamespace">
 *      *here's where we're looking*
 *   </pre:inner>
 * </pre:outer>
 * 
 * If we look for a prefix for "namespace" at the indicated spot, we won't
 * find one because "pre" is actually mapped to "otherNamespace"
 */
public String getPrefix(String namespaceURI, boolean noDefault) {
    if ((namespaceURI == null) || (namespaceURI.length() == 0))
        return null;

    if (optimizePrefixes) {
        // If defaults are OK, and the given NS is the current default,
        // return "" as the prefix to favor defaults where possible.
        if (!noDefault && currentDefaultNS > 0 && stack[currentDefaultNS] != null
                && namespaceURI == stack[currentDefaultNS].getNamespaceURI())
            return "";
    }
    namespaceURI = namespaceURI.intern();

    for (int cursor = top; cursor > 0; cursor--) {
        Mapping map = stack[cursor];
        if (map == null)
            continue;

        if (map.getNamespaceURI() == namespaceURI) {
            String possiblePrefix = map.getPrefix();
            if (noDefault && possiblePrefix.length() == 0)
                continue;

            // now make sure that this is the first occurance of this 
            // particular prefix
            for (int cursor2 = top; true; cursor2--) {
                if (cursor2 == cursor)
                    return possiblePrefix;
                map = stack[cursor2];
                if (map == null)
                    continue;
                if (possiblePrefix == map.getPrefix())
                    break;
            }
        }
    }

    return null;
}

From source file:org.apache.xmlgraphics.image.loader.cache.ImageCache.java

/**
 * Returns an ImageInfo instance for a given URI.
 * @param uri the image's URI/*from   w  w w.  ja  v a  2s  .  c o  m*/
 * @param session the session context
 * @param manager the ImageManager handling the images
 * @return the ImageInfo instance
 * @throws ImageException if an error occurs while parsing image data
 * @throws IOException if an I/O error occurs while loading image data
 */
public ImageInfo needImageInfo(String uri, ImageSessionContext session, ImageManager manager)
        throws ImageException, IOException {
    //Fetch unique version of the URI and use it for synchronization so we have some sort of
    //"row-level" locking instead of "table-level" locking (to use a database analogy).
    //The fine locking strategy is necessary since preloading an image is a potentially long
    //operation.
    if (isInvalidURI(uri)) {
        throw new FileNotFoundException("Image not found: " + uri);
    }
    String lockURI = uri.intern();
    synchronized (lockURI) {
        ImageInfo info = getImageInfo(uri);
        if (info == null) {
            try {
                Source src = session.needSource(uri);
                if (src == null) {
                    registerInvalidURI(uri);
                    throw new FileNotFoundException("Image not found: " + uri);
                }
                info = manager.preloadImage(uri, src);
                session.returnSource(uri, src);
            } catch (IOException ioe) {
                registerInvalidURI(uri);
                throw ioe;
            } catch (ImageException e) {
                registerInvalidURI(uri);
                throw e;
            }
            putImageInfo(info);
        }
        return info;
    }
}

From source file:org.wso2.andes.kernel.slot.SlotManager.java

/**
 * Get an overlapped slot by nodeId and the queue name. These are slots
 * which are overlapped with some slots that were acquired by given node
 *
 * @param nodeId    id of the node// w w  w  .j  a  v  a2s .c  om
 * @param queueName name of the queue slot is required
 * @return slot or null if not found
 */
private Slot getOverlappedSlot(String nodeId, String queueName) {
    Slot slotToBeAssigned = null;
    TreeSet<Slot> currentSlotList;
    HashMap<String, TreeSet<Slot>> queueToSlotMap;
    HashmapStringTreeSetWrapper wrapper = overLappedSlotMap.get(nodeId);

    String lockKey = nodeId + SlotManager.class;

    synchronized (lockKey.intern()) {
        if (null != wrapper) {
            queueToSlotMap = wrapper.getStringListHashMap();
            currentSlotList = queueToSlotMap.get(queueName);
            if (null != currentSlotList && !currentSlotList.isEmpty()) {
                //get and remove slot
                slotToBeAssigned = currentSlotList.pollFirst();
                queueToSlotMap.put(queueName, currentSlotList);
                //update hazelcast map
                wrapper.setStringListHashMap(queueToSlotMap);
                overLappedSlotMap.set(nodeId, wrapper);
                if (log.isDebugEnabled()) {
                    log.debug("Slot Manager - giving a slot from overlapped slot pool. Slot= "
                            + slotToBeAssigned);
                }
            }
        }
    }
    return slotToBeAssigned;
}

From source file:org.wso2.andes.kernel.slot.SlotManager.java

/**
 * Get an unassigned slot (slots dropped by sudden subscription closes)
 *
 * @param queueName name of the queue slot is required
 * @return slot or null if cannot find//w w w. jav a 2s.  c o  m
 */
private Slot getUnassignedSlot(String queueName) {
    Slot slotToBeAssigned = null;

    String lockKey = queueName + SlotManager.class;

    synchronized (lockKey.intern()) {

        TreeSetSlotWrapper unAssignedSlotWrapper = unAssignedSlotMap.get(queueName);

        if (unAssignedSlotWrapper != null) {
            TreeSet<Slot> slotsFromUnassignedSlotMap = unAssignedSlotWrapper.getSlotTreeSet();
            if (slotsFromUnassignedSlotMap != null && !slotsFromUnassignedSlotMap.isEmpty()) {

                //Get and remove slot and update hazelcast map
                slotToBeAssigned = slotsFromUnassignedSlotMap.pollFirst();
                unAssignedSlotWrapper.setSlotTreeSet(slotsFromUnassignedSlotMap);
                unAssignedSlotMap.set(queueName, unAssignedSlotWrapper);

                if (log.isDebugEnabled()) {
                    log.debug("Slot Manager - giving a slot from unAssignedSlotMap. Slot= " + slotToBeAssigned);
                }
            }
        }
    }
    return slotToBeAssigned;
}

From source file:SymbolTable.java

/**
 * Main access method; will check if actual symbol String exists;
 * if so, returns it; if not, will create, add and return it.
 *
 * @return The symbol matching String in input array
 *///from  w  ww. jav a 2  s .co  m
/*
public String findSymbol(char[] buffer, int start, int len)
{
return findSymbol(buffer, start, len, calcHash(buffer, start, len));
}
*/

public String findSymbol(char[] buffer, int start, int len, int hash) {
    // Sanity check:
    if (len < 1) {
        return EMPTY_STRING;
    }

    hash &= mIndexMask;

    String sym = mSymbols[hash];

    // 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;
            do {
                if (sym.charAt(i) != buffer[start + i]) {
                    break;
                }
            } while (++i < len);
            // Optimal case; primary match found
            if (i == len) {
                return sym;
            }
        }
        // How about collision bucket?
        Bucket b = mBuckets[hash >> 1];
        if (b != null) {
            sym = b.find(buffer, start, len);
            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)
         */
        hash = calcHash(buffer, start, len) & mIndexMask;
    } else if (!mDirty) {
        // Or perhaps we need to do copy-on-write?
        copyArrays();
        mDirty = true;
    }
    ++mSize;

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

    return newSymbol;
}

From source file:org.wso2.andes.kernel.slot.SlotManager.java

/**
 * Update the slot assignment map when a slot is assigned for a node
 *
 * @param queueName     Name of the queue
 * @param allocatedSlot Slot object which is allocated to a particular node
 * @param nodeId        ID of the node to which slot is Assigned
 *///from   w  w w .ja v  a  2  s.c o m
private void updateSlotAssignmentMap(String queueName, Slot allocatedSlot, String nodeId) {
    TreeSet<Slot> currentSlotList;
    HashMap<String, TreeSet<Slot>> queueToSlotMap;

    //Lock is used because this method will be called by multiple nodes at the same time
    String lockKey = nodeId + SlotManager.class;
    synchronized (lockKey.intern()) {

        HashmapStringTreeSetWrapper wrapper = slotAssignmentMap.get(nodeId);
        if (wrapper == null) {
            wrapper = new HashmapStringTreeSetWrapper();
            queueToSlotMap = new HashMap<String, TreeSet<Slot>>();
            wrapper.setStringListHashMap(queueToSlotMap);
            slotAssignmentMap.putIfAbsent(nodeId, wrapper);
        }

        wrapper = slotAssignmentMap.get(nodeId);
        queueToSlotMap = wrapper.getStringListHashMap();
        currentSlotList = queueToSlotMap.get(queueName);
        if (currentSlotList == null) {
            currentSlotList = new TreeSet<Slot>();
        }

        //update slot state
        if (allocatedSlot.addState(SlotState.ASSIGNED)) {
            //remove any similar slot from hazelcast and add the updated one
            currentSlotList.remove(allocatedSlot);
            currentSlotList.add(allocatedSlot);
            queueToSlotMap.put(queueName, currentSlotList);
            wrapper.setStringListHashMap(queueToSlotMap);
            slotAssignmentMap.set(nodeId, wrapper);
        }
    }
}

From source file:org.wso2.andes.kernel.slot.SlotManager.java

/**
 * Get a slot by giving the queue name. This method first lookup the free slot pool for slots
 * and if there are no slots in the free slot pool then return a newly created slot
 *
 * @param queueName name of the queue/* ww  w.  j ava  2s . c om*/
 * @return Slot object
 */
public Slot getSlot(String queueName, String nodeId) {

    Slot slotToBeAssigned;

    /**
     *First look in the unassigned slots pool for free slots. These slots are previously own by
     * other nodes
     */
    String lockKey = queueName + SlotManager.class;

    synchronized (lockKey.intern()) {
        slotToBeAssigned = getOverlappedSlot(nodeId, queueName);

        if (null == slotToBeAssigned) {
            slotToBeAssigned = getUnassignedSlot(queueName);
        }
        if (null == slotToBeAssigned) {
            slotToBeAssigned = getFreshSlot(queueName);
        }
    }

    if (null != slotToBeAssigned) {
        updateSlotAssignmentMap(queueName, slotToBeAssigned, nodeId);
        if (log.isDebugEnabled()) {
            log.debug("Assigning slot for node : " + nodeId + " ||| " + slotToBeAssigned);
        }
    } else {
        if (log.isDebugEnabled()) {
            log.debug("Slot Manager - returns empty slot for the queue: " + queueName);
        }
    }

    return slotToBeAssigned;

}

From source file:org.madsonic.controller.CoverArtController.java

private File getCachedImage(CoverArtRequest request, int size) throws IOException {
    String hash = DigestUtils.md5Hex(request.getKey());
    String encoding = request.getCoverArt() != null ? "jpeg" : "png";
    File cachedImage = new File(getImageCacheDirectory(size), hash + "." + encoding);

    // Synchronize to avoid concurrent writing to the same file.
    synchronized (hash.intern()) {

        // Is cache missing or obsolete?
        if (!cachedImage.exists() || request.lastModified() > cachedImage.lastModified()) {
            //                LOG.info("Cache MISS - " + request + " (" + size + ")");
            OutputStream out = null;
            try {
                BufferedImage image = request.createImage(size);
                if (image == null) {
                    throw new Exception("Unable to decode image.");
                }/* ww w  .  j a  v a2  s. c om*/
                out = new FileOutputStream(cachedImage);
                ImageIO.write(image, encoding, out);

            } catch (Throwable x) {
                // Delete corrupt (probably empty) thumbnail cache.
                LOG.warn("Failed to create thumbnail for " + request, x);
                IOUtils.closeQuietly(out);
                cachedImage.delete();
                throw new IOException("Failed to create thumbnail for " + request + ". " + x.getMessage());

            } finally {
                IOUtils.closeQuietly(out);
            }
        } else {
            //                LOG.info("Cache HIT - " + request + " (" + size + ")");
        }
        return cachedImage;
    }
}