Java Code Examples for java.util.SortedMap#put()

The following examples show how to use java.util.SortedMap#put() . 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: TxPoolV1.java    From aion with MIT License 6 votes vote down vote up
private void poolAdd(ByteArrayWrapper txHash, PooledTransaction poolTx) {

        LOG_TXPOOL.debug("Adding tx[{}]", poolTx.tx);

        poolTransactions.put(txHash, poolTx);
        long txTime = TimeUnit.MICROSECONDS.toSeconds(poolTx.tx.getTimeStampBI().longValue()) + transactionTimeout;
        Set<ByteArrayWrapper> timeSet = timeView.getOrDefault(txTime, new LinkedHashSet<>());
        timeView.putIfAbsent(txTime, timeSet);
        timeSet.add(txHash);

        long txEnergyPrice = poolTx.tx.getEnergyPrice();
        Set<ByteArrayWrapper> feeSet = feeView.getOrDefault(txEnergyPrice, new LinkedHashSet<>());
        feeView.putIfAbsent(txEnergyPrice, feeSet);
        feeSet.add(txHash);

        SortedMap<BigInteger, ByteArrayWrapper> accountInfo = accountView.getOrDefault(poolTx.tx.getSenderAddress(), new TreeMap<>());
        accountView.putIfAbsent(poolTx.tx.getSenderAddress(), accountInfo);
        accountInfo.put(poolTx.tx.getNonceBI(), txHash);

        LOG_TXPOOL.debug("Added tx[{}]", poolTx.tx);
    }
 
Example 2
Source File: FormattingReviewAssistant.java    From naturalize with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Position the renaming in the text.
 * 
 * @param testSourceFile
 * @param suggestedRenamings
 * @return
 */
private SortedMap<Integer, SortedSet<Renaming>> postionRenamings(
		final String testSourceFile,
		final SortedMap<Integer, SortedSet<Renaming>> suggestedRenamings) {
	final List<String> tokensPos = tokenizer
			.tokenListFromCode(testSourceFile.toCharArray());

	// Hack: reverse engineer list to do something useful
	final SortedMap<Integer, SortedSet<Renaming>> positionedRenamings = Maps
			.newTreeMap();
	int i = 0;
	for (final Entry<Integer, String> token : tokenizer.getBaseTokenizer()
			.tokenListWithPos(testSourceFile.toCharArray()).entrySet()) {
		if (suggestedRenamings.containsKey(i)) {
			positionedRenamings.put(token.getKey(),
					suggestedRenamings.get(i));
		}
		if (tokensPos.get(i).equals(FormattingTokenizer.WS_NO_SPACE)) {
			i++;
		}
		i++;
	}

	return positionedRenamings;
}
 
Example 3
Source File: JavaTypeTokenizer.java    From tassal with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * @param tokens
 * @param cu
 * @return
 */
public SortedMap<Integer, FullToken> doApproximateTypeInference(
		final SortedMap<Integer, FullToken> tokens, final ASTNode cu) {
	final JavaApproximateTypeInferencer tInf = new JavaApproximateTypeInferencer(
			cu);
	tInf.infer();
	final Map<Integer, String> types = tInf.getVariableTypesAtPosition();

	final SortedMap<Integer, FullToken> typeTokenList = Maps.newTreeMap();
	for (final Entry<Integer, FullToken> token : tokens.entrySet()) {
		final String type = types.get(token.getKey());
		if (type != null) {
			typeTokenList.put(token.getKey(), new FullToken("var%" + type
					+ "%", token.getValue().tokenType));
		} else {
			typeTokenList.put(token.getKey(),
					new FullToken(token.getValue().token,
							token.getValue().tokenType));
		}
	}
	return typeTokenList;
}
 
