/** * Copyright 2011 the original author or authors. * * Licensed under the Apache 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.apache.org/licenses/LICENSE-2.0 * * 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.bricket.web.util; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.util.Map.Entry; import java.util.Properties; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import brix.exception.BrixException; public final class PropertyUtils { private static final Logger LOG = LoggerFactory.getLogger(PropertyUtils.class); private PropertyUtils() { super(); } /** * Loads properties from a classpath resource * * @param resource * @param throwExceptionIfNotFound * @return loaded properties */ public static Properties loadFromClassPath(String resource, boolean throwExceptionIfNotFound) { URL url = PropertyUtils.class.getClassLoader().getResource(resource); if (url == null) { if (throwExceptionIfNotFound) { throw new IllegalStateException("Could not find classpath properties resource: " + resource); } else { return new Properties(); } } InputStream is = null; try { is = url.openStream(); Properties props = new Properties(); props.load(url.openStream()); return props; } catch (IOException e) { throw new BrixException("Could not read properties at classpath resource: " + resource, e); } finally { if (is != null) { try { is.close(); } catch (IOException e) { LOG.error("error closing property input stream.", e); } } } } /** * Merge mode * * @author igor.vaynberg * */ public static enum MergeMode { OVERRIDE_ONLY, MERGE } /** * Merges multiple {@link Properties} instances into one * * @param mode * merge mode * @param sources * properties to merge * @return new instance of {@link Properties} containing merged values */ public static Properties merge(MergeMode mode, Properties... sources) { Properties props = new Properties(); for (int i = 0; i < sources.length; i++) { final Properties source = sources[i]; for (Entry<Object, Object> prop : source.entrySet()) { final boolean exists = props.containsKey(prop.getKey()); boolean set = false; switch (mode) { case MERGE: set = true; break; case OVERRIDE_ONLY: set = exists; break; default: set = false; break; } if (set || i == 0) { props.put(prop.getKey(), prop.getValue()); } } } return props; } }