Example usage for java.util HashMap remove

List of usage examples for java.util HashMap remove

Introduction

In this page you can find the example usage for java.util HashMap remove.

Prototype

public V remove(Object key) 

Source Link

Document

Removes the mapping for the specified key from this map if present.

Usage

From source file:com.mobileman.moments.core.security.UserSecurityService.java

private void sanitizeUserCacheInfo(UserCacheInfo userCacheInfo) {
    if (false) {/* www.  j a v  a2s  .c o  m*/
        HashMap<String, Date> tokens = userCacheInfo.getTokens();
        if (tokens.size() > 10) {
            tokens.clear(); // Protection against too many devices
        }
        // remove older items
        Date now = DateUtils.addSeconds(new Date(), -60 * 10);
        HashSet<String> ks = new HashSet<String>(tokens.keySet());
        for (String key : ks) {
            Date d = tokens.get(key);
            if (now.after(d)) {
                tokens.remove(key);
            }
        }
    }
}

From source file:gov.nih.nci.cabig.caaers.service.synchronizer.StudyOrganizationSynchronizer.java

private void syncStudyPersonnels(StudyOrganization dbStudyOrganization, StudyOrganization xmlStudyOrganization,
        Organization organization, DomainObjectImportOutcome<Study> studyImportOutcome) {

    //do nothing if there is no personnel in the xmlStudy Organization
    if (CollectionUtils.isEmpty(xmlStudyOrganization.getStudyPersonnels())) {
        return;/*from w w  w  .  j a v  a 2  s .co  m*/
    }

    //generate and index of existing study StudyPersonnel
    HashMap<String, StudyPersonnel> dbStudyPersonnelIndexMap = new HashMap<String, StudyPersonnel>();
    for (StudyPersonnel sp : dbStudyOrganization.getStudyPersonnels()) {
        dbStudyPersonnelIndexMap.put(generateIndexKey(sp), sp);
    }

    //loop through xmlStudy Organization StudyPersonnel, then add and modify details
    for (StudyPersonnel xmlSp : xmlStudyOrganization.getStudyPersonnels()) {
        StudyPersonnel sp = dbStudyPersonnelIndexMap.remove(generateIndexKey(xmlSp));
        if (sp == null) {
            //new one so add it to Study
            dbStudyOrganization.addStudyPersonnel(xmlSp);
            continue;
        }
        //update existing study personnel
        sp.setEndDate(xmlSp.getEndDate());
        sp.setStartDate(xmlSp.getStartDate());
        sp.setRoleCode(xmlSp.getRoleCode());
    }

    //deactivate the study staff which are not present in xmlStudy Organization
    for (StudyPersonnel sp : dbStudyPersonnelIndexMap.values()) {
        sp.deactivate();
    }

}

From source file:blusunrize.immersiveengineering.api.ApiUtils.java

private static boolean handlePos(Vec3d pos, BlockPos posB, HashMap<BlockPos, Vec3d> halfScanned,
        HashSet<BlockPos> done, Predicate<Triple<BlockPos, Vec3d, Vec3d>> shouldStop,
        HashSet<Triple<BlockPos, Vec3d, Vec3d>> near) {
    final double DELTA_NEAR = .3;
    if (!done.contains(posB)) {
        if (halfScanned.containsKey(posB) && !pos.equals(halfScanned.get(posB))) {
            Triple<BlockPos, Vec3d, Vec3d> added = new ImmutableTriple<>(posB, halfScanned.get(posB), pos);
            boolean stop = shouldStop.test(added);
            done.add(posB);/*from w w  w .  j a  va 2  s .  com*/
            halfScanned.remove(posB);
            near.removeIf((t) -> t.getLeft().equals(posB));
            if (stop)
                return true;
            for (int i = 0; i < 3; i++) {
                double coord = getDim(pos, i);
                double diff = coord - Math.floor(coord);
                if (diff < DELTA_NEAR)
                    near.add(
                            new ImmutableTriple<>(offsetDim(posB, i, -1), added.getMiddle(), added.getRight()));
                diff = Math.ceil(coord) - coord;
                if (diff < DELTA_NEAR)
                    near.add(new ImmutableTriple<>(offsetDim(posB, i, 1), added.getMiddle(), added.getRight()));
            }
        } else {
            halfScanned.put(posB, pos);
        }
    }
    return false;
}

