Java Code Examples for java.util.Map.forEach()

The following are Jave code examples for showing how to use forEach() of the java.util.Map class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: spring-depend   File: SpringDependencyAnalyzer.java   View Source Code Vote up 6 votes
public void printReport(Class<?> springConfigurationClass) {
    System.err.println("Configuration layers:\n");
    getConfigurationLayers(springConfigurationClass).forEach((layer,classes) -> {
        System.err.println("" + layer + "\t" + StringUtils.join(classes,','));
    });

    System.err.println("\n\nDependencies:\n");
    Map<String, Set<String>> beanDependencies = getBeanDependencies();
    beanDependencies.forEach((name,dependencies) -> {
        System.err.println(name + ": " + StringUtils.join(dependencies,','));
    });
    System.err.println("\n\nReverse dependencies:\n");
    Map<String, Set<String>> reverseBeanDependencies = getReverseBeanDependencies();
    reverseBeanDependencies.forEach((name,dependencies) -> {
        System.err.println(name + ": " + StringUtils.join(dependencies,','));
    });

    System.err.println("\n\nBean dependency graph:\n");
    System.err.println(getBeanGraph());
    System.err.println("Bean layers:\n");

    getBeanGraph().getLayers().forEach((layer,classes) -> {
        System.err.println("" + layer + "\t" + StringUtils.join(classes,','));
    });
}
 
Example 2
Project: SqlSauce   File: DatabaseWrapper.java   View Source Code Vote up 6 votes
/**
 * @return the number of entities updated or deleted
 */
public int executeJpqlQuery(@Nonnull final String queryString, @Nullable final Map<String, Object> parameters)
        throws DatabaseException {
    final EntityManager em = this.databaseConnection.getEntityManager();
    try {
        final Query query = em.createQuery(queryString);
        if (parameters != null) {
            parameters.forEach(query::setParameter);
        }
        em.getTransaction().begin();
        final int updatedOrDeleted = query.executeUpdate();
        em.getTransaction().commit();
        return updatedOrDeleted;
    } catch (final PersistenceException e) {
        final String message = String.format("Failed to execute JPQL query %s with %s parameters on DB %s",
                queryString, parameters != null ? parameters.size() : "null", this.databaseConnection.getName());
        throw new DatabaseException(message, e);
    } finally {
        em.close();
    }
}
 
Example 3
Project: neo4j-versioner-sql   File: TestData.java   View Source Code Vote up 6 votes
public static void assertForeignKeys(GraphDatabaseService neo4j, Neo4jVersionerCore neo4jVersionerCore, Map<Tuple2<String, String>, Map<String, String>> relationships) {

		ResourceIterator<Optional<Node>> tablesStateList = neo4j.findNodes(Label.label("Table")).map(table -> neo4jVersionerCore.findStateNode(table.getId()));

		List<Relationship> foreignKeysList = tablesStateList.stream()
				.map(tableStateOpt -> tableStateOpt.get().getRelationships(Direction.OUTGOING, RelationshipType.withName("RELATION")))
				.flatMap(list -> StreamSupport.stream(list.spliterator(), false))
				.collect(toList());

		assertThat(foreignKeysList)
				.hasSize(relationships.size());

		relationships.forEach((keys, description) -> assertThat(foreignKeysList).anySatisfy(foreignKey -> {
			assertThat(foreignKey.getStartNode().hasProperty(keys.a)).isTrue();
			assertThat(foreignKey.getEndNode().hasProperty(keys.b)).isTrue();
			assertThat(foreignKey.getAllProperties()).containsAllEntriesOf(description);
		}));
	}
 
