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.Core;
028import org.apache.logging.log4j.core.config.plugins.Plugin;
029import org.apache.logging.log4j.core.config.plugins.PluginAttribute;
030import org.apache.logging.log4j.core.config.plugins.PluginFactory;
031import org.apache.logging.log4j.core.net.JndiManager;
032import org.apache.logging.log4j.status.StatusLogger;
033import org.apache.logging.log4j.util.Strings;
034
035/**
036 * A {@link JdbcAppender} connection source that uses a {@link DataSource} to connect to the database.
037 */
038@Plugin(name = "DataSource", category = Core.CATEGORY_NAME, elementType = "connectionSource", printObject = true)
039public final class DataSourceConnectionSource extends AbstractConnectionSource {
040    private static final Logger LOGGER = StatusLogger.getLogger();
041
042    private final DataSource dataSource;
043    private final String description;
044
045    private DataSourceConnectionSource(final String dataSourceName, final DataSource dataSource) {
046        this.dataSource = Objects.requireNonNull(dataSource, "dataSource");
047        this.description = "dataSource{ name=" + dataSourceName + ", value=" + dataSource + " }";
048    }
049
050    @Override
051    public Connection getConnection() throws SQLException {
052        return this.dataSource.getConnection();
053    }
054
055    @Override
056    public String toString() {
057        return this.description;
058    }
059
060    /**
061     * Factory method for creating a connection source within the plugin manager.
062     *
063     * @param jndiName The full JNDI path where the data source is bound. Must start with java:/comp/env or environment-equivalent.
064     * @return the created connection source.
065     */
066    @PluginFactory
067    public static DataSourceConnectionSource createConnectionSource(@PluginAttribute("jndiName") final String jndiName) {
068        if (!JndiManager.isJndiJdbcEnabled()) {
069            LOGGER.error("JNDI must be enabled by setting log4j2.enableJndiJdbc=true");
070            return null;
071        }
072        if (Strings.isEmpty(jndiName)) {
073            LOGGER.error("No JNDI name provided.");
074            return null;
075        }
076        try {
077            @SuppressWarnings("resource")
078            final DataSource dataSource = JndiManager.getDefaultManager(DataSourceConnectionSource.class.getCanonicalName()).lookup(jndiName);
079            if (dataSource == null) {
080                LOGGER.error("No DataSource found with JNDI name [" + jndiName + "].");
081                return null;
082            }
083            return new DataSourceConnectionSource(jndiName, dataSource);
084        } catch (final NamingException e) {
085            LOGGER.error(e.getMessage(), e);
086            return null;
087        }
088    }
089}