Java Code Examples for java.util.AbstractMap.SimpleEntry

The following examples show how to use java.util.AbstractMap.SimpleEntry. These examples are extracted from open source projects. 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 want to check out the right sidebar which shows the related API usage.
Example 1
Source Project: Bats   Source File: StreamingContainer.java    License: Apache License 2.0 6 votes vote down vote up
private HashMap.SimpleEntry<String, ComponentContextPair<Stream, StreamContext>> deployBufferServerPublisher(
    String connIdentifier, StreamCodec<?> streamCodec, long finishedWindowId, int queueCapacity,
    OperatorDeployInfo.OutputDeployInfo nodi)
    throws UnknownHostException
{
  String sinkIdentifier = "tcp://".concat(nodi.bufferServerHost).concat(":").concat(String.valueOf(nodi.bufferServerPort)).concat("/").concat(connIdentifier);

  StreamContext bssc = new StreamContext(nodi.declaredStreamId);
  bssc.setPortId(nodi.portName);
  bssc.setSourceId(connIdentifier);
  bssc.setSinkId(sinkIdentifier);
  bssc.setFinishedWindowId(finishedWindowId);
  bssc.put(StreamContext.CODEC, streamCodec);
  bssc.put(StreamContext.EVENT_LOOP, eventloop);
  bssc.setBufferServerAddress(InetSocketAddress.createUnresolved(nodi.bufferServerHost, nodi.bufferServerPort));
  bssc.put(StreamContext.BUFFER_SERVER_TOKEN, nodi.bufferServerToken);
  InetAddress inetAddress = bssc.getBufferServerAddress().getAddress();
  if (inetAddress != null && NetUtils.isLocalAddress(inetAddress)) {
    bssc.setBufferServerAddress(new InetSocketAddress(InetAddress.getByName(null), nodi.bufferServerPort));
  }

  Stream publisher = fastPublisherSubscriber ? new FastPublisher(connIdentifier, queueCapacity * 256) : new BufferServerPublisher(connIdentifier, queueCapacity);
  return new HashMap.SimpleEntry<>(sinkIdentifier, new ComponentContextPair<>(publisher, bssc));
}
 
Example 2
Source Project: sdn-rx   Source File: Relationships.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * The value for a relationship can be a scalar object (1:1), a collection (1:n), a map (1:n, but with dynamic
 * relationship types) or a map (1:n) with properties for each relationship.
 * This method unifies the type into something iterable, depending on the given inverse type.
 *
 * @param rawValue The raw value to unify
 * @return A unified collection (Either a collection of Map.Entry for dynamic and relationships with properties
 * or a list of related values)
 */
@Nullable
public static Collection<?> unifyRelationshipValue(Neo4jPersistentProperty property, Object rawValue) {
	Collection<?> unifiedValue;
	if (property.isDynamicAssociation()) {
		if (property.isDynamicOneToManyAssociation()) {
			unifiedValue = ((Map<String, Collection<?>>) rawValue)
				.entrySet()
				.stream()
				.flatMap(e -> e.getValue().stream().map(v -> new SimpleEntry(e.getKey(), v)))
				.collect(toList());
		} else {
			unifiedValue = ((Map<String, Object>) rawValue).entrySet();
		}
	} else if (property.isRelationshipWithProperties()) {
		unifiedValue = ((Map<Object, Object>) rawValue).entrySet();
	} else if (property.isCollectionLike()) {
		unifiedValue = (Collection<Object>) rawValue;
	} else {
		unifiedValue = Collections.singleton(rawValue);
	}
	return unifiedValue;
}
 
Example 3
Source Project: CogniCrypt   Source File: CrySLParser.java    License: Eclipse Public License 2.0 6 votes vote down vote up
private List<CrySLForbiddenMethod> getForbiddenMethods(final EList<ForbMethod> methods) {
	final List<CrySLForbiddenMethod> methodSignatures = new ArrayList<>();
	for (final ForbMethod fm : methods) {
		final JvmExecutable meth = fm.getJavaMeth();
		final List<Entry<String, String>> pars = new ArrayList<>();
		for (final JvmFormalParameter par : meth.getParameters()) {
			pars.add(new SimpleEntry<>(par.getSimpleName(), par.getParameterType().getSimpleName()));
		}
		final List<CrySLMethod> crysl = new ArrayList<>();

		final Event alternative = fm.getRep();
		if (alternative != null) {
			crysl.addAll(CrySLParserUtils.resolveAggregateToMethodeNames(alternative));
		}
		methodSignatures.add(new CrySLForbiddenMethod(
				new CrySLMethod(meth.getDeclaringType().getIdentifier() + "." + meth.getSimpleName(), pars, null, new SimpleEntry<>(UNDERSCORE, ANY_TYPE)), false, crysl));
	}
	return methodSignatures;
}
 