Example 4
Project: take   File: LoginTest.java   View Source Code Vote up 6 votes
/**
 * Set-Cookie:xqat=93b9123bccf67168e3adb0c07d89b9e1f6cc8db6; domain=.xueqiu.com; path=/; expires=Mon, 23 May 2016 13:36:54 GMT; httpOnly
 Set-Cookie:xq_r_token=8cfa9fd958be66a0a6692ab80219e8eaecef6718; domain=.xueqiu.com; path=/; expires=Mon, 23 May 2016 13:36:54 GMT; httpOnly
 Set-Cookie:xq_is_login=1; domain=xueqiu.com; path=/; expires=Mon, 23 May 2016 13:36:54 GMT
 Set-Cookie:u=2970459786; domain=.xueqiu.com; path=/; expires=Mon, 23 May 2016 13:36:54 GMT; httpOnly
 Set-Cookie:xq_token_expire=Mon%20May%2023%202016%2021%3A36%3A54%20GMT%2B0800%20(CST); domain=.xueqiu.com; path=/; expires=Mon, 23 May 2016 13:36:54 GMT; httpOnly
 Set-Cookie:xq_a_token=93b9123bccf67168e3adb0c07d89b9e1f6cc8db6; domain=.xueqiu.com; path=/; expires=Mon, 23 May 2016 13:36:54 GMT; httpOnlyvv

 * @throws Exception
 */
@Test
public void test01() throws Exception {

    String base = "https://xueqiu.com/user/login";
    String param = "areacode=86&username=jt120lz%40gmail.com&password=3E0409E11A5756B971C54CC38035C198&remember_me=on";
    URL url = new URL(base+"?"+param);
    URLConnection conn = url.openConnection();
    conn.connect();
    BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
    String s = null;
    while ((s = br.readLine()) != null) {
        System.out.println(s);
    }
    br.close();
    Map<String, List<String>> headers = conn.getHeaderFields();
    headers.forEach((key,value)-> {
        if (key.startsWith("Set-Cookie")) {
            value.forEach(v->System.out.println(v));
        }
    });
}
 
Example 5
Project: SqlSauce   File: DatabaseWrapper.java   View Source Code Vote up 6 votes
/**
 * Use this for COUNT() and similar jpql queries which are guaranteed to return a result
 */
@Nonnull
@CheckReturnValue
public <T> T selectJpqlQuerySingleResult(@Nonnull final String queryString,
                                         @Nullable final Map<String, Object> parameters,
                                         @Nonnull final Class<T> resultClass) throws DatabaseException {
    final EntityManager em = this.databaseConnection.getEntityManager();
    try {
        final Query q = em.createQuery(queryString);
        if (parameters != null) {
            parameters.forEach(q::setParameter);
        }
        em.getTransaction().begin();
        final T result = resultClass.cast(q.getSingleResult());
        em.getTransaction().commit();
        return setSauce(result);
    } catch (final PersistenceException | ClassCastException e) {
        final String message = String.format("Failed to select single result JPQL query %s with %s parameters for class %s on DB %s",
                queryString, parameters != null ? parameters.size() : "null", resultClass.getName(), this.databaseConnection.getName());
        throw new DatabaseException(message, e);
    } finally {
        em.close();
    }
}
 
Example 6
Project: n4js   File: N4IDEXpectFileSetup.java   View Source Code Vote up 5 votes
/**
 * Finds {@link IFile} and containing {@link IProject} for xpect file that is currently processed.
 *
 * Looks through all available projects and finds all files that match (by {@link URI}) to currently processed xpect
 * file. If only one file in only one project is found, returns that mapping, throws error in other cases
 *
 * @return {@link java.util.Map.Entry} map entry of file and containing project for a given
 *         {@link org.eclipse.xpect.XpectFile}
 */