From source file:org.nuxeo.ecm.platform.semanticentities.sources.StanbolEntityHubSource.java

@SuppressWarnings("unchecked")
@Override//from w  w w .j ava 2 s .  co  m
public boolean dereferenceInto(DocumentModel localEntity, URI remoteEntity, boolean override,
        boolean lazyResourceFetch) throws DereferencingException {
    Map<String, Object> representation = Collections.emptyMap();
    try {
        Map<String, Object> jsonDescription = fetchJSONDescription(remoteEntity);
        representation = (Map<String, Object>) jsonDescription.get("representation");
        if (representation == null) {
            throw new DereferencingException("Invalid JSON response from Stanbol server:"
                    + " missing 'representation' key: " + mapper.writeValueAsString(jsonDescription));
        }
        Set<String> possibleTypes = getAdmissibleTypes(representation);
        if (!possibleTypes.contains(localEntity.getType())) {
            throw new DereferencingException(
                    String.format("Remote entity '%s' can be mapped to types:" + " ('%s') but not to '%s'",
                            remoteEntity, StringUtils.join(possibleTypes, "', '"), localEntity.getType()));
        }
        // special handling for the entity:sameas property
        // XXX: the following code should be factorized somewhere
        List<String> samesas = new ArrayList<String>();
        List<String> sameasDisplayLabel = new ArrayList<String>();
        Property sameasProp = localEntity.getProperty("entity:sameas");
        if (sameasProp.getValue() != null) {
            samesas.addAll(sameasProp.getValue(List.class));
        }
        Property sameasDisplayLabelProp = localEntity.getProperty("entity:sameasDisplayLabel");
        if (sameasDisplayLabelProp.getValue() != null) {
            sameasDisplayLabel.addAll(sameasDisplayLabelProp.getValue(List.class));
        }
        if (!samesas.contains(remoteEntity.toString())) {
            samesas.add(remoteEntity.toString());
            localEntity.setPropertyValue("entity:sameas", (Serializable) samesas);

            String titlePropUri = descriptor.getMappedProperties().get("dc:title");
            String label = localEntity.getTitle();
            label = label != null ? label : "Missing label";
            if (titlePropUri != null) {
                String labelFromRDF = readDecodedLiteral(representation, titlePropUri, StringType.INSTANCE,
                        "en").toString();
                label = labelFromRDF != null ? labelFromRDF : label;
            }
            sameasDisplayLabel.add(label);
            localEntity.setPropertyValue("entity:sameasDisplayLabel", (Serializable) sameasDisplayLabel);
        }
    } catch (DereferencingException e) {
        throw e;
    } catch (Exception e) {
        throw new DereferencingException(e);
    }
    HashMap<String, String> mapping = new HashMap<String, String>(descriptor.getMappedProperties());
    // as sameas has a special handling, remove it from the list of
    // properties to synchronize the generic way
    mapping.remove("entity:sameas");

    // generic handling of mapped properties
    for (Entry<String, String> mappedProperty : mapping.entrySet()) {
        String localPropertyName = mappedProperty.getKey();
        String remotePropertyUri = mappedProperty.getValue();
        try {
            Property localProperty = localEntity.getProperty(localPropertyName);
            Type type = localProperty.getType();
            if (type.isListType()) {
                // only synchronize string lists right now
                List<String> newValues = new ArrayList<String>();
                if (localProperty.getValue() != null) {
                    newValues.addAll(localProperty.getValue(List.class));
                }
                if (override) {
                    newValues.clear();
                }
                for (String value : readStringList(representation, remotePropertyUri)) {
                    if (!newValues.contains(value)) {
                        newValues.add(value);
                    }
                }
                localEntity.setPropertyValue(localPropertyName, (Serializable) newValues);
            } else {
                if (localProperty.getValue() == null || "".equals(localProperty.getValue()) || override) {
                    if (type.isComplexType() && "content".equals(type.getName())) {
                        if (lazyResourceFetch) {
                            // TODO: store the resource and property
                            // info in a DocumentModel context data entry to
                            // be used later by the entity serializer
                        } else {
                            Serializable linkedResource = readLinkedResource(representation, remotePropertyUri);
                            if (linkedResource != null) {
                                localEntity.setPropertyValue(localPropertyName, linkedResource);
                            }
                        }
                    } else {
                        Serializable literal = readDecodedLiteral(representation, remotePropertyUri, type,
                                "en");
                        if (literal != null) {
                            localEntity.setPropertyValue(localPropertyName, literal);
                        }
                    }
                }
            }
        } catch (PropertyException e) {
            // ignore missing properties
        } catch (ClientException e) {
            throw new DereferencingException(e);
        }
    }
    return true;
}

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

