Java Code Examples for java.util.Map#remove()

The following examples show how to use java.util.Map#remove() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: PendingAsyncOperations.java    From flink-statefun with Apache License 2.0 6 votes vote down vote up
/**
 * Removes the completed async operation.
 *
 * <p>NOTE: this method should be called with {@link
 * org.apache.flink.statefun.flink.core.state.State#setCurrentKey(Address)} set on the
 * owningAddress. This should be the case as it is called by {@link
 * AsyncMessageDecorator#postApply()}.
 */
void remove(Address owningAddress, long futureId) {
  Map<Long, Message> asyncOps = memoryStore.get(owningAddress);
  if (asyncOps == null) {
    // there are no async operations in the memory store,
    // therefore it must have been previously flushed to the backing store.
    removeFromTheBackingStore(owningAddress, futureId);
    return;
  }
  Message message = asyncOps.remove(futureId);
  if (message == null) {
    // async operation was not found, it was flushed to the backing store.
    removeFromTheBackingStore(owningAddress, futureId);
  }
  if (asyncOps.isEmpty()) {
    // asyncOps has become empty after removing futureId,
    // we need to remove it from memoryStore.
    memoryStore.remove(owningAddress);
  }
}
 
Example 2
Source File: ColumnGroupsCommandHandler.java    From tmxeditor8 with GNU General Public License v2.0 6 votes vote down vote up
private void handleRemovalFromGroup(Map<String, Integer> toColumnPositions, int columnIndex) {
	final String columnGroupName = model.getColumnGroupNameForIndex(columnIndex);
	final List<Integer> columnIndexesInGroup = model.getColumnIndexesInGroup(columnIndex);
	final int columnGroupSize = columnIndexesInGroup.size();
	if (!toColumnPositions.containsKey(columnGroupName)) {
		for (int colGroupIndex : columnIndexesInGroup) {
			if (ColumnGroupUtils.isFirstVisibleColumnIndexInGroup(colGroupIndex, contextLayer, selectionLayer, model)) {
				int toPosition = selectionLayer.getColumnPositionByIndex(colGroupIndex);
				if (colGroupIndex == columnIndex) {
					if (columnGroupSize == 1) {
						break;
					} else {
						toPosition++;
					}
				}
				toColumnPositions.put(columnGroupName, Integer.valueOf(toPosition));
				break;
			}
		}
	} else {
		if (columnGroupSize - 1 <= 0) {
			toColumnPositions.remove(columnGroupName);
		}
	}
	model.removeColumnFromGroup(columnIndex);
}
 
Example 3
Source File: V3HttpAPIMultiClusterTest.java    From vespa with Apache License 2.0 6 votes vote down vote up
@Test
public void testPriorityAndTraceFlag() throws Exception {
    try (Server serverA = new Server(new V3MockParsingRequestHandler(
            200, V3MockParsingRequestHandler.Scenario.EXPECT_HIGHEST_PRIORITY_AND_TRACELEVEL_123), 0);
         Session session = SessionFactory.create(
                 new SessionParams.Builder()
                         .addCluster(new Cluster.Builder()
                                 .addEndpoint(Endpoint.create("localhost", serverA.getPort(), false))
                                 .build())
                         .setConnectionParams(new ConnectionParams.Builder()
                                 .setTraceLevel(123)
                                 .build())
                         .setFeedParams(new FeedParams.Builder()
                                 .setMaxSleepTimeMs(0)
                                 .setPriority("HIGHEST")
                                 .build())
                         .build())) {
        writeDocuments(session);
        Map<String, Result> results = getResults(session, documents.size());
        assertThat("Results received: " + results.values(), results.size(), is(documents.size()));
        for (TestDocument document : documents) {
            Result r = results.remove(document.getDocumentId());
            assertThat(r.getDetails().toString(), r.isSuccess(), is(true));
        }
    }
}
 
Example 4
Source File: ThreadContext.java    From disconf with Apache License 2.0 5 votes vote down vote up
/**
 * 删除上下文中的key
 *
 * @param key
 */
public final static void remove(String key) {
    Map<String, Object> ctx = CTX_HOLDER.get();
    if (ctx != null) {
        ctx.remove(key);
    }
}
 