Example 4
Source File: ContextBuilder.java    From Elasticsearch with Apache License 2.0 6 votes vote down vote up
public static SortedMap<String, ContextMapping> loadMappings(Object configuration, Version indexVersionCreated)
        throws ElasticsearchParseException {
    if (configuration instanceof Map) {
        Map<String, Object> configurations = (Map<String, Object>)configuration;
        SortedMap<String, ContextMapping> mappings = Maps.newTreeMap();
        for (Entry<String,Object> config : configurations.entrySet()) {
            String name = config.getKey();
            mappings.put(name, loadMapping(name, (Map<String, Object>) config.getValue(), indexVersionCreated));
        }
        return mappings;
    } else if (configuration == null) {
        return ContextMapping.EMPTY_MAPPING;
    } else {
        throw new ElasticsearchParseException("no valid context configuration");
    }
}
 
Example 5
Source File: CppWhitespaceTokenizer.java    From api-mining with GNU General Public License v3.0 6 votes vote down vote up
@Override
public SortedMap<Integer, String> tokenListWithPos(final char[] code) {
	final SortedMap<Integer, String> tokens = Maps.newTreeMap();
	tokens.put(-1, SENTENCE_START);
	tokens.put(Integer.MAX_VALUE, SENTENCE_END);

	final Scanner scanner = new Scanner();
	scanner.setSource(code);
	final WhitespaceToTokenConverter wsConverter = new WhitespaceToTokenConverter();
	do {
		final int token = scanner.getNextToken();
		if (token == Token.tWHITESPACE) {
			final String wsToken = wsConverter
					.toWhiteSpaceSymbol(new String(scanner
							.getCurrentTokenSource()));
			tokens.put(scanner.getCurrentPosition(), wsToken);
		} else {
			final String nxtToken = new String(
					scanner.getCurrentTokenSource());
			tokens.put(scanner.getCurrentPosition(),
					getTokenType(token, nxtToken));
		}
	} while (!scanner.atEnd());
	return tokens;
}
 
Example 6
Source File: JdbcMySqlBinLogRecordReader.java    From datacollector with Apache License 2.0 6 votes vote down vote up
/**
 * Records from MySQL BinLog origin have a bit unique structure.
 *
 * Records for Insert and update operations have a field path "/Data", which is a map
 * of all column names as key and values stored in DB as value.
 *
 * Record for Delete operation don't have /Data field. Instead it has a filed path "/OldData",
 * which store the original data in table. So need to look into /OldData when operation is delete.
 *
 * We expect user to configure /Data as a filed path in column-filed mapping configuration.
 * @param record
 * @param op
 * @param parameters
 * @param columnsToFields
 * @return
 */
@Override
public SortedMap<String, String> getColumnsToParameters(
    final Record record, int op,
    Map<String, String> parameters,
    Map<String, String> columnsToFields)
{
  SortedMap<String, String> columnsToParameters = new TreeMap<>();
  for (Map.Entry<String, String> entry : columnsToFields.entrySet()) {
    String columnName = entry.getKey();
    String fieldPath = entry.getValue();
    if(op == OperationType.DELETE_CODE){
      fieldPath = fieldPath.replace(DATA_FIELD, OLD_DATA_FIELD);
    }

    if (record.has(fieldPath)) {
      columnsToParameters.put(columnName, parameters.get(columnName));
    }
  }
  return columnsToParameters;
}
 
Example 7
Source File: TokenTypeTokenizer.java    From codemining-core with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Override
public SortedMap<Integer, FullToken> fullTokenListWithPos(final char[] code) {
	final Iterable<Token> tokens = lexer.getTokens(new String(code));
	final SortedMap<Integer, FullToken> tokensWithPos = Maps.newTreeMap();
	tokensWithPos.put(-1, new FullToken(SENTENCE_START, SENTENCE_START));
	tokensWithPos.put(Integer.MAX_VALUE, new FullToken(SENTENCE_END,
			SENTENCE_END));
	for (final Token tok : tokens) {
		if (isProgramToken(tok)) {
			continue;
		}
		tokensWithPos.put(tok.getPos(), new FullToken(getTokenString(tok),
				""));
	}
	return tokensWithPos;
}
 
