Java 类java.util.AbstractMap.SimpleEntry 实例源码

项目:openjdk-jdk10    文件:NullCheckLineNumberTest.java   
public static void main(String[] args) throws Exception {
    List<Entry> actualEntries = findEntries();
    List<Entry> expectedEntries = List.of(
            new SimpleEntry<>(29, 0),
            new SimpleEntry<>(30, 4),
            new SimpleEntry<>(32, 9),
            new SimpleEntry<>(33, 16),
            new SimpleEntry<>(34, 32),
            new SimpleEntry<>(35, 46),
            new SimpleEntry<>(36, 52)
    );
    if (!Objects.equals(actualEntries, expectedEntries)) {
        error(String.format("Unexpected LineNumberTable: %s", actualEntries.toString()));
    }

    try {
        new Test();
    } catch (NullPointerException npe) {
        if (Arrays.stream(npe.getStackTrace())
                  .noneMatch(se -> se.getFileName().contains("NullCheckLineNumberTest") &&
                                   se.getLineNumber() == 34)) {
            throw new AssertionError("Should go through line 34!");
        }
    }
}
项目:alevin-svn2    文件:XMLExporter.java   
/**
 * Extracts and exports normal parameters
 * 
 * @param writer Writer object
 * @param ob Object 
 * @throws XMLStreamException 
 */
static void exportParameters(XMLStreamWriter writer,
        Object ob) throws XMLStreamException {
    Method[] mets = ob.getClass().getMethods();
    for(Method m : mets) {
        //lookup if the Method is marked as ExchangeParameter and NOT a setter
        ExchangeParameter ep = m.getAnnotation(ExchangeParameter.class);
        if(ep != null && m.getName().contains("get")) {
            writer.writeEmptyElement("Parameter");
            String paramName = m.getName().substring(3);
            SimpleEntry<String, String> se = exportParamType(ob, m.getName());
            writer.writeAttribute("name", paramName);
            writer.writeAttribute("type", se.getKey());
            writer.writeAttribute("value", se.getValue());
        }
    }

}
项目:alevin-svn2    文件:XMLExporter.java   
/**
 * Extracts and write out the AdditionalConstructionParameters to the writer
 * 
 * @param writer Given Writer
 * @param ob Object with annotations from AdditionalConstructParameter.class
 * @throws XMLStreamException 
 */
