Java tutorial
/* * Copyright 2015 Kaiserpfalz EDV-Service Roland Lichti * * 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 de.kaiserpfalzEdv.commons.jee.servlet.util; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.servlet.ServletContext; import static com.google.common.base.Preconditions.checkArgument; import static org.apache.commons.lang3.StringUtils.isNotBlank; /** * Reads configuration from the Servlet Context. * * @author klenkes * @since 2013Q */ public class ServletContextParamReader { private static final Logger LOG = LoggerFactory.getLogger(ServletContextParamReader.class); private ServletContext context; /** * @param context The application servlet context. * @throws IllegalArgumentException If the servlet context is NULL. */ public ServletContextParamReader(ServletContext context) { checkArgument(context != null, "Can't read configuration from NULL context."); this.context = context; //noinspection ConstantConditions LOG.info("Loading configuration from context: {}", context.getServletContextName()); } /** * @param key The param name to read from context. * @param defaultValue the default to be returned if nothing is configured. * @return the value read from servlet context param or the given defaultValue. * @throws IllegalArgumentException If the key is NULL, empty or blank. */ public String getParam(String key, String defaultValue) { checkArgument(isNotBlank(key), "Can't read configuration for an empty key!"); String result = context.getInitParameter(key); LOG.debug("Configuration load {\"key\": \"{}\", \"value\": \"{}\", \"default\": \"{}\"}", key, result, defaultValue); return (result != null) ? result : defaultValue; } }