/**
 * Delete all slot associations with a given queue. This is required to handle a queue purge event.
 *
 * @param queueName name of destination queue
 *//*  ww w  .  j a  va 2  s  .c o m*/
public void clearAllActiveSlotRelationsToQueue(String queueName) {

    if (null != unAssignedSlotMap) {
        unAssignedSlotMap.remove(queueName);
    }

    if (null != slotIDMap) {
        slotIDMap.remove(queueName);
    }

    // Clear slots assigned to the queue
    if (AndesContext.getInstance().isClusteringEnabled()) {
        String nodeId = HazelcastAgent.getInstance().getNodeId();

        // The requirement here is to clear slot associations for the queue on all nodes.
        List<String> nodeIDs = HazelcastAgent.getInstance().getMembersNodeIDs();

        for (String nodeID : nodeIDs) {
            String lockKey = nodeID + SlotManager.class;

            synchronized (lockKey.intern()) {
                HashmapStringListWrapper wrapper = slotAssignmentMap.get(nodeId);
                HashMap<String, List<String>> queueToSlotMap = null;
                if (wrapper != null) {
                    queueToSlotMap = wrapper.getStringListHashMap();
                }
                if (queueToSlotMap != null) {
                    queueToSlotMap.remove(queueName);
                    wrapper.setStringListHashMap(queueToSlotMap);
                    slotAssignmentMap.set(nodeId, wrapper);
                }
            }
        }
    }

}

From source file:gov.nih.nci.cabig.caaers.service.synchronizer.StudyOrganizationSynchronizer.java

private void syncStudyInvestigators(StudyOrganization dbStudyOrganization,
        StudyOrganization xmlStudyOrganization, Organization organization,
        DomainObjectImportOutcome<Study> studyImportOutcome) {

    //do nothing if there is no investigator in the xmlStudy Organization
    if (CollectionUtils.isEmpty(xmlStudyOrganization.getStudyInvestigators())) {
        return;/* ww  w .j a v a 2s  .c o  m*/
    }

    //generate and index of existing study investigators
    HashMap<String, StudyInvestigator> dbStudyInvIndexMap = new HashMap<String, StudyInvestigator>();
    for (StudyInvestigator si : dbStudyOrganization.getStudyInvestigators()) {
        dbStudyInvIndexMap.put(generateIndexKey(si), si);
    }

    //loop through xmlStudy Organization StudyInvestigators, then add and modify details
    for (StudyInvestigator xmlSi : xmlStudyOrganization.getStudyInvestigators()) {
        StudyInvestigator si = dbStudyInvIndexMap.remove(generateIndexKey(xmlSi));
        if (si == null) {
            //new one so add it to Study
            dbStudyOrganization.addStudyInvestigators(xmlSi);
            continue;
        }
        //update existing investigator
        si.setEndDate(xmlSi.getEndDate());
        si.setStartDate(xmlSi.getStartDate());
        si.setRoleCode(xmlSi.getRoleCode());
    }

    //deactivate the study investigators which are not present in xmlStudy Organization
    for (StudyInvestigator si : dbStudyInvIndexMap.values()) {
        si.deactivate();
    }

}

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

/**
 * Re-assign the slot when there are no local subscribers in the node
 *
 * @param nodeId    node ID of the node without subscribers
 * @param queueName name of the queue whose slots to be reassigned
 *///from   ww w . j  a  v a  2 s.c  om