private Entry<IFile, IProject> findTestResources() throws RuntimeException {
	Map<IFile, IProject> files2projects = new HashMap<>();

	IProject[] worksapceProjects = ResourcesPlugin.getWorkspace().getRoot().getProjects();

	String xtFileLocation = ctx.getXpectFileURI().toString();// file://C:/Users/Administrator/runtime-New_configuration/yyyyyyyyyyyyyyyyyy/src/TestFile_001.n4js.xt

	for (IProject iProject : worksapceProjects) {
		String projLoc = iProject.getLocationURI().toString();
		if (xtFileLocation.startsWith(projLoc)) {
			String lkp = xtFileLocation.substring(projLoc.length());// file:/C:/Users/Administrator/runtime-New_configuration/yyyyyyyyyyyyyyyyyy
			IFile lkpFile = (IFile) iProject.findMember(lkp);
			if (lkpFile != null) {
				files2projects.put(lkpFile, iProject);
			}
		}
	}

	RuntimeException re = null;
	switch (files2projects.size()) {
	case 0:
		re = new RuntimeException("cannot find any file and project for processed xpect file");
		N4IDEXpectUIPlugin.logError("no projects with files mathching " + xtFileLocation + " found", re);
		throw re;
	case 1:
		return files2projects.entrySet().iterator().next();

	default:
		re = new RuntimeException("cannot find single file and project for processed xpect file");
		StringBuilder sb = new StringBuilder("multiple projects matching " + xtFileLocation + " found");
		files2projects.forEach((file, project) -> {
			sb.append("\n file : " + file.getRawLocation().toString() + ", project :: "
					+ project.getRawLocation().toString());
		});
		N4IDEXpectUIPlugin.logError(sb.toString(), re);
		throw re;
	}
}
 
Example 7
Project: RecursiveSwaggerSchemaParser   File: SwaggerSchemaResponseParser.java   View Source Code Vote up 5 votes
public HashMap<String, SwaggerResponseSchema> parseResponseForAllPaths() {
    Map<String, Path> paths = swagger.getPaths();
    HashMap<String, SwaggerResponseSchema> responses = new HashMap<>();
    paths.forEach((path, methods) -> {
        Map<HttpMethod, Operation> operationMap = methods.getOperationMap();
        operationMap.forEach(((httpMethod, operation) -> {
            SwaggerResponseSchema response = parseReponseForGivenPathHTTPMethodAndAllResponseType(path, httpMethod);
            responses.put(httpMethod.name() + path, response);
        }));
    });
    return responses;
}
 
Example 8
Project: GoPush   File: NodeServerDiscoveryService.java   View Source Code Vote up 5 votes
/**
 * 初始化node-server列表
 */
private void initNodeServerDiscovery() {
    nodeServerPool.clear();
    Map<String, String> datas = zkUtils.readTargetChildsData(ZkGroupEnum.NODE_SERVER.getValue());
    if (datas != null) {
        datas.forEach((k, v) -> nodeServerPool.put(k, JSON.parseObject(v, NodeServerInfo.class)));
    }
    nodeServerPool().forEach((k, v) -> nodeManager.put(k, v.getIntranetIp(), v.getNodePort(), v.getInternetIp(), v.getDevicePort()));

}
 
Example 9
Project: hekate   File: FailoverAggregateTest.java   View Source Code Vote up 5 votes
@Test
public void testDelay() throws Exception {
    int failoverDelay = 200;

    failures.set(channels.size() * 3);

    Map<ClusterNodeId, List<Long>> times = new HashMap<>();

    channels.forEach(c -> times.put(c.getNodeId(), Collections.synchronizedList(new ArrayList<>())));

    AggregateResult<String> result = get(sender.get().withFailover(ctx -> {
        times.get(ctx.failedNode().id()).add(currentTimeMillis());

        return ctx.retry().withDelay(failoverDelay);
    }).aggregate("test"));

    times.forEach((id, series) -> {
        assertEquals(3, series.size());

        long prevTime = 0;

        for (Long time : series) {
            if (prevTime == 0) {
                prevTime = time;
            } else {
                assertTrue(time - prevTime >= failoverDelay);

                prevTime = time;
            }
        }
    });

    assertTrue(result.isSuccess());
    assertEquals(channels.size(), result.results().size());
}
 
Example 10
Project: jeeves   File: WechatHttpServiceInternal.java   View Source Code Vote up 5 votes
private void appendAdditionalCookies(CookieStore store, Map<String, String> cookies, String domain, String path, Date expiryDate) {
    cookies.forEach((key, value) -> {
        BasicClientCookie cookie = new BasicClientCookie(key, value);
        cookie.setDomain(domain);
        cookie.setPath(path);
        cookie.setExpiryDate(expiryDate);
        store.addCookie(cookie);
    });
}
 