Example 8
Source File: AbstractCdtASTAnnotatedTokenizer.java    From codemining-core with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public SortedMap<Integer, String> tokenListWithPos(final char[] code) {
	final SortedMap<Integer, String> tokens = Maps.newTreeMap();
	for (final Entry<Integer, AstAnnotatedToken> token : getAnnotatedTokens(
			code).entrySet()) {
		tokens.put(token.getKey(), token.getValue().token.token);
	}
	return tokens;
}
 
Example 9
Source File: JavaWhitespaceTokenizer.java    From tassal with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public SortedMap<Integer, String> tokenListWithPos(final char[] code) {
	final SortedMap<Integer, String> tokens = Maps.newTreeMap();
	tokens.put(-1, SENTENCE_START);
	tokens.put(Integer.MAX_VALUE, SENTENCE_END);
	final PublicScanner scanner = prepareScanner(code);

	while (!scanner.atEnd()) {
		do {
			try {
				final int token = scanner.getNextToken();
				final int position = scanner
						.getCurrentTokenStartPosition();
				if (token == ITerminalSymbols.TokenNameEOF) {
					break;
				}
				int i = 0;
				final List<String> cTokens = getConvertedToken(scanner,
						token);
				for (final String cToken : cTokens) {
					tokens.put(position + i, cToken);
					i++;
				}
			} catch (final InvalidInputException e) {
				LOGGER.warning(ExceptionUtils.getFullStackTrace(e));
			}
		} while (!scanner.atEnd());
	}
	return tokens;
}
 
Example 10
Source File: CompletionMinibuffer.java    From e4macs with Eclipse Public License 1.0 5 votes vote down vote up
protected SortedMap<String, ?> getCompletions(String searchSubstr, boolean insensitive, boolean regex) {
	SortedMap<String, ?> result = getCompletions();
	if (searchSubstr != null && result != null) {
		Set<String> keySet = result.keySet();
		String searchStr = (regex ? searchSubstr : toRegex(searchSubstr));
		boolean isRegex = (regex || isRegex(searchStr,searchSubstr));
		if (insensitive || isRegex) {
			try {
				SortedMap<String,? super Object> regResult = new TreeMap<String, Object>();
				Pattern pat = Pattern.compile(searchStr + RWILD, (insensitive ? Pattern.CASE_INSENSITIVE : 0));	//$NON-NLS-1$
				// we have to build the map up one by one on regex search
				for (String key : keySet) {
					if (pat.matcher(key).matches()) {
						regResult.put(key, result.get(key));
					}
				}
				result = regResult; 					
			} catch (Exception e) {
				// ignore any PatternSyntaxException
			}
			if (result.size() == 0 && !insensitive) {
				// try non-regex lookup
				result = getCompletions(searchSubstr, keySet);					
			} 
		} else {
			result = getCompletions(searchSubstr, keySet);
		}
		if ((result == null || result.size() == 0) && !insensitive) {
			// try once with case insensitivity
			return getCompletions(searchSubstr, true, regex);
		}
	}
	return result;
}
 
Example 11
Source File: BDDFactory.java    From LogicNG with Apache License 2.0 5 votes vote down vote up
/**
 * Returns how often each variable occurs in the given BDD.
 * @param bdd the BDD
 * @return how often each variable occurs in the BDD
 */
public SortedMap<Variable, Integer> variableProfile(final BDD bdd) {
  final int[] varProfile = this.kernel.varProfile(bdd.index());
  final SortedMap<Variable, Integer> profile = new TreeMap<>();
  for (int i = 0; i < varProfile.length; i++) {
    profile.put(this.idx2var.get(i), varProfile[i]);
  }
  return profile;
}
 
