001/*
002 * Licensed to the Apache Software Foundation (ASF) under one or more
003 * contributor license agreements. See the NOTICE file distributed with
004 * this work for additional information regarding copyright ownership.
005 * The ASF licenses this file to You under the Apache license, Version 2.0
006 * (the "License"); you may not use this file except in compliance with
007 * the License. You may obtain a copy of the License at
008 *
009 *      http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the license for the specific language governing permissions and
015 * limitations under the license.
016 */
017package org.apache.logging.log4j.core.appender.db.jdbc;
018
019import java.sql.Connection;
020import java.sql.SQLException;
021import java.util.Objects;
022
023import javax.naming.NamingException;
024import javax.sql.DataSource;
025
026import org.apache.logging.log4j.Logger;
027import org.apache.logging.log4j.core.config.plugins.Plugin;
028import org.apache.logging.log4j.core.config.plugins.PluginAttribute;
029import org.apache.logging.log4j.core.config.plugins.PluginFactory;
030import org.apache.logging.log4j.core.net.JndiManager;
031import org.apache.logging.log4j.status.StatusLogger;
032import org.apache.logging.log4j.util.Strings;
033
034/**
035 * A {@link JdbcAppender} connection source that uses a {@link DataSource} to connect to the database.
036 */
037@Plugin(name = "DataSource", category = "Core", elementType = "connectionSource", printObject = true)
038public final class DataSourceConnectionSource implements ConnectionSource {
039    private static final Logger LOGGER = StatusLogger.getLogger();
040
041    private final DataSource dataSource;
042    private final String description;
043
044    private DataSourceConnectionSource(final String dataSourceName, final DataSource dataSource) {
045        this.dataSource = Objects.requireNonNull(dataSource, "dataSource");
046        this.description = "dataSource{ name=" + dataSourceName + ", value=" + dataSource + " }";
047    }
048
049    @Override
050    public Connection getConnection() throws SQLException {
051        return this.dataSource.getConnection();
052    }
053
054    @Override
055    public String toString() {
056        return this.description;
057    }
058
059    /**
060     * Factory method for creating a connection source within the plugin manager.
061     *
062     * @param jndiName The full JNDI path where the data source is bound. Must start with java:/comp/env or environment-equivalent.
063     * @return the created connection source.
064     */
065    @PluginFactory
066    public static DataSourceConnectionSource createConnectionSource(@PluginAttribute("jndiName") final String jndiName) {
067        if (!JndiManager.isJndiJdbcEnabled()) {
068            LOGGER.error("JNDI must be enabled by setting log4j2.enableJndiJdbc=true");
069            return null;
070        }
071        if (Strings.isEmpty(jndiName)) {
072            LOGGER.error("No JNDI name provided.");
073            return null;
074        }
075        try {
076            @SuppressWarnings("resource")
077            final DataSource dataSource = JndiManager.getDefaultManager(DataSourceConnectionSource.class.getCanonicalName()).lookup(jndiName);
078            if (dataSource == null) {
079                LOGGER.error("No DataSource found with JNDI name [" + jndiName + "].");
080                return null;
081            }
082            return new DataSourceConnectionSource(jndiName, dataSource);
083        } catch (final NamingException e) {
084            LOGGER.error(e.getMessage(), e);
085            return null;
086        }
087    }
088}