Example 5
Source File: NodeDiscoverTask.java    From nuls with MIT License 5 votes vote down vote up
private boolean checkNeedProbeNow(Node node, Map<String, Node> verifyNodes) {
    // 探测间隔时间,根据失败的次数来决定,探测失败次数为failCount,探测间隔为probeInterval,定义分别如下:
    // failCount : 0-10 ,probeInterval = 60s
    // failCount : 11-20 ,probeInterval = 300s
    // failCount : 21-30 ,probeInterval = 600s
    // failCount : 31-50 ,probeInterval = 1800s
    // failCount : 51-100 ,probeInterval = 3600s
    // 当一个节点失败次数大于100时,将从节点列表中移除,除非再次收到该节点的分享,否则永远丢弃该节点

    long probeInterval;
    int failCount = node.getFailCount();

    if (failCount <= 10) {
        probeInterval = 60 * 1000L;
    } else if (failCount <= 20) {
        probeInterval = 300 * 1000L;
    } else if (failCount <= 30) {
        probeInterval = 600 * 1000L;
    } else if (failCount <= 50) {
        probeInterval = 1800 * 1000L;
    } else if (failCount <= 100) {
        probeInterval = 3600 * 1000L;
    } else {
        verifyNodes.remove(node.getId());
        return false;
    }

    return TimeService.currentTimeMillis() - node.getLastProbeTime() > probeInterval;
}
 
Example 6
Source File: SimpleRegistryService.java    From dubbox with Apache License 2.0 5 votes vote down vote up
@Override
public void unregister(String service, URL url) {
    super.unregister(service, url);
    String client = RpcContext.getContext().getRemoteAddressString();
    Map<String, URL> urls = remoteRegistered.get(client);
    if (urls != null && urls.size() > 0) {
        urls.remove(service);
    }
    notify(service, getRegistered().get(service));
}
 
Example 7
Source File: BasePlaceMonitorHandler.java    From arcusplatform with Apache License 2.0 5 votes vote down vote up
protected void pruneAddressDateMap(SubsystemContext<PlaceMonitorSubsystemModel> context, String attr){
   Map<String,Date>map=getAddressDateMapAttribute(context.model(), attr);
   Map<String,Date>prunedList=new HashMap<String,Date>(map);
   Map<String,Date>devices=new HashMap<String, Date>();
   for(Model device:context.models().getModelsByType(DeviceCapability.NAMESPACE)){
      devices.put(device.getAddress().getRepresentation(), new Date());
   }
   for(String key:map.keySet()){
      if(!devices.containsKey(key)){
         prunedList.remove(key);
      }
   }
   context.model().setAttribute(attr, prunedList);
}
 
Example 8
Source File: SyncUtils.java    From dubbox with Apache License 2.0 5 votes vote down vote up
public static <SM extends Map<String, Map<Long, URL>>> Map<Long, URL> filterFromCategory(Map<String, SM> urls, Map<String, String> filter) {
    String c = (String) filter.get(Constants.CATEGORY_KEY);
    if(c==null) throw new IllegalArgumentException("no category");
    
    filter.remove(Constants.CATEGORY_KEY);
    return filterFromService(urls.get(c), filter);
}
 
Example 9
Source File: SerializerConverter.java    From PoseidonX with Apache License 2.0 5 votes vote down vote up
private void removeSystemRepeatConfig(Map<String, String> config, SerDeAPI ob)
    throws ApplicationBuildException
{
    Map<String, String> opConf = AnnotationUtils.getAnnotationsToConfig(ob);
    for (Entry<String, String> et : opConf.entrySet())
    {
        config.remove(et.getKey());
    }
}
 
Example 10
Source File: SimpleRegistryService.java    From dubbo-2.6.5 with Apache License 2.0 5 votes vote down vote up
@Override
public void unregister(String service, URL url) {
    super.unregister(service, url);
    String client = RpcContext.getContext().getRemoteAddressString();
    Map<String, URL> urls = remoteRegistered.get(client);
    if (urls != null && urls.size() > 0) {
        urls.remove(service);
    }
    notify(service, getRegistered().get(service));
}
 
Example 11
Source File: XmlPolicyModelMarshaller.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Write default prefixes onto the given TypedXmlWriter
 *
 * @param model The policy source model. May not be null.
 * @param writer The TypedXmlWriter. May not be null.
 * @throws PolicyException If the creation of the prefix to namespace URI map failed.
 */
private void marshalDefaultPrefixes(final PolicySourceModel model, final TypedXmlWriter writer) throws PolicyException {
    final Map<String, String> nsMap = model.getNamespaceToPrefixMapping();
    if (!marshallInvisible && nsMap.containsKey(PolicyConstants.SUN_POLICY_NAMESPACE_URI)) {
        nsMap.remove(PolicyConstants.SUN_POLICY_NAMESPACE_URI);
    }
    for (Map.Entry<String, String> nsMappingEntry : nsMap.entrySet()) {
        writer._namespace(nsMappingEntry.getKey(), nsMappingEntry.getValue());
    }
}
 
Example 12
Source File: MorphShapeExporterBase.java    From jpexs-decompiler with GNU General Public License v3.0 5 votes vote down vote up
protected void removeEdgeFromCoordMap(Map<Long, List<IMorphEdge>> coordMap, IMorphEdge edge) {
    long fromLong = (((long) edge.getFromX()) << 32) | (edge.getFromY() & 0xffffffffL);
    List<IMorphEdge> coordMapArray = coordMap.get(fromLong);
    if (coordMapArray != null) {
        if (coordMapArray.size() == 1) {
            coordMap.remove(fromLong);
        } else {
            int i = coordMapArray.indexOf(edge);
            if (i > -1) {
                coordMapArray.remove(i);
            }
        }
    }
}
 