Example 4
public static <T> boolean completePromise(int xid, ClusterResponse<T> response) {
    if (!PROMISE_MAP.containsKey(xid)) {
        return false;
    }
    SimpleEntry<ChannelPromise, ClusterResponse> entry = PROMISE_MAP.get(xid);
    if (entry != null) {
        ChannelPromise promise = entry.getKey();
        if (promise.isDone() || promise.isCancelled()) {
            return false;
        }
        entry.setValue(response);
        promise.setSuccess();
        return true;
    }
    return false;
}
 
Example 5
Source Project: jelectrum   Source File: LobstackNode.java    License: MIT License 6 votes vote down vote up
public void getAll(Lobstack stack, BlockingQueue<Map.Entry<String, ByteBuffer> > consumer)
  throws IOException, InterruptedException
{
  for(String key : children.keySet())
  {
    NodeEntry ne = children.get(key);
    if (ne.node)
    {
      stack.loadNodeAt(ne.location).getAll(stack, consumer);
    }
    else
    {
      String data_key = key.substring(0, key.length()-1);
      consumer.put(new SimpleEntry<String,ByteBuffer>(data_key, stack.loadAtLocation(ne.location)));
    }
  }
 
}
 
Example 6
/**
 * Given a PCollection of String's each representing an MusicBrainzDataObject transform those strings into
 * MusicBrainzDataObject's where the name space for the MusicBrainzDataObject is 'name'
 *
 * @param text    the json string representing the MusicBrainzDataObject
 * @param name    the namespace for hte MusicBrainzDataObject
 * @param mappers variable number of lookup descriptions - lookup descriptions can be created using the
 *                factory method lookup();
 * @return PCollection of MusicBrainzDataObjects
 */

public static PCollection<KV<Long, MusicBrainzDataObject>> loadTableFromText(PCollection<String> text, String name,
                                                                             String keyName,
                                                                             LookupDescription... mappers) {
  //[START lookupTableWithSideInputs2]
  List<SimpleEntry<ArrayList<String>, PCollectionView<Map<Long, String>>>> mapSideInputs = new ArrayList<SimpleEntry<ArrayList<String>, PCollectionView<Map<Long, String>>>>();

  for (LookupDescription mapper : mappers) {
    PCollectionView<Map<Long, String>> mapView = loadMap(text.getPipeline(), mapper.objectName, mapper.keyKey, mapper.valueKey);
    List<String> destKeyList = 
        mapper.destinationKeys.stream()
                              .map( destinationKey -> name + "_" + destinationKey )
                              .collect(Collectors.toList());

      mapSideInputs.add(new SimpleEntry(destKeyList, mapView));

  }
  //[END lookupTableWithSideInputs2]
  return loadTableFromText(text, name, keyName, mapSideInputs);
}
 
Example 7
Source Project: anomaly-detection   Source File: ADStateManager.java    License: Apache License 2.0 6 votes vote down vote up
private ActionListener<GetResponse> onGetResponse(String adID, ActionListener<Optional<AnomalyDetector>> listener) {
    return ActionListener.wrap(response -> {
        if (response == null || !response.isExists()) {
            listener.onResponse(Optional.empty());
            return;
        }

        String xc = response.getSourceAsString();
        LOG.info("Fetched anomaly detector: {}", xc);

        try (
            XContentParser parser = XContentType.JSON.xContent().createParser(xContentRegistry, LoggingDeprecationHandler.INSTANCE, xc)
        ) {
            ensureExpectedToken(XContentParser.Token.START_OBJECT, parser.nextToken(), parser::getTokenLocation);
            AnomalyDetector detector = AnomalyDetector.parse(parser, response.getId());
            currentDetectors.put(adID, new SimpleEntry<>(detector, clock.instant()));
            listener.onResponse(Optional.of(detector));
        } catch (Exception t) {
            LOG.error("Fail to parse detector {}", adID);
            LOG.error("Stack trace:", t);
            listener.onResponse(Optional.empty());
        }
    }, listener::onFailure);
}
 
