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

org.kuali.common.util.base.string.Replacer Maven / Gradle / Ivy

There is a newer version: 4.4.17
Show newest version
/**
 * Copyright 2010-2014 The Kuali Foundation
 *
 * Licensed under the Educational Community License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.opensource.org/licenses/ecl2.php
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.kuali.common.util.base.string;

import static org.kuali.common.util.base.Precondition.checkNotNull;

import java.util.Map;

import com.google.common.collect.BiMap;
import com.google.common.collect.HashBiMap;
import com.google.common.collect.ImmutableBiMap;

public final class Replacer {

	private final ImmutableBiMap tokens;

	public String replace(final String string) {
		String s = string;
		for (Map.Entry pair : tokens.entrySet()) {
			s = s.replace(pair.getKey(), pair.getValue());
		}
		return s;
	}

	public String restore(final String string) {
		String s = string;
		for (Map.Entry pair : tokens.entrySet()) {
			s = s.replace(pair.getValue(), pair.getKey());
		}
		return s;
	}

	private Replacer(Builder builder) {
		this.tokens = ImmutableBiMap.copyOf(builder.tokens);
	}

	public static Replacer create(String oldToken, String newToken) {
		return builder().add(oldToken, newToken).build();
	}

	public static Builder builder() {
		return new Builder();
	}

	public static class Builder implements org.apache.commons.lang3.builder.Builder {

		private BiMap tokens = HashBiMap.create();

		public Builder add(String oldToken, String newToken) {
			this.tokens.put(oldToken, newToken);
			return this;
		}

		public Builder tokens(BiMap tokens) {
			this.tokens = tokens;
			return this;
		}

		@Override
		public Replacer build() {
			Replacer instance = new Replacer(this);
			validate(instance);
			return instance;
		}

		private static void validate(Replacer instance) {
			checkNotNull(instance.tokens, "tokens");
		}

		public BiMap getTokens() {
			return tokens;
		}

		public void setTokens(BiMap tokens) {
			this.tokens = tokens;
		}
	}

	public BiMap getTokens() {
		return tokens;
	}

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy