001/**
002 * Logback: the reliable, generic, fast and flexible logging framework.
003 * Copyright (C) 1999-2015, QOS.ch. All rights reserved.
004 *
005 * This program and the accompanying materials are dual-licensed under
006 * either the terms of the Eclipse Public License v1.0 as published by
007 * the Eclipse Foundation
008 *
009 *   or (per the licensee's choosing)
010 *
011 * under the terms of the GNU Lesser General Public License version 2.1
012 * as published by the Free Software Foundation.
013 */
014package ch.qos.logback.core.property;
015
016import ch.qos.logback.core.PropertyDefinerBase;
017import ch.qos.logback.core.util.Loader;
018import ch.qos.logback.core.util.OptionHelper;
019
020import java.net.URL;
021
022/**
023 * In conjunction with {@link ch.qos.logback.core.joran.action.PropertyAction} sets
024 * the named variable to "true" if the {@link #setResource(String) resource} specified
025 * by the user is available on the class path, "false" otherwise.
026 *
027 * @see #getPropertyValue()
028 *
029 * @author XuHuisheng
030 * @author Ceki Gulcu
031 * @since 1.1.0
032 */
033public class ResourceExistsPropertyDefiner extends PropertyDefinerBase {
034
035    String resourceStr;
036
037    public String getResource() {
038        return resourceStr;
039    }
040
041    /**
042     * The resource to search for on the class path.
043     *
044     * @param resource
045     */
046    public void setResource(String resource) {
047        this.resourceStr = resource;
048    }
049
050    /**
051     * Returns the string "true" if the {@link #setResource(String) resource} specified by the
052     * user is available on the class path, "false" otherwise.
053     *
054     * @return "true"|"false" depending on the availability of resource on the classpath
055     */
056    public String getPropertyValue() {
057        if (OptionHelper.isEmpty(resourceStr)) {
058            addError("The \"resource\" property must be set.");
059            return null;
060        }
061
062        URL resourceURL = Loader.getResourceBySelfClassLoader(resourceStr);
063        return booleanAsStr(resourceURL != null);
064    }
065
066}