Example 8
Source Project: openhab-core   Source File: RunRuleModuleTest.java    License: Eclipse Public License 2.0 6 votes vote down vote up
private Rule createOuterRule() {
    final Configuration outerRuleTriggerConfig = new Configuration(Collections.unmodifiableMap(Stream
            .of(new SimpleEntry<>("eventSource", "ruleTrigger"), new SimpleEntry<>("eventTopic", "smarthome/*"),
                    new SimpleEntry<>("eventTypes", "ItemStateEvent"))
            .collect(Collectors.toMap((e) -> e.getKey(), (e) -> e.getValue()))));

    final List<String> ruleUIDs = new ArrayList<>();
    ruleUIDs.add("exampleSceneRule");

    final Configuration outerRuleActionConfig = new Configuration(
            Collections.unmodifiableMap(Stream.of(new SimpleEntry<>("ruleUIDs", ruleUIDs))
                    .collect(Collectors.toMap((e) -> e.getKey(), (e) -> e.getValue()))));

    final Rule outerRule = RuleBuilder.create("sceneActivationRule")
            .withTriggers(ModuleBuilder.createTrigger().withId("ItemStateChangeTrigger2")
                    .withTypeUID("core.GenericEventTrigger").withConfiguration(outerRuleTriggerConfig).build())
            .withActions(ModuleBuilder.createAction().withId("RunRuleAction1").withTypeUID("core.RunRuleAction")
                    .withConfiguration(outerRuleActionConfig).build())
            .withName("scene activator").build();

    return outerRule;
}
 
Example 9
@Test
public void reducedFilter_Test() throws Exception {
    Map<String, Object> item1 = new HashMap<>();
    item1.put("id", 1);
    item1.put("name", "john");
    item1.put("age", 24);

    Map<String, Object> item2 = new HashMap<>();
    item2.put("id", 2);
    item2.put("name", "mike");
    item2.put("age", 50);

    Map<String, Object>[] filtered = Snippets.reducedFilter((Map<String, Object>[]) new Map[]{item1, item2}, new String[]{"id", "name"}, item -> (Integer) item.get("age") > 24);
    assertThat(filtered).hasSize(1);
    assertThat(filtered[0])
            .containsOnly(
                    new SimpleEntry<String, Object>("id", 2),
                    new SimpleEntry<String, Object>("name", "mike"));
}
 
Example 10
Source Project: Chimera   Source File: CommandParser.java    License: MIT License 6 votes vote down vote up
protected void check(T type, Command command, String name, Label label) {
    if (matcher.reset(name).matches()) {
        environment.error(type, format(name, "is not a valid command " + label, "should not contain whitespaces"));
        return;
        
    } else if (name.isEmpty()) {
        environment.error(type, "Command " + label + " should not be empty");
        return;
    }
    
    var entry = names.get(name);
    if (entry == null) {
        names.put(name, new SimpleEntry<>(command, label));
        
    } else {
        environment.error(type, format(name, "already exists", "commands should not have the same aliases and names"));
    }
}
 
Example 11
Source Project: streamex   Source File: EntryStreamTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testSelect() {
    Map<Object, Object> map = new LinkedHashMap<>();
    map.put("a", 1);
    map.put("b", "2");
    map.put(3, "c");
    assertEquals(Collections.singletonMap("a", 1), EntryStream.of(map).selectValues(Integer.class).toMap());
    assertEquals(Collections.singletonMap(3, "c"), EntryStream.of(map).selectKeys(Integer.class).toMap());

    // Weird way to create a map from the array. Don't do this in production
    // code!
    Object[] interleavingArray = { "a", 1, "bb", 22, "ccc", 33 };
    Map<String, Integer> result = EntryStream.of(
        StreamEx.of(interleavingArray).pairMap(SimpleEntry::new)).selectKeys(String.class)
            .selectValues(Integer.class).toMap();
    assertEquals(createMap(), result);
}
 
