All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.magicwerk.brownies.html.IdMap Maven / Gradle / Ivy

The newest version!
package org.magicwerk.brownies.html;

import java.util.Map;
import java.util.WeakHashMap;

import org.magicwerk.brownies.core.CheckTools;
import org.magicwerk.brownies.core.TypeTools;

/**
 * Class {@link IdMap} allows to construct unique ids which can be used as id attribute for HTML elements.
 */
public class IdMap {

	/** Map holding the ids for the objects. It is implemented as {@link WeakHashMap} to prevent memory issues. */
	Map ids = new WeakHashMap<>();

	/**
	 * Clear map. As the map is implemented as {@link WeakHashMap}, it should normally not be necessary to clean it manually.
	 */
	public void clear() {
		ids.clear();
	}

	/**
	 * Returns id for passed key. If the key already has an id, it is returned. Otherwise a new id is created and returned.
	 */
	public String get(Object key) {
		return ids.computeIfAbsent(key, k -> createId());
	}

	/**
	 * Creates a new id for the passed key and and returns it. If the key already has an id, an exception is thrown.
	 */
	public String addAbsent(Object key) {
		String id = createId();
		String oldId = ids.putIfAbsent(key, id);
		CheckTools.check(oldId == null, "Duplicate key: {}", key);
		return id;
	}

	/**
	 * Retrieves the existing id for the passed key and and returns it. If the key does not have an id, an exception is thrown.
	 */
	public String getPresent(Object key) {
		String id = ids.get(key);
		CheckTools.check(id != null, "Unknown key: {}", key);
		return id;
	}

	String createId() {
		return TypeTools.format(ids.size());
	}
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy