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

The following are Jave code examples for showing how to use forEach() of the java.util.HashMap 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: amelia   File: XMLController.java   View Source Code Vote up 6 votes
public void writeXMLFile(HashMap<String,String> lines,String path) throws IOException, XMLStreamException{
    XMLOutputFactory xof =  XMLOutputFactory.newInstance();
    final XMLStreamWriter xtw = xof.createXMLStreamWriter(new FileWriter(path));
    xtw.writeStartDocument("utf-8","1.0");
    xtw.writeCharacters("\n");
    
    lines.forEach((key,value) ->{
        try {
            xtw.writeStartElement(key);
            xtw.writeCharacters(value);
            xtw.writeEndElement();
            xtw.writeCharacters("\n");
        } catch (XMLStreamException ex) {
            Logger.getLogger(XMLController.class.getName()).log(Level.SEVERE, null, ex);
        }
    });
    xtw.writeEndDocument();
    xtw.flush();
    xtw.close();
}
 
Example 2
Project: Supreme-Bot   File: Util.java   View Source Code Vote up 6 votes
public static final String cookiesToString(HashMap<String, String> cookies) {
    if (cookies == null) {
        return null;
    }
    if (cookies.isEmpty()) {
        return "";
    }
    try {
        final StringBuilder out = new StringBuilder();
        cookies.forEach((name, value) -> {
            out.append(name);
            out.append("=");
            out.append(value);
            out.append(";");
        });
        return out.substring(0, out.length() - ";".length());
    } catch (Exception ex) {
        ex.printStackTrace();
        return null;
    }
}
 
Example 3
Project: anki-cards-web-browser   File: Exporter.java   View Source Code Vote up 6 votes
private void moveAndRenameImageFiles() throws AnkiExpectedExportingException {
    HashMap<String, String> imageNamesDictionary = parser.getImageNamesDictionary();

    File imagesFolder = new File(destinationFolder, "anki-images");
    //noinspection ResultOfMethodCallIgnored
    imagesFolder.mkdirs();

    imageNamesDictionary.forEach((currentName, targetName) -> {
        File originalFile    = new File(parser.getUnzippedToFolder(), currentName);
        File destinationFile = new File(imagesFolder, targetName);

        try {
            Files.copy(originalFile, destinationFile);
        } catch (IOException e) {
            throw new AnkiExpectedExportingException("Cannot move "+originalFile+" to "+destinationFile);
        }
    });
}
 
Example 4
Project: ProjectAres   File: GunGizmo.java   View Source Code Vote up 6 votes
@Override
public void run() {
    try {
        final HashMap<UUID, Integer> counts = Maps.newHashMap();
        gifts.forEach(playerId -> counts.merge(playerId, 1, Integer::sum));

        counts.forEach((playerId, count) -> onlinePlayers.byUuid(playerId).ifPresent(player -> {
            RaindropUtil.giveRaindrops(
                userStore.playerId(player),
                count,
                null,
                new TranslatableComponent("gizmo.gun.raindropsResult"),
                false
            );
        }));
    } finally {
        gifts.clear();
    }
}
 
Example 5
Project: Nukkit-WorldProtect   File: WorldProtect.java   View Source Code Vote up 6 votes
public void onEnable(){
    plugin = this;
    this.getLogger().notice("WorldProtect is enable");
    this.getServer().getPluginManager().registerEvents(new EventListener(),this);
    this.config = new Config(this.getDataFolder()+"/worlds.yml",Config.YAML);
    if (!this.config.exists("worlds")){
        this.config.set("#worlds(保护列表)","#世界名称,分割(英文)");
        this.config.set("worlds","");
        this.config.set("createmode","false");
        this.config.save();
    }

    HashMap<String, String> permissions = new HashMap<>();
    permissions.put("world.protect.command.worldprotectcommand", "op");
    permissions.forEach((name, permission) -> Server.getInstance().getPluginManager().addPermission(new Permission(name, permission)));
    Server.getInstance().getCommandMap().register("", new WorldProtectCommand());

    List<String> list = new ArrayList<>();
    list.addAll(Arrays.asList(this.config.get("worlds").toString().split(",")));
    this.worlds = list;
}
 
Example 6
Project: esup-ecandidat   File: DroitProfilController.java   View Source Code Vote up 6 votes
/** Enregistre un droit profil
 * @param droitProfil
 * @param fonctionnaliteMap
 */