Example 12
Source Project: cloudbreak   Source File: HueConfigProviderTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void getServiceConfigsWhenKnoxConfiguredToExternalDomain() {
    BlueprintView blueprintView = getMockBlueprintView("7.0.2", "7.0.2");

    GeneralClusterConfigs generalClusterConfigs = new GeneralClusterConfigs();
    generalClusterConfigs.setExternalFQDN("myaddress.cloudera.site");
    generalClusterConfigs.setKnoxUserFacingCertConfigured(true);
    generalClusterConfigs.setPrimaryGatewayInstanceDiscoveryFQDN(Optional.of("private-gateway.cloudera.site"));
    TemplatePreparationObject tpo = new Builder()
            .withGeneralClusterConfigs(generalClusterConfigs)
            .withBlueprintView(blueprintView)
            .withGateway(new Gateway(), "", new HashSet<>())
            .build();
    List<ApiClusterTemplateConfig> result = underTest.getServiceConfigs(null, tpo);
    Map<String, String> paramToVariable =
            result.stream().collect(Collectors.toMap(ApiClusterTemplateConfig::getName, ApiClusterTemplateConfig::getVariable));
    assertThat(paramToVariable).containsOnly(
            new SimpleEntry<>("database_host", "hue-hue_database_host"),
            new SimpleEntry<>("database_port", "hue-hue_database_port"),
            new SimpleEntry<>("database_name", "hue-hue_database_name"),
            new SimpleEntry<>("database_type", "hue-hue_database_type"),
            new SimpleEntry<>("database_user", "hue-hue_database_user"),
            new SimpleEntry<>("database_password", "hue-hue_database_password"),
            new SimpleEntry<>("hue_service_safety_valve", "hue-hue_service_safety_valve")
    );
}
 
Example 13
/**
 * Extract the tag and name from an XML element
 *
 * @param element
 *            the XML element
 * @param tagAttribute
 *            the tag attribute
 * @param nameAttribute
 *            the name attribute
 * @return an entry where the key is the tag and the value is the name
 * @since 2.1
 */
protected static Entry<@NonNull Tag, @NonNull String> extractTagAndName(Element element, String tagAttribute, String nameAttribute) {
    Tag tag = Tag.fromName(element.getAttribute(tagAttribute));
    String name = element.getAttribute(nameAttribute);
    if (tag == null) {
        // Backward compatibility
        if (name.equals(Messages.CustomTraceDefinition_timestampTag)) {
            tag = Tag.TIMESTAMP;
            name = checkNotNull(Tag.TIMESTAMP.toString());
        } else if (name.equals(Messages.CustomTraceDefinition_messageTag)) {
            tag = Tag.MESSAGE;
            name = checkNotNull(Tag.MESSAGE.toString());
        } else if (name.equals(Messages.CustomXmlTraceDefinition_ignoreTag)) {
            tag = Tag.IGNORE;
            name = checkNotNull(Tag.IGNORE.toString());
        } else {
            tag = Tag.OTHER;
        }
    } else if (name.isEmpty()) {
        name = checkNotNull(tag.toString());
    }
    return new SimpleEntry<>(tag, name);
}
 
Example 14
Source Project: yuvi   Source File: Query.java    License: Apache License 2.0 6 votes vote down vote up
public Query(final String metricName, final List<TagMatcher> tagMatchers) {
  if (metricName == null || metricName.isEmpty() || tagMatchers == null) {
    throw new IllegalArgumentException("metric name or tag matcher can't be null.");
  }

  final Map<String, List<TagMatcher>> tagNameMap = tagMatchers.stream()
      .map(t -> new SimpleEntry<>(t.tag.key, t))
      .collect(groupingBy(Entry::getKey, mapping(Entry::getValue, toList())));

  tagNameMap.entrySet().forEach(tagKeyEntry -> {
    if (tagKeyEntry.getValue().size() != 1) {
      throw new IllegalArgumentException("Only one tagFilter is allowed per tagKey: "
          + tagKeyEntry.getKey() + " .But we found " + tagKeyEntry.getValue().toString());
    }
  });

  this.metricName = metricName;
  this.tagMatchers = tagMatchers;
}
 