Example 12
Source File: TestCloudSchemaless.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
@Override
public SortedMap<ServletHolder,String> getExtraServlets() {
  final SortedMap<ServletHolder,String> extraServlets = new TreeMap<>();
  final ServletHolder solrRestApi = new ServletHolder("SolrSchemaRestApi", ServerServlet.class);
  solrRestApi.setInitParameter("org.restlet.application", "org.apache.solr.rest.SolrSchemaRestApi");
  extraServlets.put(solrRestApi, "/schema/*");  // '/schema/*' matches '/schema', '/schema/', and '/schema/whatever...'
  return extraServlets;
}
 
Example 13
Source File: CDefinitionTest.java    From Rhombus with MIT License 5 votes vote down vote up
public void testGetMostSelectiveMatchingIndexMostSelective() throws IOException {
	String json = TestHelpers.readFileToString(this.getClass(), "CObjectCQLGeneratorTestData.js");
	CDefinition definition = CDefinition.fromJsonString(json);
	SortedMap<String, Object> indexValues = new TreeMap<String, Object>();
	indexValues.put("type", "typeValue");
	indexValues.put("foreignid", 13);
	indexValues.put("instance", 11);

	CIndex matchingIndex = definition.getMostSelectiveMatchingIndex(indexValues);
	String expectedIndexKey = Joiner.on(":").join(indexValues.keySet());
	assertEquals(expectedIndexKey, matchingIndex.getKey());
}
 
Example 14
Source File: BitSetsTest.java    From calcite with Apache License 2.0 5 votes vote down vote up
/**
 * Tests the method {@link BitSets#closure(java.util.SortedMap)}
 */
@Test void testClosure() {
  final SortedMap<Integer, BitSet> empty = new TreeMap<>();
  assertThat(BitSets.closure(empty), equalTo(empty));

  // Map with an an entry for each position.
  final SortedMap<Integer, BitSet> map = new TreeMap<>();
  map.put(0, BitSets.of(3));
  map.put(1, BitSets.of());
  map.put(2, BitSets.of(7));
  map.put(3, BitSets.of(4, 12));
  map.put(4, BitSets.of());
  map.put(5, BitSets.of());
  map.put(6, BitSets.of());
  map.put(7, BitSets.of());
  map.put(8, BitSets.of());
  map.put(9, BitSets.of());
  map.put(10, BitSets.of());
  map.put(11, BitSets.of());
  map.put(12, BitSets.of());
  final String original = map.toString();
  final String expected =
      "{0={3, 4, 12}, 1={}, 2={7}, 3={3, 4, 12}, 4={4, 12}, 5={}, 6={}, 7={7}, 8={}, 9={}, 10={}, 11={}, 12={4, 12}}";
  assertThat(BitSets.closure(map).toString(), equalTo(expected));
  assertThat("argument modified", map.toString(), equalTo(original));

  // Now a similar map with missing entries. Same result.
  final SortedMap<Integer, BitSet> map2 = new TreeMap<>();
  map2.put(0, BitSets.of(3));
  map2.put(2, BitSets.of(7));
  map2.put(3, BitSets.of(4, 12));
  map2.put(9, BitSets.of());
  final String original2 = map2.toString();
  assertThat(BitSets.closure(map2).toString(), equalTo(expected));
  assertThat("argument modified", map2.toString(), equalTo(original2));
}
 
Example 15
Source File: TripoliFraction.java    From ET_Redux with Apache License 2.0 5 votes vote down vote up
/**
 *
 * @return
 */
public SortedMap<String, ValueModel> assembleCommonLeadCorrectionParameters() {
    SortedMap<String, ValueModel> parameters = new TreeMap<>();

    // initial pb model parameters
    parameters.put("r207_206c", initialPbSchemeA_r207_206c);
    parameters.put("r206_204c", initialPbSchemeB_R206_204c);
    parameters.put("r207_204c", initialPbSchemeB_R207_204c);
    parameters.put("r208_204c", initialPbSchemeB_R208_204c);

    return parameters;
}
 