public void reAssignSlotWhenNoSubscribers(String nodeId, String queueName) {
    ArrayList<String> assignedSlotList = null;
    String lockKeyForNodeId = nodeId + SlotManager.class;
    synchronized (lockKeyForNodeId.intern()) {
        HashmapStringListWrapper wrapper = slotAssignmentMap.get(nodeId);
        HashMap<String, List<String>> queueToSlotMap = null;
        if (wrapper != null) {
            queueToSlotMap = wrapper.getStringListHashMap();
        }
        if (queueToSlotMap != null) {
            assignedSlotList = (ArrayList<String>) queueToSlotMap.remove(queueName);
            wrapper.setStringListHashMap(queueToSlotMap);
            slotAssignmentMap.set(nodeId, wrapper);
        }
    }
    if (assignedSlotList != null && !assignedSlotList.isEmpty()) {
        String lockKeyForQueueName = queueName + SlotManager.class;
        synchronized (lockKeyForQueueName.intern()) {
            TreeSetStringWrapper treeSetStringWrapper = unAssignedSlotMap.get(queueName);

            TreeSet<String> unAssignedSlotSet = new TreeSet<String>();
            if (treeSetStringWrapper != null) {
                unAssignedSlotSet = treeSetStringWrapper.getStringTreeSet();
            } else {
                treeSetStringWrapper = new TreeSetStringWrapper();
            }
            if (unAssignedSlotSet == null) {
                unAssignedSlotSet = new TreeSet<String>();
            }
            for (String slotToBeReAssignedString : assignedSlotList) {
                Gson gson = new GsonBuilder().create();
                Slot slotToBeReAssigned = gson.fromJson(slotToBeReAssignedString, (Type) Slot.class);
                //Reassign only if the slot is not empty
                if (!SlotUtils.checkSlotEmptyFromMessageStore(slotToBeReAssigned)) {
                    unAssignedSlotSet.add(slotToBeReAssignedString);
                }
            }
            treeSetStringWrapper.setStringTreeSet(unAssignedSlotSet);
            unAssignedSlotMap.set(queueName, treeSetStringWrapper);
        }
    }
}

From source file:edu.caltech.ipac.firefly.server.util.ipactable.DataGroupReader.java

public static DataGroup getEnumValues(File inf, int cutoffPoint) throws IOException {

    TableDef tableMeta = IpacTableUtil.getMetaInfo(inf);
    List<DataType> cols = tableMeta.getCols();

    HashMap<DataType, List<String>> enums = new HashMap<DataType, List<String>>();
    ArrayList<DataType> workList = new ArrayList<DataType>();

    for (DataType dt : cols) {
        if (dt.getDataType().isAssignableFrom(Float.class) || dt.getDataType().isAssignableFrom(Double.class)) {
            continue;
        }//from www.j  ava  2 s  .  com
        enums.put(dt, new ArrayList<String>());
        workList.add(dt);
    }
    DataGroup dg = new DataGroup(null, cols);

    BufferedReader reader = new BufferedReader(new FileReader(inf), IpacTableUtil.FILE_IO_BUFFER_SIZE);
    String line = null;
    int lineNum = 0;
    try {
        line = reader.readLine();
        lineNum++;
        while (line != null) {
            DataObject row = IpacTableUtil.parseRow(dg, line, false);
            if (row != null) {
                List<DataType> ccols = new ArrayList<DataType>(workList);
                for (DataType dt : ccols) {
                    String v = String.valueOf(row.getDataElement(dt));
                    List<String> l = enums.get(dt);
                    if (l == null || l.size() >= cutoffPoint
                            || (dt.getDataType().isAssignableFrom(String.class) && v.length() > 20)) {
                        workList.remove(dt);
                        enums.remove(dt);
                    } else if (!l.contains(v)) {
                        l.add(v);
                    }
                }
            }
            line = reader.readLine();
            lineNum++;
            if (enums.size() == 0) {
                break;
            }
        }
    } catch (Exception e) {
        String msg = e.getMessage() + "<br>on line " + lineNum + ": " + line;
        if (msg.length() > 128)
            msg = msg.substring(0, 128) + "...";
        logger.error(e, "on line " + lineNum + ": " + line);
        throw new IOException(msg);
    } finally {
        reader.close();
    }

    if (enums.size() > 0) {
        for (DataType dt : enums.keySet()) {
            List<String> values = enums.get(dt);
            Collections.sort(values, DataGroupUtil.getComparator(dt));
            dg.addAttribute(
                    TemplateGenerator.createAttributeKey(TemplateGenerator.Tag.ITEMS_TAG, dt.getKeyName()),
                    StringUtils.toString(values, ","));
        }
    }

    return dg;
}