static void exportConstructParameters(XMLStreamWriter writer,
        Object ob) throws XMLStreamException {
    //Get the Construction Parameters
    AdditionalConstructParameter acp = ob.getClass().getAnnotation(AdditionalConstructParameter.class);
    if(acp != null) {
        for(int i = 0; i < acp.parameterGetters().length; i++) {
            writer.writeEmptyElement("ConstructParameter");
            writer.writeAttribute("name", acp.parameterNames()[i]);
            SimpleEntry<String, String> se = exportParamType(ob, acp.parameterGetters()[i]);
            writer.writeAttribute("type", se.getKey());
            writer.writeAttribute("value", se.getValue());
        }
    }


}
项目:incubator-servicecomb-java-chassis    文件:SPIServiceUtils.java   
public static <T> List<T> getSortedService(Class<T> serviceType) {
  List<Entry<Integer, T>> serviceEntries = new ArrayList<>();
  ServiceLoader<T> serviceLoader = ServiceLoader.load(serviceType);
  serviceLoader.forEach(service -> {
    int serviceOrder = 0;
    Method getOrder = ReflectionUtils.findMethod(service.getClass(), "getOrder");
    if (getOrder != null) {
      serviceOrder = (int) ReflectionUtils.invokeMethod(getOrder, service);
    }

    Entry<Integer, T> entry = new SimpleEntry<>(serviceOrder, service);
    serviceEntries.add(entry);
  });

  return serviceEntries.stream()
      .sorted(Comparator.comparingInt(Entry::getKey))
      .map(Entry::getValue)
      .collect(Collectors.toList());
}
项目:SubgraphIsomorphismIndex    文件:ProblemContainerNeighbourhoodAware.java   
public static <K, V> Entry<K, V> firstEntry(NavigableMap<K, ? extends Iterable<V>> map) {
    Entry<K, V> result = null;

    Iterator<? extends Entry<K, ? extends Iterable<V>>> itE = map.entrySet().iterator();

    // For robustness, remove entry valueX sets
    while(itE.hasNext()) {
        Entry<K, ? extends Iterable<V>> e = itE.next();

        K k = e.getKey();
        Iterable<V> vs = e.getValue();

        Iterator<V> itV = vs.iterator();
        if(itV.hasNext()) {
            V v = itV.next();

            result = new SimpleEntry<>(k, v);
            break;
        } else {
            continue;
        }
    }

    return result;
}
项目:trellis    文件:GetHandlerTest.java   
@Test
public void testExtraLinks() {
    final String inbox = "http://ldn.example.com/inbox";
    final String annService = "http://annotation.example.com/resource";

    when(mockResource.getExtraLinkRelations()).thenAnswer(inv -> Stream.of(
            new SimpleEntry<>(annService, OA.annotationService.getIRIString()),
            new SimpleEntry<>(SKOS.Concept.getIRIString(), "type"),
            new SimpleEntry<>(inbox, "inbox")));
    when(mockHeaders.getAcceptableMediaTypes()).thenReturn(singletonList(TEXT_TURTLE_TYPE));

    final GetHandler getHandler = new GetHandler(mockLdpRequest, mockResourceService,
            mockIoService, mockBinaryService, baseUrl);

    final Response res = getHandler.getRepresentation(mockResource).build();
    assertEquals(OK, res.getStatusInfo());
    assertTrue(res.getLinks().stream().anyMatch(hasType(SKOS.Concept)));
    assertTrue(res.getLinks().stream().anyMatch(hasLink(rdf.createIRI(inbox), "inbox")));
    assertTrue(res.getLinks().stream().anyMatch(hasLink(rdf.createIRI(annService),
                    OA.annotationService.getIRIString())));
}
项目:JRediClients    文件:AbstractCacheMap.java   
public final Iterator<Map.Entry<K,V>> iterator() {
    return new MapIterator<Map.Entry<K,V>>() {
        @Override
        public Map.Entry<K,V> next() {
            if (mapEntry == null) {
                throw new NoSuchElementException();
            }

            SimpleEntry<K, V> result = new SimpleEntry<K, V>(mapEntry.getKey(), readValue(mapEntry.getValue()));
            mapEntry = null;
            return result;
        }

        @Override
        public void remove() {
            if (mapEntry == null) {
                throw new IllegalStateException();
            }
            map.remove(mapEntry.getKey(), mapEntry.getValue());
            mapEntry = null;
        }
    };
}
项目:openjdk-jdk10    文件:NullCheckLineNumberTest.java   
static List<Entry> findEntries() throws IOException, ConstantPoolException {
    ClassFile self = ClassFile.read(NullCheckLineNumberTest.Test.class.getResourceAsStream("NullCheckLineNumberTest$Test.class"));
    for (Method m : self.methods) {
        if ("<init>".equals(m.getName(self.constant_pool))) {
            Code_attribute code_attribute = (Code_attribute)m.attributes.get(Attribute.Code);
            for (Attribute at : code_attribute.attributes) {
                if (Attribute.LineNumberTable.equals(at.getName(self.constant_pool))) {
                    return Arrays.stream(((LineNumberTable_attribute)at).line_number_table)
                                 .map(e -> new SimpleEntry<> (e.line_number, e.start_pc))
                                 .collect(Collectors.toList());
                }
            }
        }
    }
    return null;
}
项目:hashsdn-controller    文件:ClusterAdminRpcService.java   
private <T> void sendMessageToManagerForConfiguredShards(DataStoreType dataStoreType,
        List<Entry<ListenableFuture<T>, ShardResultBuilder>> shardResultData,
        Function<String, Object> messageSupplier) {
    ActorContext actorContext = dataStoreType == DataStoreType.Config ? configDataStore.getActorContext()
            : operDataStore.getActorContext();
    Set<String> allShardNames = actorContext.getConfiguration().getAllShardNames();

    LOG.debug("Sending message to all shards {} for data store {}", allShardNames, actorContext.getDataStoreName());

    for (String shardName: allShardNames) {
        ListenableFuture<T> future = this.ask(actorContext.getShardManager(), messageSupplier.apply(shardName),
                                              SHARD_MGR_TIMEOUT);
        shardResultData.add(new SimpleEntry<>(future,
                new ShardResultBuilder().setShardName(shardName).setDataStoreType(dataStoreType)));
    }
}
项目:hashsdn-controller    文件:BlueprintContainerRestartServiceImpl.java   
private void possiblyAddConfigModuleIdentifier(final ServiceReference<?> reference,
        final List<Entry<String, ModuleIdentifier>> configModules) {
    Object moduleNamespace = reference.getProperty(CONFIG_MODULE_NAMESPACE_PROP);
    if (moduleNamespace == null) {
        return;
    }

    String moduleName = getRequiredConfigModuleProperty(CONFIG_MODULE_NAME_PROP, moduleNamespace,
            reference);
    String instanceName = getRequiredConfigModuleProperty(CONFIG_INSTANCE_NAME_PROP, moduleNamespace,
            reference);
    if (moduleName == null || instanceName == null) {
        return;
    }

    LOG.debug("Found service with config module: namespace {}, module name {}, instance {}",
            moduleNamespace, moduleName, instanceName);

    configModules.add(new SimpleEntry<>(moduleNamespace.toString(),
            new ModuleIdentifier(moduleName, instanceName)));
}
项目:AndroTickler    文件:JavaSqueezer.java   
/**
 * Searches for a group of Keys and print each occurrence and its file name. 
 * @param keys
 */