Example 16
Source File: ArchiveDatasetSource.java    From mr4c with Apache License 2.0 5 votes vote down vote up
protected Collection<DataKey> getSortedFileKeys(Dataset dataset) {
	DataKeyFileMapper mapper = m_config.getKeyFileMapper();
	SortedMap<String,DataKey> map = new TreeMap<String,DataKey>();
	for ( DataKey key : dataset.getAllFileKeys() ) {
		String name = mapper.getFileName(key);
		map.put(name,key);
	}
	return map.values();
}
 
Example 17
Source File: InputGestureTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public void testReadALogAndTestInputGestures() throws Exception {
    InputStream is = getClass().getResourceAsStream("NB1216449736.0");
    SortedMap<Integer,InputGesture> expectedGestures = new TreeMap<Integer,InputGesture>();
    expectedGestures.put(35, InputGesture.MENU);
    expectedGestures.put(59, InputGesture.KEYBOARD);
    expectedGestures.put(66, InputGesture.MENU);
    expectedGestures.put(80, InputGesture.MENU);
    expectedGestures.put(81, InputGesture.MENU);
    expectedGestures.put(177, InputGesture.KEYBOARD);
    expectedGestures.put(197, InputGesture.KEYBOARD);
    expectedGestures.put(205, InputGesture.MENU);
    TestHandler records = new TestHandler(is);
    for (int cnt = 0;; cnt++) {
        LOG.log(Level.INFO, "Reading {0}th record", cnt);
        LogRecord r = records.read();
        if (r == null) {
            break;
        }
        if (r.getSequenceNumber() > expectedGestures.lastKey()) {
            break;
        }
        LOG.log(Level.INFO, "Read {0}th record, seq {1}", new Object[] { cnt, r.getSequenceNumber() });

        InputGesture g = InputGesture.valueOf(r);
        InputGesture exp = expectedGestures.get((int)r.getSequenceNumber());
        assertEquals(cnt + ": For: " + r.getSequenceNumber() + " txt:\n`"+ r.getMessage() +
            "\nkey: " + r.getResourceBundleName()
            , exp, g);
    }
    is.close();
}
 
Example 18
Source File: SymbolicPolynomial.java    From symja_android_library with GNU General Public License v3.0 5 votes vote down vote up
/**
 * GenPolynomial subtract a multiple.
 * 
 * @param a
 *            coefficient.
 * @param e
 *            exponent.
 * @param S
 *            GenPolynomial.
 * @return this - a x<sup>e</sup> S.
 */
public SymbolicPolynomial subtractMultiple(IExpr a, ExpVectorSymbolic e, SymbolicPolynomial S) {
	if (a == null || a.isZERO()) {
		return this;
	}
	if (S == null || S.isZERO()) {
		return this;
	}
	if (this.isZERO()) {
		return S.multiply(a.negate(), e);
	}
	assert (ring.nvar == S.ring.nvar);
	SymbolicPolynomial n = this.copy();
	SortedMap<ExpVectorSymbolic, IExpr> nv = n.val;
	SortedMap<ExpVectorSymbolic, IExpr> sv = S.val;
	for (Map.Entry<ExpVectorSymbolic, IExpr> me : sv.entrySet()) {
		ExpVectorSymbolic f = me.getKey();
		f = e.sum(f);
		IExpr y = me.getValue(); // assert y != null
		y = a.multiply(y);
		IExpr x = nv.get(f);
		if (x != null) {
			x = x.subtract(y);
			if (!x.isZERO()) {
				nv.put(f, x);
			} else {
				nv.remove(f);
			}
		} else if (!y.isZERO()) {
			nv.put(f, y.negate());
		}
	}
	return n;
}
 