Example 15
Source Project: XHAIL   Source File: Acquirer.java    License: GNU General Public License v3.0 6 votes vote down vote up
public Map.Entry<Values, Collection<Collection<String>>> parse() {
	this.answers = new HashSet<>();
	try {
		if (UNKNOWN.equals(token))
			parseUNKNOWN();
		else if (UNSATISFIABLE.equals(token))
			parseUNSATISFIABLE();
		else
			parseAnswer();
		parseEOF();
	} catch (ParserErrorException e) {
		Logger.error(e.getMessage());
		// return null;
	}
	return new SimpleEntry<Values, Collection<Collection<String>>>(this.values, this.answers);
}
 
Example 16
Source Project: openjdk-jdk8u   Source File: TestPrintXML.java    License: GNU General Public License v2.0 6 votes vote down vote up
@Override
public void startElement(String uri, String localName, String qName, Attributes attrs) throws SAXException {
    elements.push(new SimpleEntry<>(attrs.getValue("name"), attrs.getValue("index")));
    String nil = attrs.getValue("xsi:nil");
    if ("true".equals(nil)) {
        objects.push(null);
        return;
    }

    switch (qName) {
    case "event":
        objects.push(new XMLEvent(attrs.getValue("type")));
        break;
    case "struct":
        objects.push(new HashMap<String, Object>());
        break;
    case "array":
        objects.push(new Object[Integer.parseInt(attrs.getValue("size"))]);
        break;
    case "value":
        objects.push(new StringBuilder());
        break;
    }
}
 
Example 17
Source Project: XHAIL   Source File: SchemeTerm.java    License: GNU General Public License v3.0 6 votes vote down vote up
public static Map.Entry<Collection<Atom>, Collection<Term>> matchAndOutput(Scheme scheme, Collection<Atom> atoms, Collection<Term> substitutes) {
	if (null == scheme)
		throw new IllegalArgumentException("Illegal 'scheme' argument in SchemeTerm.matchAndOutput(Scheme, Collection<Atom>, Collection<Term>): " + scheme);
	if (null == atoms)
		throw new IllegalArgumentException("Illegal 'atoms' argument in SchemeTerm.matchAndOutput(Scheme, Collection<Atom>, Collection<Term>): " + atoms);
	if (null == substitutes)
		throw new IllegalArgumentException("Illegal 'substitutes' argument in SchemeTerm.matchAndOutput(Scheme, Collection<Atom>, Collection<Term>): "
				+ substitutes);
	Set<Atom> matches = new HashSet<>();
	Set<Term> outputs = new HashSet<>();
	for (Atom atom : atoms) {
		Collection<Term> output = matchAndOutput(scheme, atom, substitutes);
		if (null != output) {
			matches.add(atom);
			outputs.addAll(output);
		}
	}
	return new SimpleEntry<Collection<Atom>, Collection<Term>>(matches, outputs);
}
 
Example 18
Source Project: SPADE   Source File: ProcessUnitState.java    License: GNU General Public License v3.0 5 votes vote down vote up
protected boolean hasTheNamespaceEverBeenSeenForProcess(NamespaceIdentifier namespace){
	for(SimpleEntry<AgentIdentifier, NamespaceIdentifier> value : timeToAgentAndNamespace.getValues()){
		if(namespace.equals(value.getValue())){
			return true;
		}
	}
	return false;
}
 
Example 19
Source Project: lucene-solr   Source File: FileDictionaryTest.java    License: Apache License 2.0 5 votes vote down vote up
private Map.Entry<List<List<String>>,String> generateFileInput(int count, String fieldDelimiter, boolean hasWeights, boolean hasPayloads) {
  List<List<String>> entries = new ArrayList<>();
  StringBuilder sb = new StringBuilder();
  boolean hasPayload = hasPayloads;
  for (int i = 0; i < count; i++) {
    if (hasPayloads) {
      hasPayload = (i==0) ? true : random().nextBoolean();
    } 
    Map.Entry<List<String>, String> entrySet = generateFileEntry(fieldDelimiter, (!hasPayloads && hasWeights) ? random().nextBoolean() : hasWeights, hasPayload);
    entries.add(entrySet.getKey());
    sb.append(entrySet.getValue());
  }
  return new SimpleEntry<>(entries, sb.toString());
}
 
Example 20
Source Project: AndroTickler   Source File: SearchUtil.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 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;
}
 