Example 11
Project: CentauriCloud   File: CentauriCloudCommandListener.java   View Source Code Vote up 5 votes
private void handleProfileCommand() {
	if (!Cloud.getInstance().getProfiler().isEnabled()) {
		Cloud.getLogger().info("Profiler is not enabled!");
		return;
	}
	Map<String, List<CentauriProfiler.Profile>> keyToProfiles = new HashMap<>();

	Cloud.getInstance().getProfiler().getProfiles().forEach(profile -> {
		if (!keyToProfiles.containsKey(profile.getKey()))
			keyToProfiles.put(profile.getKey(), new ArrayList<>());
		keyToProfiles.get(profile.getKey()).add(profile);
	});

	keyToProfiles.forEach((key, profiles) -> {
		final ProfilerStatistic statistic = new ProfilerStatistic();

		profiles.forEach(profile -> {
			if (profile.getTime() < statistic.getMin())
				statistic.setMin(profile.getTime());

			if (profile.getTime() > statistic.getMax())
				statistic.setMax(profile.getTime());

			statistic.setAvg(statistic.getAvg() + profile.getTime());
		});

		statistic.setAvg(statistic.getAvg() / profiles.size());

		Cloud.getLogger().info("Key: {}, Min: {}ms, Max: {}ms, Avg: {}ms", key, statistic.getMin(), statistic.getMax(), statistic.getAvg());
	});
}
 
Example 12
Project: ensembl-elastic-rest-final   File: Application.java   View Source Code Vote up 5 votes
private void printElasticSearchInfo() {

        System.out.println("--ElasticSearch-->");
        Client client = es.getClient();
        Map<String, String> asMap = client.settings().getAsMap();

        asMap.forEach((k, v) -> {
            System.out.println(k + " = " + v);
        });
        System.out.println("<--ElasticSearch--");
    }
 
Example 13
Project: properlty   File: ToLowerCaseAndDotKeyReader.java   View Source Code Vote up 5 votes
@Override
protected Map<String, PropertyValue> apply(Map<String, PropertyValue> input) {
	final Map<String, PropertyValue> output = new HashMap<>();
	input.forEach((key, value) -> {
		output.put(key.toLowerCase().replace("_", "."), value);
	});
	return output;
}
 
Example 14
Project: Shuriken   File: Utils.java   View Source Code Vote up 5 votes
public static Path generateTestJar(Pair<String, byte[]>... files) {
    Path jarFile;
    try {
        jarFile = Files.createTempFile("testjar", ".jar");
        try(ZipOutputStream zos = new ZipOutputStream(Files.newOutputStream(jarFile))) {
            Map<String, List<Pair<String, byte[]>>> filesMap = new HashMap<>();
            for (Pair<String, byte[]> file : files) {
                filesMap.compute(file.getKey(), (k, data) -> {
                    List<Pair<String, byte[]>> fileData = data != null ? data : new ArrayList<>();
                    fileData.add(new Pair<>(file.getKey(), compress(file.getValue())));
                    return fileData;
                });
            }

            filesMap.forEach((path, data) -> {
                putPath(Paths.get(path).getParent().toString(), zos);
                data.forEach(file -> putFile(file.getKey(), file.getValue(), zos));
            });

            zos.closeEntry();
            zos.finish();
        }
    } catch (Throwable e) {
        SneakyThrow.throwException(e);
        return null;
    }
    //jarFile.toFile().deleteOnExit();
    return jarFile;
}
 