Example 13
Source File: MergeContent.java    From localization_nifi with Apache License 2.0 5 votes vote down vote up
@Override
public Map<String, String> getMergedAttributes(final List<FlowFile> flowFiles) {
    final Map<String, String> result = new HashMap<>();

    //trivial cases
    if (flowFiles == null || flowFiles.isEmpty()) {
        return result;
    } else if (flowFiles.size() == 1) {
        result.putAll(flowFiles.iterator().next().getAttributes());
    }

    /*
     * Start with the first attribute map and only put an entry to the
     * resultant map if it is common to every map.
     */
    final Map<String, String> firstMap = flowFiles.iterator().next().getAttributes();

    outer:
    for (final Map.Entry<String, String> mapEntry : firstMap.entrySet()) {
        final String key = mapEntry.getKey();
        final String value = mapEntry.getValue();

        for (final FlowFile flowFile : flowFiles) {
            final Map<String, String> currMap = flowFile.getAttributes();
            final String curVal = currMap.get(key);
            if (curVal == null || !curVal.equals(value)) {
                continue outer;
            }
        }
        result.put(key, value);
    }

    // Never copy the UUID from the parents - which could happen if we don't remove it and there is only 1 parent.
    result.remove(CoreAttributes.UUID.key());
    return result;
}
 
Example 14
Source File: MapVariableBinder.java    From arcusplatform with Apache License 2.0 5 votes vote down vote up
private V removeFromMap(SubsystemContext<M> context, Address address) {
   if(address == null) {
      return null;
   }

   Map<String, V> values = getValues(context);
   if(!values.containsKey(address.getRepresentation())) {
      return null;
   }
   
   values = new HashMap<>(values);
   V oldValue = values.remove(address.getRepresentation());
   setValues(context, values);
   return oldValue;
}
 
Example 15
Source File: XSLTURIMapper.java    From jbpm-work-items with Apache License 2.0 5 votes vote down vote up
@Override
public URI toURI(Map<String, Object> options) throws URISyntaxException {
    String address = (String) options.remove("templateName");

    String path = address;
    return prepareCamelUri(path,
                           options);
}
 
Example 16
Source File: TaskCache.java    From hugegraph-client with Apache License 2.0 5 votes vote down vote up
public void remove(TaskAPI api, long task) {
    Map<Long, Task> tasks = this.tasks(api);
    tasks.remove(task);
    if (tasks.isEmpty()) {
        this.taskTable.remove(api);
    }
    if (this.taskTable.isEmpty()) {
        this.stop();
    }
}
 
Example 17
Source File: SessionWatchers.java    From sofa-registry with Apache License 2.0 5 votes vote down vote up
@Override
public boolean deleteById(String registerId, String dataInfoId) {
    write.lock();
    try {

        Map<String, Watcher> watcherMap = watchers.get(dataInfoId);

        if (watcherMap == null) {
            LOGGER.error("Delete failed because watcher is not registered for dataInfoId: {}",
                dataInfoId);
            return false;
        } else {
            Watcher watcher = watcherMap.remove(registerId);

            if (watcher == null) {
                LOGGER.error(
                    "Delete failed because watcher is not registered for registerId: {}",
                    registerId);
                return false;
            } else {
                removeConnectIndex(watcher);
                return true;
            }
        }
    } finally {
        write.unlock();
    }
}
 
Example 18
Source File: ToStringStyle.java    From common-utils with GNU General Public License v2.0 5 votes vote down vote up
/**
 * <p>
 * Unregisters the given object.
 * </p>
 * 
 * <p>
 * Used by the reflection methods to avoid infinite loops.
 * </p>
 * 
 * @param value The object to unregister.
 */
static void unregister(Object value) {
    if (value != null) {
        Map<Object, Object> m = getRegistry();
        if (m != null) {
            m.remove(value);
            if (m.isEmpty()) {
                REGISTRY.set(null);
            }
        }
    }
}
 