public void saveDroitProfil(DroitProfil droitProfil, HashMap<DroitFonctionnalite, Boolean> fonctionnaliteMap) {
	Assert.notNull(droitProfil, applicationContext.getMessage("assert.notNull", null, UI.getCurrent().getLocale()));

	/* Verrou */
	if (droitProfil.getIdProfil()!=null && !lockController.getLockOrNotify(droitProfil, null)) {
		return;
	}
	
	final DroitProfil droitProfilSaved = droitProfilRepository.saveAndFlush(droitProfil);
	droitProfilSaved.getDroitProfilFoncs().clear();
	fonctionnaliteMap.forEach((k,v)->droitProfilSaved.addFonctionnalite(new DroitProfilFonc(k,droitProfilSaved,v)));
	/*on met a jour la date pour que l'entity soit push*/
	droitProfilSaved.setDatModProfil(LocalDateTime.now());
	
	droitProfilRepository.saveAndFlush(droitProfilSaved);
	lockController.releaseLock(droitProfilSaved);
}
 
Example 7
Project: RecursiveSwaggerSchemaParser   File: SwaggerParserHelper.java   View Source Code Vote up 6 votes
private void getSchemaFromModel(Model model) {
    HashMap<String, Property> references = getAllSchemaReferencesFromModel(model);

    references.forEach((modelKey, property) -> {
        String simpleRef = null;
        Boolean isArray = false;
        if (property instanceof RefProperty) {
            simpleRef = ((RefProperty) property).getSimpleRef();
        } else {
            Property items = ((ArrayProperty) property).getItems();
            if (items instanceof RefProperty) {
                simpleRef = ((RefProperty) items).getSimpleRef();
            } else {
                return;
            }
        }
        if (simpleRef != null) {
            getDefinationsFromSchemaReference(simpleRef, modelKey);
        }

    });
}
 
Example 8
Project: MFM   File: ZipUtils.java   View Source Code Vote up 6 votes
public static TreeMap<String, TreeMap<String, String>> getZipEntryNames(HashMap<String, File> extrasZipFilesMap) {
    final TreeMap<String, TreeMap<String, String>> zipEntries = new TreeMap<String, TreeMap<String, String>>();
    extrasZipFilesMap.forEach((key, file) -> {
        zipEntries.put(key, getZipEntries(file.getAbsolutePath()));
    });
    return zipEntries;
}
 
Example 9
Project: StickyChunk   File: CommandUnload.java   View Source Code Vote up 5 votes
/**
 * Callback for the execution of a command.
 *
 * @param src  The commander who is executing this command
 * @param args The parsed command arguments for this command
 * @return the result of executing this command
 * @throws CommandException If a user-facing error occurs while executing this command
 */
public CommandResult execute(CommandSource src, CommandContext args) throws CommandException {
	if (!(src instanceof Player))
		return execServer(src, args);

	HashMap<Player, UUID> deleteQueue = Maps.newHashMap();
	Player player = (Player) src;

	if (args.hasAny(ALL)) {
		player.sendMessage(Text.of(
			TextColors.GOLD, "Are you sure you want to unload all? ",
			TextColors.GREEN, Text.builder("Yes ").onClick(TextActions.executeCallback(unloadAll(player))),
			TextColors.RED, Text.builder("No").onClick(TextActions
				.executeCallback(s -> player.sendMessage(Text.of(TextColors.GREEN, "Unload All Cancelled."))))
		));
		return CommandResult.success();
	}

	dataStore.getPlayerRegions(player).forEach(region ->
		region.getChunks().forEach(chunk -> {
				if (player.getLocation().getChunkPosition().equals(chunk.getPosition())) {
					region.unForceChunks();
					region.invalidateTicket();
					deleteQueue.put(player, region.getUniqueId());
					player.sendMessage(Text.of(TextColors.GREEN, "Successfully removed loaded region"));
				}
			}
		));

	// Delete all the regions queued to be deleted
	deleteQueue.forEach((owner, regionId) -> dataStore.deletePlayerRegion(owner, regionId));

	return CommandResult.success();
}
 