private ArrayList<SimpleEntry> returnFNameLineGroup(String[] keys, boolean printName){
    ArrayList<SimpleEntry> eA = new ArrayList<>();
    ArrayList<SimpleEntry> keyRes = new ArrayList<>();

    for (String s: keys){
        keyRes = this.sU.searchForKeyInJava(s,this.codeRoot);
        if (printName && (!keyRes.isEmpty()))
            OutBut.printH3(s);

        eA.addAll(this.sU.searchForKeyInJava(s,this.codeRoot));
    }

    return eA;

}
项目:hashsdn-controller    文件:DistributedShardedDOMDataTree.java   
@SuppressWarnings("checkstyle:IllegalCatch")
private Entry<DataStoreClient, ActorRef> createDatastoreClient(
        final String shardName, final ActorContext actorContext)
        throws DOMDataTreeShardCreationFailedException {

    LOG.debug("{}: Creating distributed datastore client for shard {}", memberName, shardName);
    final Props distributedDataStoreClientProps =
            SimpleDataStoreClientActor.props(memberName, "Shard-" + shardName, actorContext, shardName);

    final ActorRef clientActor = actorSystem.actorOf(distributedDataStoreClientProps);
    try {
        return new SimpleEntry<>(SimpleDataStoreClientActor
                .getDistributedDataStoreClient(clientActor, 30, TimeUnit.SECONDS), clientActor);
    } catch (final Exception e) {
        LOG.error("{}: Failed to get actor for {}", distributedDataStoreClientProps, memberName, e);
        clientActor.tell(PoisonPill.getInstance(), noSender());
        throw new DOMDataTreeShardCreationFailedException(
                "Unable to create datastore client for shard{" + shardName + "}", e);
    }
}
项目:AndroTickler    文件:ProviderAttacker.java   
public void getContentURIsFromSmali(String smaliPath){

    this.contentURIs = new ArrayList<String>();
    ArrayList<String> contents = new ArrayList<String>();
    ArrayList<SimpleEntry> contentsReturn =new ArrayList<SimpleEntry>(); 
    SearchUtil searcher = new SearchUtil();
    String contentUri;

    contents = searcher.search4KeyInDir(smaliPath, "content://");

    for (String c:contents){
        if (!"".equals(contentUri = this.correctContentUri(c)))
            this.contentURIs.add(contentUri);
    }
    this.contentURIs = this.removeDuplicates(this.contentURIs);
}
项目:3DSFE-Randomizer    文件:EventDecompiler.java   
private SimpleEntry<String, Integer> parseRaw(byte[] input, int index) {
    StringBuilder result = new StringBuilder();
    int advance = 0;
    ArrayList<Byte> raw = new ArrayList<>();
    while (!isKnownByte(input[index + advance])) {
        raw.add(input[index + advance]);
        advance++;
        if (index + advance >= input.length)
            break;
        if (conditionalLengths.size() > 0 && conditionalIndexes.size() > 0) {
            if (index + advance >= conditionalLengths.peek() + conditionalIndexes.peek())
                break;
        }
    }
    advance--;

    result.append("raw(");
    for (int x = 0; x < raw.size(); x++) {
        result.append(Integer.toHexString(raw.get(x) & 0xFF));
        if (x < raw.size() - 1)
            result.append(",");
        else
            result.append(")");
    }
    return new SimpleEntry<>(result.toString(), advance);
}
项目:3DSFE-Randomizer    文件:EventDecompiler.java   
private SimpleEntry<String, Integer> parseRaw(byte[] input, int index, int length) {
    StringBuilder result = new StringBuilder();
    int advance = length - 1;
    ArrayList<Byte> raw = new ArrayList<>();
    for (int x = 0; x < length; x++)
        raw.add(input[index + x]);
    result.append("raw(");
    for (int x = 0; x < raw.size(); x++) {
        result.append(Integer.toHexString(raw.get(x) & 0xFF));
        if (x < raw.size() - 1)
            result.append(",");
        else
            result.append(")");
    }

    return new SimpleEntry<>(result.toString(), advance);
}
项目:3DSFE-Randomizer    文件:EventDecompiler.java   
private SimpleEntry<String, Integer> parseReturn(byte[] input, int index) {
    String result;
    int advance = 2;
    int returnPoint = (ScriptUtils.shortFromByteArray(input, index + 1) + 3) * -1; // Return markers will always use a negative value.
    if (savedPoints.containsKey(index - returnPoint)) {
        int point = savedPoints.get(index - returnPoint);
        int line = point + lineNumber;

        //Special case fix for A002_OP1 bev file.
        if (input[index - returnPoint] != 0x47 && (decompiled.get(point).startsWith("ev::") || decompiled.get(point).startsWith("bev::"))) {
            return this.parseRaw(input, index, 3);
        }

        result = "goto(" + line + ")";
        return new SimpleEntry<>(result, advance);
    } else {
        return this.parseRaw(input, index, 3);
    }
}
项目:3DSFE-Randomizer    文件:EventDecompiler.java   
private SimpleEntry<Boolean, Integer> hasEndConditional(byte[] input) {
    if (conditionalLengths.size() > 0 && conditionalIndexes.size() > 0) {
        int currentConditionalLength = conditionalLengths.peek();
        int currentConditionalIndex = conditionalIndexes.peek();
        int checkIndex = currentConditionalLength + currentConditionalIndex - 3;
        if (checkIndex < input.length) {
            for (byte b : CONDITIONAL_VALS) {
                if (ScriptUtils.shortFromByteArray(input, checkIndex + 1) < 0)
                    return new SimpleEntry<>(false, checkIndex); // The ending is a goto.
                if (input[checkIndex] == b)
                    return new SimpleEntry<>(true, checkIndex); // Ends in an else statement.
            }
        }
    }
    return new SimpleEntry<>(false, -1);
}
项目:BrainControl    文件:VoiceKnowledgeManager.java   
static <A> Entry<A, Double> selectLikelyEntry(TreeMap<A, Double> entries)
{
    ArrayList<A> keys = new ArrayList<A>(entries.keySet());

    Double value;
    A randomKey;

    do
    {           
        randomKey = keys.get(random.nextInt(keys.size()));
        value = entries.get(randomKey);

        //System.out.println("thinking to talk about " + randomKey + " + " + value + "("+keys.size()+" keys)");
    }
    while(value==null || (Math.random() > value.doubleValue()));

    return new SimpleEntry<A, Double>(randomKey, value);
}
项目:hashsdn-controller    文件:ConfigurationImpl.java   
@Nullable
@Override
public String getShardNameForPrefix(@Nonnull final DOMDataTreeIdentifier prefix) {
    Preconditions.checkNotNull(prefix, "prefix should not be null");

    Entry<DOMDataTreeIdentifier, PrefixShardConfiguration> bestMatchEntry =
            new SimpleEntry<>(
                    new DOMDataTreeIdentifier(prefix.getDatastoreType(), YangInstanceIdentifier.EMPTY), null);

    for (Entry<DOMDataTreeIdentifier, PrefixShardConfiguration> entry : prefixConfigMap.entrySet()) {
        if (entry.getKey().contains(prefix) && entry.getKey().getRootIdentifier().getPathArguments().size()
                > bestMatchEntry.getKey().getRootIdentifier().getPathArguments().size()) {
            bestMatchEntry = entry;
        }
    }

    //TODO we really should have mapping based on prefix instead of Strings
    return ClusterUtils.getCleanShardName(bestMatchEntry.getKey().getRootIdentifier());
}
项目:test-data-supplier    文件:DataSupplierMetaData.java   
private StreamEx<?> wrap(final Object data) {
    return Match(data).of(
            Case($(isNull()), () -> {
                throw new IllegalArgumentException(format(
                        "Nothing to return from data supplier. The following test will be skipped: %s.%s.",
                        testMethod.getConstructorOrMethod().getDeclaringClass().getSimpleName(),
                        testMethod.getConstructorOrMethod().getName()));
            }),
            Case($(instanceOf(Collection.class)), d -> StreamEx.of((Collection<?>) d)),
            Case($(instanceOf(Map.class)), d -> EntryStream.of((Map<?, ?>) d).mapKeyValue(SimpleEntry::new)),
            Case($(instanceOf(Map.Entry.class)), d -> StreamEx.of(d.getKey(), d.getValue())),
            Case($(instanceOf(Object[].class)), d -> StreamEx.of((Object[]) d)),
            Case($(instanceOf(double[].class)), d -> DoubleStreamEx.of((double[]) d).boxed()),
            Case($(instanceOf(int[].class)), d -> IntStreamEx.of((int[]) d).boxed()),
            Case($(instanceOf(long[].class)), d -> LongStreamEx.of((long[]) d).boxed()),
            Case($(instanceOf(Stream.class)), d -> StreamEx.of((Stream<?>) d)),
            Case($(instanceOf(Tuple.class)), d -> StreamEx.of(((Tuple) d).toSeq().toJavaArray())),
            Case($(), d -> StreamEx.of(d)));
}
项目:jparsercombinator    文件:JsonParser.java   
JsonParser() {
  ParserCombinatorReference<JsonElement> jsonParser = newRef();

  ParserCombinator<JsonElement> jsonNullParser = string("null").map(v -> new JsonNull());

  ParserCombinator<JsonElement> jsonBooleanParser =
      regex("(true|false)").map(v -> new JsonPrimitive(Boolean.valueOf(v)));
  ParserCombinator<JsonElement> jsonIntegerParser =
      regex("[0-9]+").map(v -> new JsonPrimitive(Integer.parseInt(v)));
  ParserCombinator<JsonElement> jsonStringParser =
      regexMatchResult("\"([^\"]*)\"").map(v -> new JsonPrimitive(v.group(1)));
  ParserCombinator<JsonElement> jsonPrimitiveParser =
      jsonStringParser.or(jsonBooleanParser).or(jsonIntegerParser);

  ParserCombinatorReference<JsonElement> jsonObjectParser = newRef();
  ParserCombinatorReference<JsonElement> jsonArrayParser = newRef();

  ParserCombinator<Entry<String, JsonElement>> jsonObjectEntryParser =
      jsonStringParser.skip(string(":")).next(jsonParser)
          .map(pair -> new SimpleEntry<>(pair.first.toString(), pair.second));

  jsonObjectParser.setCombinator(
      skip(string("{"))
          .next(jsonObjectEntryParser.many(string(",")))
          .skip(string("}"))
          .map(JsonObject::new));

  jsonArrayParser.setCombinator(
      skip(string("["))
          .next(jsonParser.many(string(",")))
          .skip(string("]"))
          .map(JsonArray::new));

  jsonParser.setCombinator(
      jsonNullParser.or(jsonPrimitiveParser).or(jsonArrayParser).or(jsonObjectParser));

  parser = jsonParser.end();
}
项目:jparsercombinator    文件:JsonParserTest.java   
@Test
public void shouldParseSimpleJsonObject() {
  JsonObject jsonObject = new JsonObject(
      new SimpleEntry<>("foo", new JsonPrimitive("bar")));

  assertEquals(jsonObject, jsonParser.apply("{\"foo\":\"bar\"}"));
}
项目:springmock    文件:MockitoContextCustomizerFactory.java   
@Override
protected ContextCustomizer createContextCustomizer(DoubleRegistry doubleRegistry) {
    return new MockContextCustomizer(
            MockitoDoubleFactory.class,
            doubleRegistry,
            Stream
                    .of(new SimpleEntry<>(SkipMockitoBeansPostProcessing.BEAN_NAME, skipMockitoBeansPostProcessing()))
                    .collect(toMap(Map.Entry::getKey, Map.Entry::getValue)));
}
项目:jparsercombinator    文件:JsonParserTest.java   
@Test
public void shouldParseNestedArraysAndObjects() {
  JsonArray firstArray =
      new JsonArray(
          new JsonObject(new SimpleEntry<>("1", new JsonArray(
              new JsonObject(new SimpleEntry<>("1", new JsonPrimitive(1))),
              new JsonObject(new SimpleEntry<>("2", new JsonPrimitive(2)))))),
          new JsonObject(new SimpleEntry<>("2", new JsonArray(
              new JsonObject(new SimpleEntry<>("1", new JsonPrimitive(3))),
              new JsonObject(new SimpleEntry<>("2", new JsonPrimitive(4)))))));

  JsonArray secondArray =
      new JsonArray(
          new JsonObject(new SimpleEntry<>("1", new JsonArray(
              new JsonObject(new SimpleEntry<>("1", new JsonPrimitive(5))),
              new JsonObject(new SimpleEntry<>("2", new JsonPrimitive(6)))))),
          new JsonObject(new SimpleEntry<>("2", new JsonArray(
              new JsonObject(new SimpleEntry<>("1", new JsonPrimitive(7))),
              new JsonObject(new SimpleEntry<>("2", new JsonPrimitive(8)))))));

  JsonObject jsonObject = new JsonObject(
      new SimpleEntry<>("1", firstArray),
      new SimpleEntry<>("2", secondArray));

  String firstArrayJson = "[{\"1\":[{\"1\":1},{\"2\":2}]},{\"2\":[{\"1\":3},{\"2\":4}]}]";
  String secondArrayJson = "[{\"1\":[{\"1\":5},{\"2\":6}]},{\"2\":[{\"1\":7},{\"2\":8}]}]";
  String json = String.format("{\"1\":%s,\"2\":%s}", firstArrayJson, secondArrayJson);

  assertEquals(jsonObject, jsonParser.apply(json));
}
项目:alexa-skill    文件:CalendarSpeechletIT.java   
@Test
public void cancel_dialog() throws CalendarWriteException {
  //given
  //when
  HttpEntity<String> request = buildRequestWithSession("AMAZON.CancelIntent",
    new SimpleEntry<>(KEY_DIALOG_TYPE, DIALOG_TYPE_NEW_EVENT)
  );

  final SpeechletResponseEnvelope response = perform(request);

  //then
  assertEquals(
      ((PlainTextOutputSpeech)toTestBasic.speechService.speechCancelNewEvent(Locale.GERMANY)).getText(),
      ((PlainTextOutputSpeech)response.getResponse().getOutputSpeech()).getText());
}
项目:ibm-cos-sdk-java    文件:NotificationConfigurationStaxUnmarshaller.java   
/**
 * Id (aka configuration name) isn't modeled on the actual {@link NotificationConfiguration}
 * class but as the key name in the map of configurations in
 * {@link BucketNotificationConfiguration}
 */