Example 21
@Override
public void lockBindings(int companyId, List<SimpleEntry<Integer, Integer>> cmPairs) {
	StringBuffer selForUpd = new StringBuffer("select * from customer_" + companyId + "_binding_tbl where (customer_id,mailinglist_id) in (");
	boolean first = true;
	for (SimpleEntry<Integer, Integer> entry : cmPairs) {
		if (!first) {
			selForUpd.append(",");
		}
		selForUpd.append("("+entry.getKey()+","+entry.getValue()+")");
		first = false;
	}
	selForUpd.append(") for update");
	select(logger, selForUpd.toString());
}
 
Example 22
Source Project: SPADE   Source File: ProcessWithAgentState.java    License: GNU General Public License v3.0 5 votes vote down vote up
protected void setAgentAndNamespace(Double time, AgentIdentifier agent, NamespaceIdentifier namespace){
	super.setAgentAndNamespace(time, agent, namespace);
	previousProcessAgentsAndNamespaces.add(new SimpleEntry<AgentIdentifier, NamespaceIdentifier>(agent, namespace));
	if(isUnitActive()){
		previousUnitAgentsAndNamespaces.add(new SimpleEntry<AgentIdentifier, NamespaceIdentifier>(agent, namespace));
	}
}
 
Example 23
Source Project: CogniCrypt   Source File: GeneratorMethod.java    License: Eclipse Public License 2.0 5 votes vote down vote up
public void addStatementToBody(String statement) {
	body.append(statement);
	int index = -1;
	if ((index = statement.indexOf('=')) > 0) {
		String[] varDecl = statement.substring(0, index).split(" ");
		if (varDecl.length == 2) {
			SimpleEntry<String, String> newVar = new SimpleEntry<>(varDecl[1], varDecl[0]);
			if (!variableDeclarations.contains(newVar)) {
				variableDeclarations.add(newVar);
			}
		}
	}
	body.append("\n");
}
 
Example 24
Source Project: pravega   Source File: PersistentStreamBase.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Seal a transaction in OPEN/COMMITTING_TXN/ABORTING state. This method does CAS on the transaction VersionedMetadata node if
 * the transaction is in OPEN state, optionally checking version of transaction VersionedMetadata node, if required.
 *
 * @param epoch   transaction epoch.
 * @param txId    transaction identifier.
 * @param commit  boolean indicating whether to commit or abort the transaction.
 * @param version optional expected version of transaction node to validate before updating it.
 * @param writerId writer Id
 * @param timestamp commit timestamp supplied by writer
 * @return        a pair containing transaction status and its epoch.
 */
private CompletableFuture<SimpleEntry<TxnStatus, Integer>> sealActiveTxn(final int epoch,
                                                                         final UUID txId,
                                                                         final boolean commit,
                                                                         final Optional<Version> version, 
                                                                         final String writerId, final long timestamp) {
    return getActiveTx(epoch, txId).thenCompose(data -> {
        ActiveTxnRecord txnRecord = data.getObject();
        Version dataVersion = version.orElseGet(data::getVersion);
        TxnStatus status = txnRecord.getTxnStatus();
        switch (status) {
            case OPEN:
                return sealActiveTx(epoch, txId, commit, txnRecord, dataVersion, writerId, timestamp).thenApply(y ->
                        new SimpleEntry<>(commit ? TxnStatus.COMMITTING : TxnStatus.ABORTING, epoch));
            case COMMITTING:
            case COMMITTED:
                if (commit) {
                    return CompletableFuture.completedFuture(new SimpleEntry<>(status, epoch));
                } else {
                    throw StoreException.create(StoreException.Type.ILLEGAL_STATE,
                            "Stream: " + getName() + " Transaction: " + txId.toString() +
                                    " State: " + status.name());
                }
            case ABORTING:
            case ABORTED:
                if (commit) {
                    throw StoreException.create(StoreException.Type.ILLEGAL_STATE,
                            "Stream: " + getName() + " Transaction: " + txId.toString() + " State: " +
                                    status.name());
                } else {
                    return CompletableFuture.completedFuture(new SimpleEntry<>(status, epoch));
                }
            default:
                throw StoreException.create(StoreException.Type.DATA_NOT_FOUND,
                        "Stream: " + getName() + " Transaction: " + txId.toString());
        }
    });
}
 