Example 15
Project: kmanager   File: ElasticsearchRESTUtil.java   View Source Code Vote up 4 votes
public static Map<String, List<OffsetStat>> offset(String group, String topic, String start, String end) {
  Map<String, List<OffsetStat>> statsMap = new HashMap<String, List<OffsetStat>>();
  String indexPrefix = SystemManager.getConfig().getEsIndex();
  try {
    ElasticsearchAssistEntity assistEntity = ScrollSearchTemplate.getInterval(start, end);

    List<String> indexes = new ArrayList<String>();
    assistEntity.getIndexs().forEach(a -> {
      indexes.add(indexPrefix + "-" + a);
    });

    String[] esHost = SystemManager.getConfig().getEsHosts().split("[,;]")[0].split(":");

    String url = "http://" + esHost[0] + ":" + esHost[1] + "/" + String.join(",", indexes) + "/"
        + SystemManager.getElasticSearchOffsetType() + "/_search?ignore_unavailable=true&allow_no_indices=true";

    ResponseEntity<String> response = REST.exchange(url, HttpMethod.POST,
        new HttpEntity<String>(ScrollSearchTemplate.getOffset(group, topic, assistEntity), headers), String.class);
    String searchResult = response.getBody();
    JSONObject temp = new JSONObject(searchResult);
    JSONArray temp2 = temp.getJSONObject("aggregations").getJSONObject("aggs").getJSONArray("buckets");
    List<OffsetStat> stats = new ArrayList<OffsetStat>();
    temp2.forEach(obj -> {
      JSONObject item = (JSONObject) obj;
      JSONArray xx = item.getJSONObject("group").getJSONArray("buckets");
      for (int i = 0; i < xx.length(); i++) {
        JSONObject item2 = xx.getJSONObject(i);
        JSONArray xxx = item2.getJSONObject("topic").getJSONArray("buckets");
        for (int j = 0; j < xxx.length(); j++) {
          JSONObject item3 = xxx.getJSONObject(j);
          stats.add(new OffsetStat(item.getLong("key"), item2.get("key").toString(), item3.get("key").toString(),
              item3.getJSONObject("offset").getLong("value"), item3.getJSONObject("lag").getLong("value")));
        }
      }
    });

    stats.forEach(a -> {
      String topicName = a.getTopic();
      if (topicName == null || topicName.length() == 0) {
        topicName = "empty";
      }
      if (statsMap.containsKey(topicName)) {
        statsMap.get(topicName).add(a);
      } else {
        List<OffsetStat> arr = new ArrayList<OffsetStat>();
        arr.add(a);
        statsMap.put(topicName, arr);
      }
    });

    statsMap.forEach((key, val) -> {
      for (int i = val.size() - 1; i > 0; i--) {
        val.get(i).setOffset(val.get(i).getOffset() - val.get(i - 1).getOffset());
      }
      val.remove(0);
    });

  } catch (Exception e) {
    // TODO
    LOG.error("Damn...", e);
  }
  return statsMap;
}
 
Example 16
Project: oreilly-reactive-architecture-old   File: CoffeeHouseApp.java   View Source Code Vote up 4 votes
public static void applySystemProperties(final Map<String, String> opts) {
    opts.forEach((key, value) -> {
        if (key.startsWith("-D")) System.setProperty(key.substring(2), value);
    });
}
 
Example 17
Project: oreilly-reactive-architecture-student   File: CoffeeHouseApp.java   View Source Code Vote up 4 votes
public static void applySystemProperties(final Map<String, String> opts) {
    opts.forEach((key, value) -> {
        if (key.startsWith("-D")) System.setProperty(key.substring(2), value);
    });
}
 
Example 18
Project: uncommons   File: ExpiringMap.java   View Source Code Vote up 4 votes
/**
 * This method will put all entries from {@code map} into this map with {@code defaultTimeToLive}.
 */
@Override
public void putAll(final Map<? extends K, ? extends V> map) {
  map.forEach((k, v) -> this.put(k, v, defaultTimeToLive));
}
 
Example 19
Project: hygene   File: PathCalculator.java   View Source Code Vote up 2 votes
/**
 * Adds a set of computed path to its corresponding {@link Edge}.
 *
 * @param paths the paths
 */
private void addPathsToEdges(final Map<Edge, Set<String>> paths) {
    paths.forEach(Edge::setGenomes);
}
 
Example 20
Project: guava-mock   File: AtomicLongMap.java   View Source Code Vote up 2 votes
/**
 * Copies all of the mappings from the specified map to this map. The effect of this call is
 * equivalent to that of calling {@code put(k, v)} on this map once for each mapping from key
 * {@code k} to value {@code v} in the specified map. The behavior of this operation is undefined
 * if the specified map is modified while the operation is in progress.
 */
public void putAll(Map<? extends K, ? extends Long> m) {
  m.forEach(this::put);
}