@Override
public Entry<String, NotificationConfiguration> unmarshall(StaxUnmarshallerContext context) throws Exception {
    int originalDepth = context.getCurrentDepth();
    int targetDepth = originalDepth + 1;

    if (context.isStartOfDocument()) {
        targetDepth += 1;
    }

    T topicConfig = createConfiguration();
    String id = null;

    while (true) {
        XMLEvent xmlEvent = context.nextEvent();
        if (xmlEvent.isEndDocument()) {
            return new SimpleEntry<String, NotificationConfiguration>(id, topicConfig);
        }

        if (xmlEvent.isAttribute() || xmlEvent.isStartElement()) {
            if (handleXmlEvent(topicConfig, context, targetDepth)) {
                // Do nothing, subclass has handled it
            } else if (context.testExpression("Id", targetDepth)) {
                id = StringStaxUnmarshaller.getInstance().unmarshall(context);
            } else if (context.testExpression("Event", targetDepth)) {
                topicConfig.addEvent(StringStaxUnmarshaller.getInstance().unmarshall(context));
            } else if (context.testExpression("Filter", targetDepth)) {
                topicConfig.setFilter(FilterStaxUnmarshaller.getInstance().unmarshall(context));
            }
        } else if (xmlEvent.isEndElement()) {
            if (context.getCurrentDepth() < originalDepth) {
                return new SimpleEntry<String, NotificationConfiguration>(id, topicConfig);
            }
        }
    }
}
项目:alevin-svn2    文件:TestParamImporter.java   
private void parseLine(String line) {
    String[] key_value = line.split(": ");
    String key = key_value[0].replaceAll("^\"|\"$", "");
    String[] values = key_value[1].split(",");

    if (key.equals("Algorithm")) {
        algo = values[0];
    } else if (key.equals("NetworkGenerator")) {
        netGen = values[0];
    } else if (key.equals("Metrics")) {
        metrics = Arrays.asList(values);
    } else if (key.equals("ResourceGenerators")) {
        resGens = Arrays.asList(values);
    } else if (key.equals("DemandGenerators")) {
        demGens = Arrays.asList(values);
    } else if (key.equals("Runs")) {
        runs = Integer.parseInt(values[0]);
    } else if (key.equals("SaveNetworks")) {
        if (values[0].equals("") 
                || values[0].equals("XML") 
                || values[0].equals("DOT")) {
            saveNetworks = values[0];
        }
    } else if (key.equals("AlgorithmParameter")) {
        parseAlgoParamLine(values);
    } else {
        SimpleEntry<String, Object[]> entry = parseParamLine(key, values);
        params.add(entry);
    }
}
项目:spring-webflux-client    文件:MethodMetadataFactoryTest.java   
@Test
public void parameterAnnotationProcessing_withPathParameter() {
    List<MethodMetadata> visit = methodMetadataFactory.build(ReactiveClientWithPathParameters.class, URI.create(""));
    assertThat(visit)
            .hasSize(1);
    MethodMetadata requestTemplate = visit.get(0);
    assertThat(requestTemplate.getRequestTemplate().getVariableIndexToName())
            .contains(new SimpleEntry<>(0, singletonList("pathVariable1")),
                    new SimpleEntry<>(1, singletonList("pathVariable2")));
}
项目:swblocks-decisiontree    文件:ChangeFromBuilder.java   
@Before
public void setUp() {
    this.builder = RuleSetBuilder.creator("commissions",
            Arrays.asList("EXMETHOD", "EXCHANGE", "PRODUCT", "REGION", "ASSET"));

    this.builder.with(RuleSetBuilder::rule, RuleBuilder.creator()
            .with(RuleBuilder::input, Arrays.asList("*", "VG:CMEGroup:CME:CBOT", "*", "*", "INDEX"))
            .with(RuleBuilder::output, Collections.singletonMap("Rate", "1.1")));

    this.builder.with(RuleSetBuilder::rule, RuleBuilder.creator()
            .with(RuleBuilder::input, Arrays.asList("*", "CME", "S&P", "*", "INDEX"))
            .with(RuleBuilder::output, Collections.singletonMap("Rate", "1.2")));

    this.builder.with(RuleSetBuilder::rule, RuleBuilder.creator()
            .with(RuleBuilder::input, Arrays.asList("VOICE", "CME", "ED", "*", "RATE"))
            .with(RuleBuilder::output, Collections.singletonMap("Rate", "1.4")));

    this.builder.with(RuleSetBuilder::rule, RuleBuilder.creator()
            .with(RuleBuilder::input, Arrays.asList("*", "*", "*", "US", "*"))
            .with(RuleBuilder::output, Collections.singletonMap("Rate", "1.5")));

    this.builder.with(RuleSetBuilder::rule, RuleBuilder.creator()
            .with(RuleBuilder::input, Arrays.asList("*", "*", "*", "UK", "*"))
            .with(RuleBuilder::output, Stream.of(
                    new SimpleEntry<>("Rate", "1.1"),
                    new SimpleEntry<>("Unit", "£"))
                    .collect(Collectors.toMap(SimpleEntry::getKey, SimpleEntry::getValue))));
}
项目:image-resolver    文件:WebpageImageResolver.java   
private Element findElementWithMostParagraphs(Element main) {
    return main.getAllElements()
            .stream()
            .filter(e -> e.childNodes().stream().filter(n -> n instanceof Element).map(n -> (Element) n).anyMatch(el -> Objects.equals(el.tagName(), "p")))
            .map(e -> new SimpleEntry<>(e, e.getElementsByTag("p").size()))
            .sorted((e1, e2) -> e2.getValue() - e1.getValue())
            .map(SimpleEntry::getKey)
            .findFirst()
            .orElse(main);

}
项目:dds-examples    文件:DynamicPartitionCommander.java   
@Override
public void deleteSession(
    final Session session
) {
  LOGGER.info(
      "Delete session: topic='{}', partition='{}'",
      session.getTopic(),
      session.getPartition()
  );

  synchronized (activeCommands) {
    // create command
    SimpleEntry<Session, TopicRoute> command = new SimpleEntry<>(session, null);

    // when another command is scheduled, cancel it
    if (activeCommands.containsKey(command)) {
      activeCommands.remove(command).cancel(false);
    }

    // schedule creation of session
    ScheduledFuture commandFuture = executorService.scheduleWithFixedDelay(
        () -> {
          if (sendDeleteSession(
              routingServiceCommandInterface,
              targetRoutingService,
              session
          )) {
            activeCommands.remove(command).cancel(false);
          }
        },
        0,
        retryDelay,
        retryDelayTimeUnit
    );

    // add command to scheduled commands
    activeCommands.put(command, commandFuture);
  }
}
项目:fpc    文件:HTTPNotifier.java   
/**
 * Primary Constructor.
 *
 * @param startSignal - Latch start signal
 * @param blockingNotificationQueue - Blocking Queue assigned to the worker
 */