Example 10
Project: yum   File: ChefOrdersService.java   View Source Code Vote up 5 votes
private List<OrderItem> getOrderItemList(com.jrtechnologies.yum.data.entity.DailyMenu dailyMenuEntity, Long userId) {

        List<OrderItem> orderItemList = new ArrayList<OrderItem>();
        HashMap<Long, Integer> foodQtys = new HashMap<>();
        
        // get all orders
        List<DailyOrder> dailyOrderEntities = dailyMenuEntity.getDailyOrders();
        for(DailyOrder doe : dailyOrderEntities){
            
            if(userId==ALL_USERS || doe.getUserId()==userId){
            
                List<com.jrtechnologies.yum.data.entity.OrderItem> orderItems = doe.getOrderItems();
                for(com.jrtechnologies.yum.data.entity.OrderItem orderItemEntity : orderItems){
                    Long foodId = orderItemEntity.getFood().getId();
                    foodQtys.put(foodId, (foodQtys.get(foodId)==null?0:foodQtys.get(foodId)) + orderItemEntity.getQuantity());
                }                     
            }
        }
        
        foodQtys.forEach((k,v)->{
            OrderItem orderItem = new OrderItem();
            orderItem.setFoodId(k);
            orderItem.setQuantity(v);
            //System.out.println("Item : " + k + " Count : " + v);

            orderItemList.add(orderItem);
        });
        
        return orderItemList;
    }
 
Example 11
Project: Nukkit-DontTapTheWhiteTile   File: DontTapTheWhiteTile.java   View Source Code Vote up 5 votes
private void initCommand(){
    HashMap<String, String> permissions = new HashMap<>();
    permissions.put("DontTapTheWhiteTile.Command.SetGame", "op");
    permissions.put("DontTapTheWhiteTile.Command.DelGame", "op");
    permissions.forEach((name, permission) -> Server.getInstance().getPluginManager().addPermission(new Permission(name, permission)));
    Server.getInstance().getCommandMap().register("", new SetGame());
    Server.getInstance().getCommandMap().register("", new DelGame());
}
 
Example 12
Project: learnjava8   File: FunctionalFace.java   View Source Code Vote up 5 votes
public static void main(String args[]) throws IOException {

        // Function
        intIs = i -> new StringBuilder("Integer is: ").append(String.valueOf(i)).toString();
        System.out.println(intIs.apply(121));

        // UnaryOperator
        UnaryOperator<Integer> randInt = x -> (int) (Math.random() * 100);

        // Supplier
        printInt(() -> 78);
        printInt(FunctionalFace::doubleInt);               

        // Consumer
        Consumer<Integer> com = x -> System.out.println(intIs.apply(x));
        com.accept(randInt.apply(100));
        com.accept(101);

        // Predicate
        Predicate<Integer> oe = x -> x % 2 == 0;
        oddEvent(randInt.apply(50), oe);
        oddEvent(127, oe);

        // BiConsumer
        HashMap<String, String> hash = new HashMap<>();
        hash.put("cat", "orange");
        hash.put("dog", "black");
        hash.put("snake", "green");
        // Use lambda expression that matches BiConsumer to display HashMap.
        hash.forEach((string1, string2) -> System.out.println(string1 + "..."
                + string2 + ", " + string1.length()));                      
    }
 
Example 13
Project: athena   File: AnnotationsSerializer.java   View Source Code Vote up 5 votes
@Override
public DefaultAnnotations read(Kryo kryo, Input input, Class<DefaultAnnotations> type) {
    DefaultAnnotations.Builder b = DefaultAnnotations.builder();
    HashMap<String, String> map = kryo.readObject(input, HashMap.class);
    map.forEach((k, v) -> b.set(k, v));

    return b.build();
}
 
Example 14
Project: n5   File: GsonAttributesParser.java   View Source Code Vote up 5 votes
/**
 * Best effort implementation of {@link N5Reader#listAttributes(String)}
 * with limited type resolution.  Possible return types are
 * <ul>
 * <li>null</li>
 * <li>boolean</li>
 * <li>double</li>
 * <li>String</li>
 * <li>Object</li>
 * <li>boolean[]</li>
 * <li>double[]</li>
 * <li>String[]</li>
 * <li>Object[]</li>
 * </ul>
 */
