下面列出了java.util.HashMap#forEach ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Test
public void puttingDeferredVariablesOnParentScopesDoesNotBreakSetTag() {
String template = getFixtureTemplate("set-within-lower-scope-twice.jinja");
localContext.put("deferredValue", DeferredValue.instance("resolved"));
String output = interpreter.render(template);
assertThat(localContext).containsKey("varSetInside");
Object varSetInside = localContext.get("varSetInside");
assertThat(varSetInside).isInstanceOf(DeferredValue.class);
DeferredValue varSetInsideDeferred = (DeferredValue) varSetInside;
assertThat(varSetInsideDeferred.getOriginalValue()).isEqualTo("inside first scope");
HashMap<String, Object> deferredContext = DeferredValueUtils.getDeferredContextWithOriginalValues(
localContext
);
deferredContext.forEach(localContext::put);
String secondRender = interpreter.render(output);
assertThat(secondRender.trim())
.isEqualTo("inside first scopeinside first scope2".trim());
}
@Override
public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
log.info("======程序启动成功======");
coinTraderFactory.getTraderMap();
HashMap<String,CoinTrader> traders = coinTraderFactory.getTraderMap();
traders.forEach((symbol,trader) ->{
List<ExchangeOrder> orders = exchangeOrderService.findAllTradingOrderBySymbol(symbol);
List<ExchangeOrder> tradingOrders = new ArrayList<>();
orders.forEach(order -> {
BigDecimal tradedAmount = BigDecimal.ZERO;
BigDecimal turnover = BigDecimal.ZERO;
List<ExchangeOrderDetail> details = exchangeOrderDetailService.findAllByOrderId(order.getOrderId());
order.setDetail(details);
for(ExchangeOrderDetail trade:details){
tradedAmount = tradedAmount.add(trade.getAmount());
turnover = turnover.add(trade.getAmount().multiply(trade.getPrice()));
}
order.setTradedAmount(tradedAmount);
order.setTurnover(turnover);
if(!order.isCompleted()){
tradingOrders.add(order);
}
});
trader.trade(tradingOrders);
});
}
private @NonNull Optional<TerminalDataTreeCandidateNode> findNode(
Collection<HashMap<PathArgument, TerminalDataTreeCandidateNode>> nodes,
PathArgument id) {
if (nodes.isEmpty()) {
return Optional.empty();
}
Collection<HashMap<PathArgument, TerminalDataTreeCandidateNode>> nextNodes = new HashSet<>();
for (HashMap<PathArgument, TerminalDataTreeCandidateNode> map : nodes) {
if (map.containsKey(id)) {
return Optional.ofNullable(map.get(id));
}
map.forEach((childIdentifier, childNode) -> {
nextNodes.add(childNode.childNodes);
});
}
return findNode(nextNodes, id);
}
public void test_forEach() throws Exception {
HashMap<String, String> map = new HashMap<>();
map.put("one", "1");
map.put("two", "2");
map.put("three", "3");
HashMap<String, String> output = new HashMap<>();
map.forEach((k, v) -> output.put(k,v));
assertEquals(map, output);
HashSet<String> setOutput = new HashSet<>();
map.keySet().forEach((k) -> setOutput.add(k));
assertEquals(map.keySet(), setOutput);
setOutput.clear();
map.values().forEach((v) -> setOutput.add(v));
assertEquals(new HashSet<>(map.values()), setOutput);
HashSet<Map.Entry<String,String>> entrySetOutput = new HashSet<>();
map.entrySet().forEach((v) -> entrySetOutput.add(v));
assertEquals(map.entrySet(), entrySetOutput);
}
@Test
public void testIsGoodPassword() {
HashMap<String, Boolean> passwordExpectations =
new HashMap<String, Boolean>() {
{
// Bad ones.
put("Test 1234", false); // space is not a valid char
put("hello1234", false); // no uppercase
put("helloABCD", false); // no numeral
put("hello#$%&'", false); // no uppercase/numeral
put("sho!1", false); // too short, not 8 char
put("B1!\"#$%&'()*+,-./:;<=>[email protected][]^_`{|}~", false); // no lowercase
put("Test @1234", false); // contains space
// Good ones.
put("Test123!", true); // good
put("[email protected]", true); // more than 8 char
put("Abc1!\"#$%&'()*+,-./:;<=>[email protected][]^_`{|}~", true); // with all spl char, PASS
}
};
passwordExpectations.forEach(
(pwd, expectedResult) -> {
assertEquals(expectedResult, UserRequestValidator.isGoodPassword(pwd));
});
}
/**
* Analyzes all files of a commit in bulk.
*
* @param commitHash The commit hash.
* @param files The files of the commit.
* @param analyzers The analyzers to use.
* @param project The project the commit is in.
* @return A map of File and corresponding FileMetrics
*/
private HashMap<File, FileMetrics> analyzeBulk(
String commitHash,
List<File> files,
List<SourceCodeFileAnalyzerPlugin> analyzers,
Project project) {
HashMap<File, FileMetrics> fileMetricsMap = new LinkedHashMap<>();
try {
HashMap<File, byte[]> fileContents =
getRawCommitContentPort.getCommitContentBulkWithFiles(
coderadarConfigurationProperties.getWorkdir()
+ "/projects/"
+ project.getWorkdirName(),
files,
commitHash);
fileContents.forEach(
(key, value) ->
fileMetricsMap.put(
key, analyzeFileService.analyzeFile(analyzers, key.getPath(), value)));
} catch (UnableToGetCommitContentException e) {
e.printStackTrace();
}
return fileMetricsMap;
}
private void findViewById(File in) {
String res = readFile(in);
HashMap<String, String> map = split(res);
StringBuilder sb = new StringBuilder();
map.forEach((id, view) -> {
sb.append("public ").append(view).append(" ").append(formatId2Field(id)).append(";").append("\r\n");
});
sb.append("\n\n");
map.forEach((id, view) -> {
sb.append(formatId2Field(id))
.append("= itemView.findViewById(R.id.")
.append(id).append(");").append("\r\n");
if ("Button".equals(view)) {
sb.append(formatId2Field(id) + ".setOnClickListener(v -> {\n" +
" });\n");
}
});
System.out.println(sb.toString());
}
public static void main(String... args) {
// BiConsumer Example
BiConsumer<String, Integer> printKeyAndValue = (key, value) -> System.out.println(key + "-" + value);
printKeyAndValue.accept("One", 1);
printKeyAndValue.accept("Two", 2);
System.out.println("##################");
// Java Hash-Map foreach supports BiConsumer
HashMap<String, Integer> dummyValues = new HashMap<>();
dummyValues.put("One", 1);
dummyValues.put("Two", 2);
dummyValues.put("Three", 3);
dummyValues.forEach((key, value) -> System.out.println(key + "-" + value));
}
@SuppressWarnings("UnstableApiUsage")
public synchronized void shutdown() {
final HashMap<String, Process> localMap = new HashMap<>(processes);
localMap.forEach(this::killProcess);
outputProcessorExecutor.shutdown();
try {
if (!outputProcessorExecutor.awaitTermination(5, TimeUnit.SECONDS)) {
LOG.error("Output processor executor did not shutdown cleanly.");
}
} catch (final InterruptedException e) {
LOG.error("Interrupted while already shutting down", e);
Thread.currentThread().interrupt();
}
}
private static UriComponentsBuilder buildUrlParams(UriComponentsBuilder builder,
HashMap<String, String> queryParams) {
// for each key value pair in queryParams, it's calling the queryParam()
// method
// on the UriComponentsBuilder to add the param
queryParams.forEach(builder::queryParam);
return builder;
}
@SuppressWarnings("unchecked")
@Test
public void mustReplaceRootWithExpression() {
assertNotNull(testReplaceRootRepository);
List<Map<String, String>> resultsBeanList = testReplaceRootRepository.replaceRootWithExpr();
assertNotNull(resultsBeanList);
assertEquals(resultsBeanList.size(), 3);
HashMap<String, Integer> expectedResultMap = new HashMap() {
{
put("Gary Sheffield", 0);
}
{
put("Nancy Walker", 0);
}
{
put("Peter Sumner", 0);
}
};
resultsBeanList.forEach((resultMap) -> {
String fullName = resultMap.get("fullName");
Integer count = expectedResultMap.get(fullName);
expectedResultMap.put(fullName, ++count);
});
expectedResultMap.forEach((k, v) -> assertTrue(v == 1));
}
@Test
public void maskPhone() {
HashMap<String, String> phoneMaskExpectations =
new HashMap<String, String>() {
{
put("0123456789", "012345678*");
put("123-456-789", "123-456-7**");
put("123", "123");
}
};
phoneMaskExpectations.forEach(
(phone, expectedResult) -> {
assertEquals(expectedResult, logMaskService.maskPhone(phone));
});
}
private void checkStates(HashMap<String, String> testData, JsonArray servStates) {
testData.forEach((service, expectedState) -> {
System.out.println("Service: " + service);
System.out.println("Expected State: " + expectedState);
assertEquals("The state of " + service + " service is not matching.", expectedState,
HealthTestUtil.getActualState(service, servStates));
});
}
@Override
public void action(String[] args, MessageReceivedEvent event) throws ParseException, IOException {
allval = 0;
DecimalFormat df = new DecimalFormat("###.##");
URL url = new URL(LIST_URL);
Scanner s = new Scanner(url.openStream());
HashMap<String, Float> donators = new HashMap<>();
while (s.hasNextLine()) {
String[] l = s.nextLine().replace("\n", "").split(",");
donators.put(l[0], Float.parseFloat(l[1]));
}
StringBuilder sb = new StringBuilder();
donators.forEach((n, v) -> {
sb.append(String.format(":white_small_square: **%s** - %s €\n", n, df.format(v)));
addAllval(v);
});
EmbedBuilder eb = new EmbedBuilder()
.setColor(new Color(0xFFD200))
.setDescription(
"This bot is currently running on an virtual server, witch I (zekro) rent for around 20 € every year.\n" +
"Sure, this bot is fully free to use without any costs, but I would really appreciate if you could help me" +
"to finance this costs of the server by donations. :hearts:\n\n" +
"If you want to donate, you can do it **[here](https://www.paypal.me/zekro)** *(with PayPal)*.\n\n\n" +
"**List of donator's** *(for current year cycle)*\n\n" + sb.toString() + "\n\n" +
String.format(":trophy: Goal: **%s € / %s €**", df.format(allval), df.format(NEED_VAL))
);
event.getTextChannel().sendMessage(eb.build()).queue();
}
@Test
public void testExtractKeys() throws IOException, CertificateException, NoSuchAlgorithmException, KeyStoreException, UnrecoverableKeyException {
KeyStore keyStore = setupKeystore();
HashMap<String, Key> keys = TlsHelper.extractKeys(keyStore, password.toCharArray());
assertEquals(1, keys.size());
keys.forEach((String alias, Key key) -> assertEquals("PKCS#8", key.getFormat()));
}
@SuppressWarnings("unchecked")
@Test
public void mustReplaceRootWithExpression() {
assertNotNull(testReplaceRootRepository);
List<Map<String, String>> resultsBeanList = testReplaceRootRepository.replaceRootWithExpr();
assertNotNull(resultsBeanList);
assertEquals(resultsBeanList.size(), 3);
HashMap<String, Integer> expectedResultMap = new HashMap() {
{
put("Gary Sheffield", 0);
}
{
put("Nancy Walker", 0);
}
{
put("Peter Sumner", 0);
}
};
resultsBeanList.forEach((resultMap) -> {
String fullName = resultMap.get("full_name");
Integer count = expectedResultMap.get(fullName);
expectedResultMap.put(fullName, ++count);
});
expectedResultMap.forEach((k, v) -> assertTrue(v == 1));
}
public static Message error(TextChannel chan, String content, String title, HashMap<String, String> fields) {
EmbedBuilder embed = new EmbedBuilder().setColor(Color.red).setDescription(content).setTitle(title, null);
fields.forEach((t, c) -> embed.addField(t, c, false));
return chan.sendMessage(embed.build()).complete();
}
private MainPanel() {
super(new BorderLayout());
// Insets
// UIManager.put("TabbedPane.tabInsets", new Insets(8, 8, 8, 8));
// UIManager.put("TabbedPane.tabAreaInsets", new Insets(8, 8, 8, 8));
// UIManager.put("TabbedPane.contentBorderInsets", new Insets(8, 8, 8, 8));
// UIManager.put("TabbedPane.selectedTabPadInsets", new Insets(8, 8, 8, 8));
// Color
// UIManager.put("TabbedPane.shadow", Color.GRAY);
// UIManager.put("TabbedPane.darkShadow", Color.GRAY);
// UIManager.put("TabbedPane.light", Color.GRAY);
// UIManager.put("TabbedPane.highlight", Color.GRAY);
// UIManager.put("TabbedPane.tabAreaBackground", Color.GRAY);
// UIManager.put("TabbedPane.unselectedBackground", Color.GRAY);
// UIManager.put("TabbedPane.background", Color.GRAY);
// UIManager.put("TabbedPane.foreground", Color.WHITE);
// UIManager.put("TabbedPane.focus", Color.WHITE);
// UIManager.put("TabbedPane.contentAreaColor", Color.WHITE);
// UIManager.put("TabbedPane.selected", Color.WHITE);
// UIManager.put("TabbedPane.selectHighlight", Color.WHITE);
// UIManager.put("TabbedPane.borderHightlightColor", Color.WHITE);
// Opaque
// UIManager.put("TabbedPane.tabsOpaque", Boolean.FALSE);
// UIManager.put("TabbedPane.contentOpaque", Boolean.FALSE);
// ???
// UIManager.put("TabbedPane.tabRunOverlay", Boolean.FALSE);
// UIManager.put("TabbedPane.tabsOverlapBorder", Boolean.FALSE);
// // UIManager.put("TabbedPane.selectionFollowsFocus", Boolean.FALSE);
HashMap<String, Color> map = new HashMap<>();
map.put("TabbedPane.darkShadow", Color.GRAY);
map.put("TabbedPane.light", Color.GRAY);
map.put("TabbedPane.tabAreaBackground", Color.GRAY);
map.put("TabbedPane.unselectedBackground", Color.GRAY);
map.put("TabbedPane.shadow", Color.GRAY);
map.put("TabbedPane.highlight", Color.GRAY);
// map.put("TabbedPane.background", Color.RED);
// map.put("TabbedPane.foreground", Color.BLUE);
map.put("TabbedPane.focus", Color.WHITE);
map.put("TabbedPane.contentAreaColor", Color.WHITE);
map.put("TabbedPane.selected", Color.WHITE);
map.put("TabbedPane.selectHighlight", Color.WHITE);
// map.put("TabbedPane.borderHighlightColor", Color.WHITE); // Do not work
// Maybe "TabbedPane.borderHightlightColor" is a typo,
// but this is defined in MetalTabbedPaneUI
map.put("TabbedPane.borderHightlightColor", Color.WHITE);
// for (Map.Entry<String, Color> entry: map.entrySet()) {
// UIManager.put(entry.getKey(), entry.getValue());
// }
map.forEach(UIManager::put);
GridBagConstraints c = new GridBagConstraints();
c.anchor = GridBagConstraints.LINE_START;
c.gridx = GridBagConstraints.REMAINDER;
JComboBox<String> combo = makeComboBox(map);
JCheckBox opaque = new JCheckBox("JTabbedPane#setOpaque", true);
JPanel p = new JPanel(new GridBagLayout());
p.add(opaque, c);
p.add(combo, c);
JTabbedPane tabs = makeTabbedPane();
opaque.addActionListener(e -> {
tabs.setOpaque(((JCheckBox) e.getSource()).isSelected());
tabs.repaint();
});
combo.addItemListener(e -> {
if (e.getStateChange() == ItemEvent.SELECTED) {
map.forEach(UIManager::put);
UIManager.put(e.getItem(), Color.GREEN);
// XXX: JComboBox: by UP/DOWN keys
// XXX: NullPointerException at BasicComboBoxUI.selectNextPossibleValue(BasicComboBoxUI.java:1128)
// SwingUtilities.updateComponentTreeUI(tabs);
tabs.updateUI();
}
});
tabs.addTab("JTree", new JScrollPane(new JTree()));
tabs.addTab("JTextArea", new JScrollPane(new JTextArea()));
tabs.addTab("JButton", new JButton("button"));
tabs.addTab("JPanel", p);
tabs.setMnemonicAt(0, KeyEvent.VK_T);
tabs.setMnemonicAt(1, KeyEvent.VK_A);
tabs.setMnemonicAt(2, KeyEvent.VK_B);
tabs.setMnemonicAt(3, KeyEvent.VK_P);
add(tabs);
setPreferredSize(new Dimension(320, 240));
}
/**
* Returns the SignedInfo element of the V2GMessage header, based on the provided HashMap which holds
* the reference IDs (URIs) and the corresponding SHA-256 digests.
*
* @param xmlSignatureRefElements A HashMap of Strings (reflecting the reference IDs) and digest values
* @return The SignedInfoType instance
*/
public static SignedInfoType getSignedInfo(HashMap<String, byte[]> xmlSignatureRefElements) {
/*
* According to requirement [V2G2-771] in ISO/IEC 15118-2 the following message elements of the
* XML signature framework shall not be used:
* - Id (attribute in SignedInfo)
* - ##any in SignedInfo – CanonicalizationMethod
* - HMACOutputLength in SignedInfo – SignatureMethod
* - ##other in SignedInfo – SignatureMethod
* - Type (attribute in SignedInfo-Reference)
* - ##other in SignedInfo – Reference – Transforms – Transform
* - XPath in SignedInfo – Reference – Transforms – Transform
* - ##other in SignedInfo – Reference – DigestMethod
* - Id (attribute in SignatureValue)
* - Object (in Signature)
* - KeyInfo
*/
DigestMethodType digestMethod = new DigestMethodType();
digestMethod.setAlgorithm("http://www.w3.org/2001/04/xmlenc#sha256");
TransformType transform = new TransformType();
transform.setAlgorithm("http://www.w3.org/TR/canonical-exi/");
TransformsType transforms = new TransformsType();
transforms.getTransform().add(transform);
List<ReferenceType> references = new ArrayList<ReferenceType>();
xmlSignatureRefElements.forEach( (k,v) -> {
ReferenceType reference = new ReferenceType();
reference.setDigestMethod(digestMethod);
reference.setDigestValue(v);
reference.setTransforms(transforms);
reference.setURI("#" + k);
references.add(reference);
});
CanonicalizationMethodType canonicalizationMethod = new CanonicalizationMethodType();
canonicalizationMethod.setAlgorithm("http://www.w3.org/TR/canonical-exi/");
SignatureMethodType signatureMethod = new SignatureMethodType();
signatureMethod.setAlgorithm("http://www.w3.org/2001/04/xmldsig-more#ecdsa-sha256");
SignedInfoType signedInfo = new SignedInfoType();
signedInfo.setCanonicalizationMethod(canonicalizationMethod);
signedInfo.setSignatureMethod(signatureMethod);
signedInfo.getReference().addAll(references);
return signedInfo;
}
protected void doUploadTest(String requestURI, Module module, DoTest doTest) throws Exception {
BasicFuture<Object> basicFuture = new BasicFuture<>();
//
// .随机数据
byte[] bytes = new byte[1024 * 1024];
new Random(System.currentTimeMillis()).nextBytes(bytes);
HashMap<String, Object> oriData = new HashMap<String, Object>() {{
put("bytes", bytes);
put("fileName", "test_file");
}};
//
// .Http Server
HttpServer server = HttpServer.create(new InetSocketAddress(8001), 0);
server.createContext(requestURI, httpExchange -> {
Headers requestHeaders = httpExchange.getRequestHeaders();
Map<String, String[]> headerMap = new HashMap<>();
requestHeaders.forEach((key, strings) -> headerMap.put(key, strings.toArray(new String[0])));
InputStream inputStream = httpExchange.getRequestBody();
//
HttpServletRequest mockRequest = mockRequest("post", new URL("http://www.hasor.net" + requestURI), headerMap, null, null);
PowerMockito.when(mockRequest.getInputStream()).thenReturn(new InnerInputStream(inputStream));
PowerMockito.when(mockRequest.getContentType()).thenReturn(httpExchange.getRequestHeaders().getFirst("Content-type"));
//
AppContext appContext = buildWebAppContext("/META-INF/hasor-framework/web-hconfig.xml", apiBinder -> {
apiBinder.installModule(module);
}, servlet25("/"), LoadModule.Web);
//
//
try {
Object o = callInvoker(appContext, mockRequest);
if (o != null) {
doTest.doTest(oriData, o);
} else {
throw new IllegalStateException("not call test.");
}
//
httpExchange.sendResponseHeaders(200, 0);
basicFuture.completed(o);
} catch (Throwable throwable) {
basicFuture.failed(throwable);
httpExchange.sendResponseHeaders(500, 0);
}
httpExchange.getResponseBody().close();
});
server.start();
//
// .发起文件上传
MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create();
oriData.forEach((key, val) -> {
if (val instanceof byte[]) {
entityBuilder.addBinaryBody(key, (byte[]) val);
} else if (val instanceof File) {
entityBuilder.addPart(key, new FileBody((File) val));
} else {
entityBuilder.addTextBody(key, val.toString());
}
});
//
try (CloseableHttpClient client = HttpClientBuilder.create().build()) {
HttpPost httpRequest = new HttpPost("http://localhost:8001" + requestURI);
httpRequest.setEntity(entityBuilder.build());
client.execute(httpRequest);
basicFuture.get();
} finally {
server.stop(1);
}
}