public HTTPNotifier(CountDownLatch startSignal,
        BlockingQueue<AbstractMap.SimpleEntry<Uri,Notification>> blockingNotificationQueue) {
    this.run = false;
    this.startSignal = startSignal;
    this.blockingNotificationQueue = blockingNotificationQueue;
    handler = new BasicResponseHandler();
    this.api = new DpnAPI2(ZMQClientPool.getInstance().getWorker());
}
项目:AndroTickler    文件:OtherUtil.java   
/**
 * As in different functions in Searcher
 * @param hits  ARraylist of SimpleEntry, obtained after searching for a key
 * @param toBeReplaced  Replace the long path name, such as TicklerVars.jClassDir
 * @param replacement   Replacement such as [Data_Dir]
 */
public static void printSimpleEntryArray(ArrayList<SimpleEntry> hits, String toBeReplaced, String replacement) {
    if (!hits.isEmpty()){
        OutBut.printNormal(hits.size()+" Search Results are found :\n===============================\n");
        for (SimpleEntry e: hits){
            String filePath = e.getKey().toString().replaceAll(toBeReplaced, replacement); 
            System.out.println("#FileName: "+filePath);
            System.out.println(" "+e.getValue()+"\n");
        }

        OutBut.printStep("Where "+replacement+" is "+toBeReplaced);
    }
}
项目:AndroTickler    文件:SearchUtil.java   
/**
 * After searching for a key in files (which is faster), Refine the search by searching for a regex in the first search's result. 
 * @param eArray
 * @param regex
 * @return
 */