Example 25
Source Project: 99-problems   Source File: P36.java    License: MIT License 5 votes vote down vote up
public static List<SimpleEntry<Integer, List<Integer>>> goldbach_list1(IntStream range, int greaterThan) {
    return goldbach_list(range)
            .stream()
            .filter(g -> g.getValue().get(0) > greaterThan && g.getValue().get(1) > greaterThan)
            .collect(toList());

}
 
Example 26
Source Project: anomaly-detection   Source File: FeatureManagerTests.java    License: Apache License 2.0 5 votes vote down vote up
private Object[] getColdStartDataTestData() {
    double[][] samples = new double[][] { { 1.0 } };
    return new Object[] {
        new Object[] { 1L, new SimpleEntry<>(samples, 1), 1, samples },
        new Object[] { 1L, null, 1, null },
        new Object[] { null, new SimpleEntry<>(samples, 1), 1, null },
        new Object[] { null, null, 1, null }, };
}
 
Example 27
Source Project: chassis   Source File: ConfigurationBuilderTest.java    License: Apache License 2.0 5 votes vote down vote up
@SuppressWarnings({ "unchecked", "rawtypes" })
@Before
   public void setup() throws Exception {
   	initializeZookeeper();
   	
       configurationBuilder = new ConfigurationBuilder(APP_NAME, ENVIRONMENT, true, BootstrapConfiguration.REFLECTIONS);
       configurationBuilder.withAppVersion(APP_VERSION);

       TestUtils.resetArchaius();
       resetZookeeper();

       TestUtils.writePropertiesToFile(TEST_MODULE_CONFIG_PROPERTIES, filesCreated, new SimpleEntry[]{new SimpleEntry(MODULE_1_KEY_1, MODULE_1_VALUE_1), new SimpleEntry(MODULE_1_KEY_2, MODULE_1_VALUE_2), new SimpleEntry(MODULE_1_KEY_3, MODULE_1_VALUE_3)});
       TestUtils.writePropertiesToFile(TEST_MODULE_CONFIG_PROPERTIES_2, filesCreated, new SimpleEntry(MODULE_2_KEY_1, MODULE_2_VALUE_1));
   }
 
Example 28
Source Project: 99-problems   Source File: P11.java    License: MIT License 5 votes vote down vote up
public static <T> List<Object> encode_modified(List<T> list) {
    return P09.pack(list).stream().map(l -> {
        if (l.size() == 1) {
            return l.get(0);
        }
        return new SimpleEntry<>(l.size(), l.get(0));
    }).collect(toList());
}
 
Example 29
Source Project: olingo-odata4   Source File: JsonDeserializer.java    License: Apache License 2.0 5 votes vote down vote up
private Map.Entry<PropertyType, EdmTypeInfo> guessPropertyType(final JsonNode node) {
  PropertyType type;
  String typeExpression = null;

  if (node.isValueNode() || node.isNull()) {
    type = PropertyType.PRIMITIVE;
    typeExpression = guessPrimitiveTypeKind(node).getFullQualifiedName().toString();
  } else if (node.isArray()) {
    type = PropertyType.COLLECTION;
    if (node.has(0) && node.get(0).isValueNode()) {
      typeExpression = "Collection(" + guessPrimitiveTypeKind(node.get(0)) + ')';
    }
  } else if (node.isObject()) {
    if (node.has(Constants.ATTR_TYPE)) {
      type = PropertyType.PRIMITIVE;
      typeExpression = "Edm.Geography" + node.get(Constants.ATTR_TYPE).asText();
    } else {
      type = PropertyType.COMPLEX;
    }
  } else {
    type = PropertyType.EMPTY;
  }

  final EdmTypeInfo typeInfo = typeExpression == null ? null :
    new EdmTypeInfo.Builder().setTypeExpression(typeExpression).build();
  return new SimpleEntry<>(type, typeInfo);
}
 
Example 30
Source Project: styx   Source File: MapStreamTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void mapsEntries() {
    Map<String, String> result = MapStream.stream(map)
            .map((key, value) -> new SimpleEntry<>(
                    "foo." + key,
                    value.toUpperCase()
            ))
            .toMap();

    assertThat(result.size(), is(3));
    assertThat(result, hasEntry("foo.firstName", "JOHN"));
    assertThat(result, hasEntry("foo.lastName", "SMITH"));
    assertThat(result, hasEntry("foo.dateOfBirth", "1970-01-01"));
}