Example 19
Source File: IsoChronology.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
@Override  // override for enhanced behaviour
LocalDate resolveYearOfEra(Map<TemporalField, Long> fieldValues, ResolverStyle resolverStyle) {
    Long yoeLong = fieldValues.remove(YEAR_OF_ERA);
    if (yoeLong != null) {
        if (resolverStyle != ResolverStyle.LENIENT) {
            YEAR_OF_ERA.checkValidValue(yoeLong);
        }
        Long era = fieldValues.remove(ERA);
        if (era == null) {
            Long year = fieldValues.get(YEAR);
            if (resolverStyle == ResolverStyle.STRICT) {
                // do not invent era if strict, but do cross-check with year
                if (year != null) {
                    addFieldValue(fieldValues, YEAR, (year > 0 ? yoeLong: Math.subtractExact(1, yoeLong)));
                } else {
                    // reinstate the field removed earlier, no cross-check issues
                    fieldValues.put(YEAR_OF_ERA, yoeLong);
                }
            } else {
                // invent era
                addFieldValue(fieldValues, YEAR, (year == null || year > 0 ? yoeLong: Math.subtractExact(1, yoeLong)));
            }
        } else if (era.longValue() == 1L) {
            addFieldValue(fieldValues, YEAR, yoeLong);
        } else if (era.longValue() == 0L) {
            addFieldValue(fieldValues, YEAR, Math.subtractExact(1, yoeLong));
        } else {
            throw new DateTimeException("Invalid value for era: " + era);
        }
    } else if (fieldValues.containsKey(ERA)) {
        ERA.checkValidValue(fieldValues.get(ERA));  // always validated
    }
    return null;
}
 
Example 20
Source File: OneDReader.java    From weex with Apache License 2.0 4 votes vote down vote up
/**
 * We're going to examine rows from the middle outward, searching alternately above and below the
 * middle, and farther out each time. rowStep is the number of rows between each successive
 * attempt above and below the middle. So we'd scan row middle, then middle - rowStep, then
 * middle + rowStep, then middle - (2 * rowStep), etc.
 * rowStep is bigger as the image is taller, but is always at least 1. We've somewhat arbitrarily
 * decided that moving up and down by about 1/16 of the image is pretty good; we try more of the
 * image if "trying harder".
 *
 * @param image The image to decode
 * @param hints Any hints that were requested
 * @return The contents of the decoded barcode
 * @throws NotFoundException Any spontaneous errors which occur
 */
private Result doDecode(BinaryBitmap image,
                        Map<DecodeHintType,?> hints) throws NotFoundException {
  int width = image.getWidth();
  int height = image.getHeight();
  BitArray row = new BitArray(width);

  int middle = height >> 1;
  boolean tryHarder = hints != null && hints.containsKey(DecodeHintType.TRY_HARDER);
  int rowStep = Math.max(1, height >> (tryHarder ? 8 : 5));
  int maxLines;
  if (tryHarder) {
    maxLines = height; // Look at the whole image, not just the center
  } else {
    maxLines = 15; // 15 rows spaced 1/32 apart is roughly the middle half of the image
  }

  for (int x = 0; x < maxLines; x++) {

    // Scanning from the middle out. Determine which row we're looking at next:
    int rowStepsAboveOrBelow = (x + 1) / 2;
    boolean isAbove = (x & 0x01) == 0; // i.e. is x even?
    int rowNumber = middle + rowStep * (isAbove ? rowStepsAboveOrBelow : -rowStepsAboveOrBelow);
    if (rowNumber < 0 || rowNumber >= height) {
      // Oops, if we run off the top or bottom, stop
      break;
    }

    // Estimate black point for this row and load it:
    try {
      row = image.getBlackRow(rowNumber, row);
    } catch (NotFoundException ignored) {
      continue;
    }

    // While we have the image data in a BitArray, it's fairly cheap to reverse it in place to
    // handle decoding upside down barcodes.
    for (int attempt = 0; attempt < 2; attempt++) {
      if (attempt == 1) { // trying again?
        row.reverse(); // reverse the row and continue
        // This means we will only ever draw result points *once* in the life of this method
        // since we want to avoid drawing the wrong points after flipping the row, and,
        // don't want to clutter with noise from every single row scan -- just the scans
        // that start on the center line.
        if (hints != null && hints.containsKey(DecodeHintType.NEED_RESULT_POINT_CALLBACK)) {
          Map<DecodeHintType,Object> newHints = new EnumMap<>(DecodeHintType.class);
          newHints.putAll(hints);
          newHints.remove(DecodeHintType.NEED_RESULT_POINT_CALLBACK);
          hints = newHints;
        }
      }
      try {
        // Look for a barcode
        Result result = decodeRow(rowNumber, row, hints);
        // We found our barcode
        if (attempt == 1) {
          // But it was upside down, so note that
          result.putMetadata(ResultMetadataType.ORIENTATION, 180);
          // And remember to flip the result points horizontally.
          ResultPoint[] points = result.getResultPoints();
          if (points != null) {
            points[0] = new ResultPoint(width - points[0].getX() - 1, points[0].getY());
            points[1] = new ResultPoint(width - points[1].getX() - 1, points[1].getY());
          }
        }
        return result;
      } catch (ReaderException re) {
        // continue -- just couldn't decode this row
      }
    }
  }

  throw NotFoundException.getNotFoundInstance();
}