public ArrayList<SimpleEntry> refineSearch(ArrayList<SimpleEntry> eArray, String regex){
    ArrayList<SimpleEntry> result = new ArrayList<>();
    ArrayList<String> regexResult = new ArrayList<>();
    for (SimpleEntry e: eArray){
        regexResult = OtherUtil.getRegexFromString(e.getValue().toString(), regex);
        if (!regexResult.isEmpty())
            result.add(e);
    }

    return result;
}
项目:AndroTickler    文件:JavaSqueezer.java   
/**
 * Search for any possible use of external storage
 */
public void externalStorageInCode(){
    OutBut.printH2("Possible External Storage");
    ArrayList<SimpleEntry> eArray = this.sU.searchForKeyInJava("getExternal",this.codeRoot);

    this.printE(eArray);

}
项目:AndroTickler    文件:JavaSqueezer.java   
/**
 * Search for weak hashes
 */
private void weakCyphers() {
    System.out.println("\n");
    String[] weakCrypto = {"Rot13", "MD4", "MD5", "RC2", "RC4", "SHA1"};
    OutBut.printH2("Possible use of weak Ciphers/hashes");

    ArrayList<SimpleEntry> eA = new ArrayList<>();

    for (String c : weakCrypto)
        eA.addAll(this.sU.searchForKeyInJava(c,this.codeRoot));

    this.printE(eA);
}
项目:AndroTickler    文件:JavaSqueezer.java   
/**
 * Use of cryptography 
 */