Example 19
Source File: WxMpServiceImpl.java    From weixin-java-tools with Apache License 2.0 4 votes vote down vote up
@Override
public WxMpPayResult getJSSDKPayResult(String transactionId, String outTradeNo) {
  String nonce_str = System.currentTimeMillis() + "";

  SortedMap<String, String> packageParams = new TreeMap<String, String>();
  packageParams.put("appid", wxMpConfigStorage.getAppId());
  packageParams.put("mch_id", wxMpConfigStorage.getPartnerId());
  if (transactionId != null && !"".equals(transactionId.trim()))
    packageParams.put("transaction_id", transactionId);
  else if (outTradeNo != null && !"".equals(outTradeNo.trim()))
    packageParams.put("out_trade_no", outTradeNo);
  else
    throw new IllegalArgumentException("Either 'transactionId' or 'outTradeNo' must be given.");
  packageParams.put("nonce_str", nonce_str);
  packageParams.put("sign", WxCryptUtil.createSign(packageParams, wxMpConfigStorage.getPartnerKey()));

  StringBuilder request = new StringBuilder("<xml>");
  for (Entry<String, String> para : packageParams.entrySet()) {
    request.append(String.format("<%s>%s</%s>", para.getKey(), para.getValue(), para.getKey()));
  }
  request.append("</xml>");

  HttpPost httpPost = new HttpPost("https://api.mch.weixin.qq.com/pay/orderquery");
  if (httpProxy != null) {
    RequestConfig config = RequestConfig.custom().setProxy(httpProxy).build();
    httpPost.setConfig(config);
  }

  StringEntity entity = new StringEntity(request.toString(), Consts.UTF_8);
  httpPost.setEntity(entity);
  try {
    CloseableHttpResponse response = httpClient.execute(httpPost);
    String responseContent = Utf8ResponseHandler.INSTANCE.handleResponse(response);
    XStream xstream = XStreamInitializer.getInstance();
    xstream.alias("xml", WxMpPayResult.class);
    WxMpPayResult wxMpPayResult = (WxMpPayResult) xstream.fromXML(responseContent);
    return wxMpPayResult;
  } catch (IOException e) {
    throw new RuntimeException("Failed to query order due to IO exception.", e);
  }
}
 
Example 20
Source File: TestGenericRecordWriter.java    From datacollector with Apache License 2.0 4 votes vote down vote up
/**
 * Testing setParameters in JdbcGenericRecordWriter as well as setParamsToStatement()
 * and setPrimaryKeys() in JdbcBaseRecordWriter.
 * @throws StageException
 */
@Test
public void testSetParameters() throws StageException {
  List<JdbcFieldColumnParamMapping> columnMapping = ImmutableList.of(
      new JdbcFieldColumnParamMapping("/field1", "P_ID", "?"),
      new JdbcFieldColumnParamMapping("/field2", "MSG", "?")
  );

  boolean caseSensitive = false;
  JdbcGenericRecordWriter writer = new JdbcGenericRecordWriter(
      connectionString,
      dataSource,
      "TEST",
      "TEST_TABLE",
      false, //rollback
      columnMapping,
      JDBCOperationType.INSERT.getCode(),
      UnsupportedOperationAction.DISCARD,
      null,
      new JdbcRecordReader(),
      caseSensitive,
      Collections.emptyList(),
      true,
      context
  );
  Record record = RecordCreator.create();
  Map<String, Field> fields = new HashMap<>();
  fields.put("field1", Field.create(100));
  fields.put("field2", Field.create("StreamSets"));
  record.set(Field.create(fields));

  SortedMap<String, String> columnsToParameters = new TreeMap<>();
  columnsToParameters.put("P_ID", "?");
  columnsToParameters.put("MSG", "?");

  String query = "INSERT INTO TEST.TEST_TABLE (MSG, P_ID) VALUES (?, ?)";
  executeSetParameters(OperationType.INSERT_CODE, query, writer, columnsToParameters, record);

  query = "DELETE FROM TEST.TEST_TABLE  WHERE P_ID = ?";
  executeSetParameters(OperationType.DELETE_CODE, query, writer, columnsToParameters, record);

  query = "UPDATE TEST.TEST_TABLE SET  MSG = ? WHERE P_ID = ?";
  fields.put("field2", Field.create("This is an updated message"));
  columnsToParameters.remove("P_ID");
  executeSetParameters(OperationType.UPDATE_CODE, query, writer, columnsToParameters, record);
}