@Override
public default Map<String, Class<?>> listAttributes(String pathName) throws IOException {

	HashMap<String, JsonElement> jsonElementMap = getAttributes(pathName);
	final HashMap<String, Class<?>> attributes = new HashMap<>();
	jsonElementMap.forEach(
			(key, jsonElement) -> {
				final Class<?> clazz;
				if (jsonElement.isJsonNull())
					clazz = null;
				else if (jsonElement.isJsonPrimitive())
					clazz = classForJsonPrimitive((JsonPrimitive)jsonElement);
				else if (jsonElement.isJsonArray()) {
					final JsonArray jsonArray = (JsonArray)jsonElement;
					if (jsonArray.size() > 0) {
						final JsonElement firstElement = jsonArray.get(0);
						if (firstElement.isJsonPrimitive())
							clazz = Array.newInstance(classForJsonPrimitive((JsonPrimitive)firstElement), 0).getClass();
						else
							clazz = Object[].class;
						}
					else
						clazz = Object[].class;
				}
				else
					clazz = Object.class;
				attributes.put(key, clazz);
			});
	return attributes;
}
 
Example 15
Project: BestoonGui   File: Connection.java   View Source Code Vote up 4 votes
public JSONObject sendPostRequest(HashMap<String, String> data, String url) {
	if(!netIsAvailable()){
		JOptionPane.showMessageDialog(null, "Internet connection error !", "Error", JOptionPane.ERROR_MESSAGE);
		return null;
	}
	HttpClient httpClient = HttpClientBuilder.create().build();

	try {

		HttpPost request = new HttpPost(url);

		List<NameValuePair> urlParameters = new ArrayList<NameValuePair>();
		data.forEach((k, v) -> {
			urlParameters.add(new BasicNameValuePair(k, v));
		});

		request.setEntity(new UrlEncodedFormEntity(urlParameters));
		request.addHeader("content-type", "application/x-www-form-urlencoded");
		HttpResponse response = httpClient.execute(request);

		if (response.getStatusLine().getStatusCode() == 404)
			return null;

		BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));

		StringBuffer result = new StringBuffer();
		String line = "";
		while ((line = rd.readLine()) != null) {
			result.append(line);
		}

		JSONObject obj = new JSONObject(result.toString());

		return obj;
	} catch (Exception ex) {
		ex.printStackTrace();
		return null;

	} finally {

	}
}
 
Example 16
Project: RISE-V2G   File: SecurityUtils.java   View Source Code Vote up 4 votes
/**
 * 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;
}
 
Example 17
Project: BWDM   File: BoundaryValueAnalyzer.java   View Source Code Vote up 4 votes
private void generateIfConditionalBoundaryValue(InformationExtractor _information) {
	HashMap allIfConditions = _information.getIfConditions();

	allIfConditions.forEach( (parameter, ifConditions) ->{
		((ArrayList) ifConditions).forEach(condition -> { //condition : HashMap<String, String>
			String left   = ((HashMap<String, String>) condition).get("left");
			String operator = ((HashMap<String, String>) condition).get("operator");
			String right  = ((HashMap<String, String>) condition).get("right");
			ArrayList bvs = boundaryValueList.get(parameter);

			long bv1=0, bv2=0, value=0;
			if(Util.isNumber(left)) {
				value = Long.parseLong(left);
				switch (operator) {
					case "<=":
						bv1 = value;
						bv2 = bv1 - 1;
						break;
					case "<":
						bv1 = value + 1;
						bv2 = bv1 - 1;
						break;
					case ">=":
						bv1 = value;
						bv2 = bv1 + 1;
						break;
					case ">":
						bv1 = value + 1;
						bv2 = bv1 + 1;
						break;
					case "mod":
						bv1 = value;
						bv2 = value + 1;
						bvs.add(value - 1);
						break;
				}

			} else if(Util.isNumber(right)) {
				value = Long.parseLong(right);
				switch (operator) {
					case "<=":
						bv1 = value;
						bv2 = bv1 + 1;
						break;
					case "<":
						bv1 = value + 1;
						bv2 = bv1 - 1;
						break;
					case ">=":
						bv1 = value;
						bv2 = bv1 + 1;
						break;
					case ">":
						bv1 = value + 1;
						bv2 = bv1 - 1;
						break;
					case "mod":
						bv1 = value;
						bv2 = value + 1;
						bvs.add(value - 1);
						break;
				}
			}

			bvs.add(bv1);
			bvs.add(bv2);

		});

	});
}