From source file:org.sakaiproject.tool.assessment.ui.listener.author.SavePartListener.java

private void updateAttachment(List oldList, List newList, SectionDataIfc section) {
    if ((oldList == null || oldList.size() == 0) && (newList == null || newList.size() == 0))
        return;/* w  w w .j a  va2  s .  co m*/
    List list = new ArrayList();
    HashMap map = getAttachmentIdHash(oldList);
    for (int i = 0; i < newList.size(); i++) {
        SectionAttachmentIfc a = (SectionAttachmentIfc) newList.get(i);
        if (map.get(a.getAttachmentId()) != null) {
            // exist already, remove it from map
            map.remove(a.getAttachmentId());
        } else {
            // new attachments
            a.setSection(section);
            list.add(a);
        }
    }
    // save new ones
    AssessmentService assessmentService = null;
    if (isEditPendingAssessmentFlow) {
        assessmentService = new AssessmentService();
    } else {
        assessmentService = new PublishedAssessmentService();
    }
    assessmentService.saveOrUpdateAttachments(list);

    // remove old ones
    Set set = map.keySet();
    Iterator iter = set.iterator();
    while (iter.hasNext()) {
        Long attachmentId = (Long) iter.next();
        assessmentService.removeSectionAttachment(attachmentId.toString());
    }
}

From source file:org.graylog.plugins.nats.output.AbstractGelfNatsOutput.java

protected byte[] toGELFMessage(final Message message) throws IOException {
    final HashMap<String, Object> fields = new HashMap<>(message.getFields());

    final ByteArrayOutputStream outputStream = new ByteArrayOutputStream(512);
    final JsonFactory jsonFactory = new JsonFactory();
    final JsonGenerator generator = jsonFactory.createGenerator(outputStream);
    generator.writeStartObject();//from www .  ja v  a  2 s . com
    generator.writeStringField("version", "1.1");
    generator.writeStringField("host", (String) fields.remove(Message.FIELD_SOURCE));
    generator.writeStringField("short_message", (String) fields.remove(Message.FIELD_MESSAGE));

    final String fullMessage = (String) fields.remove(Message.FIELD_FULL_MESSAGE);
    if (fullMessage != null) {
        generator.writeStringField("full_message", fullMessage);
    }

    final Object fieldTimeStamp = fields.remove(Message.FIELD_TIMESTAMP);
    final DateTime timestamp;
    if (fieldTimeStamp instanceof DateTime) {
        timestamp = (DateTime) fieldTimeStamp;
    } else {
        timestamp = Tools.nowUTC();
    }
    generator.writeNumberField("timestamp", timestamp.getMillis() / 1000d);

    final Object fieldLevel = fields.remove(Message.FIELD_TIMESTAMP);
    final Integer level = extractLevel(fieldLevel);
    if (level != null) {
        generator.writeNumberField("level", level);
    }

    for (Map.Entry<String, Object> field : fields.entrySet()) {
        final String key = field.getKey();
        final Object value = field.getValue();

        if (value instanceof String) {
            generator.writeStringField(key, (String) value);
        } else if (value instanceof Boolean) {
            generator.writeBooleanField(key, (Boolean) value);
        } else if (value instanceof Integer) {
            generator.writeNumberField(key, (Integer) value);
        } else if (value instanceof Long) {
            generator.writeNumberField(key, (Long) value);
        } else if (value instanceof Float) {
            generator.writeNumberField(key, (Float) value);
        } else if (value instanceof Double) {
            generator.writeNumberField(key, (Double) value);
        } else if (value instanceof BigDecimal) {
            generator.writeNumberField(key, (BigDecimal) value);
        } else if (value == null) {
            generator.writeNullField(key);
        }
    }

    generator.writeStringField("_forwarder_cluster_id", clusterId);
    generator.writeStringField("_forwarder_node_id", nodeId);

    generator.writeEndObject();

    generator.flush();

    return outputStream.toByteArray();
}