private void crypto(){
    OutBut.printH2("Crypto and hashing keywords");
    String[] keys = {"aes", "crypt", "cipher", "sha1", "sha2"};
    ArrayList<SimpleEntry> eA = this.returnFNameLineGroup(keys, false);

    this.printE(this.removeDuplicatedSimpleEntries(eA));
}
项目:spring-webflux-client    文件:RequestHeadersTest.java   
@Test
public void requestHeaders_withList() {
    RequestHeaders requestHeaders = getDynamic("header1", 0);

    HttpHeaders httpHeaders = requestHeaders.encode(new Object[]{asList(12.23D, 234.321D)});
    Assertions.assertThat(httpHeaders)
            .containsExactly(new SimpleEntry<>("header1", asList("12.23", "234.321")));
}
项目:spring-webflux-client    文件:RequestHeadersTest.java   
@Test
public void requestHeaders_withDynamicHeader() {
    RequestHeaders requestHeaders = getDynamic("header1", 0);

    HttpHeaders httpHeaders = requestHeaders.encode(new Object[]{"headerDynamicHeader"});
    Assertions.assertThat(httpHeaders)
            .containsExactly(new SimpleEntry<>("header1", singletonList("headerDynamicHeader")));
}
项目:SubgraphIsomorphismIndex    文件:ProblemContainerNeighbourhoodAware.java   
public static <K, V, W extends Iterable<V>> Entry<K, V> pollFirstEntry(NavigableMap<K, W> map) {
    Entry<K, V> result = null;

    Iterator<Entry<K, W>> itE = map.entrySet().iterator();

    // For robustness, remove entry valueX sets
    while(itE.hasNext()) {
        Entry<K, W> e = itE.next();

        K k = e.getKey();
        Iterable<V> vs = e.getValue();

        Iterator<V> itV = vs.iterator();
        if(itV.hasNext()) {
            V v = itV.next();
            itV.remove();

            if(!itV.hasNext()) {
                itE.remove();
            }

            result = new SimpleEntry<>(k, v);
            break;
        } else {
            itE.remove();
            continue;
        }
    }

    return result;
}