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.couchdb;
018
019import org.apache.logging.log4j.Logger;
020import org.apache.logging.log4j.core.appender.nosql.NoSqlProvider;
021import org.apache.logging.log4j.core.config.plugins.Plugin;
022import org.apache.logging.log4j.core.config.plugins.PluginAttribute;
023import org.apache.logging.log4j.core.config.plugins.PluginFactory;
024import org.apache.logging.log4j.core.config.plugins.convert.TypeConverters;
025import org.apache.logging.log4j.core.config.plugins.validation.constraints.ValidHost;
026import org.apache.logging.log4j.core.config.plugins.validation.constraints.ValidPort;
027import org.apache.logging.log4j.status.StatusLogger;
028import org.apache.logging.log4j.util.LoaderUtil;
029import org.apache.logging.log4j.util.Strings;
030import org.lightcouch.CouchDbClient;
031import org.lightcouch.CouchDbProperties;
032
033import java.lang.reflect.Method;
034
035/**
036 * The Apache CouchDB implementation of {@link NoSqlProvider}.
037 */
038@Plugin(name = "CouchDB", category = "Core", printObject = true)
039public final class CouchDbProvider implements NoSqlProvider<CouchDbConnection> {
040    private static final int HTTP = 80;
041    private static final int HTTPS = 443;
042    private static final Logger LOGGER = StatusLogger.getLogger();
043
044    private final CouchDbClient client;
045    private final String description;
046
047    private CouchDbProvider(final CouchDbClient client, final String description) {
048        this.client = client;
049        this.description = "couchDb{ " + description + " }";
050    }
051
052    @Override
053    public CouchDbConnection getConnection() {
054        return new CouchDbConnection(this.client);
055    }
056
057    @Override
058    public String toString() {
059        return this.description;
060    }
061
062    /**
063     * Factory method for creating an Apache CouchDB provider within the plugin manager.
064     *
065     * @param databaseName The name of the database to which log event documents will be written.
066     * @param protocol Either "http" or "https," defaults to "http" and mutually exclusive with
067     *                 {@code factoryClassName&factoryMethodName!=null}.
068     * @param server The host name of the CouchDB server, defaults to localhost and mutually exclusive with
069     *               {@code factoryClassName&factoryMethodName!=null}.
070     * @param port The port that CouchDB is listening on, defaults to 80 if {@code protocol} is "http" and 443 if
071     *             {@code protocol} is "https," and mutually exclusive with
072     *             {@code factoryClassName&factoryMethodName!=null}.
073     * @param username The username to authenticate against the MongoDB server with, mutually exclusive with
074     *                 {@code factoryClassName&factoryMethodName!=null}.
075     * @param password The password to authenticate against the MongoDB server with, mutually exclusive with
076     *                 {@code factoryClassName&factoryMethodName!=null}.
077     * @param factoryClassName A fully qualified class name containing a static factory method capable of returning a
078     *                         {@link CouchDbClient} or {@link CouchDbProperties}.
079     * @param factoryMethodName The name of the public static factory method belonging to the aforementioned factory
080     *                          class.
081     * @return a new Apache CouchDB provider.
082     */
083    @PluginFactory
084    public static CouchDbProvider createNoSqlProvider(
085            @PluginAttribute("databaseName") final String databaseName,
086            @PluginAttribute("protocol") String protocol,
087            @PluginAttribute(value = "server", defaultString = "localhost") @ValidHost final String server,
088            @PluginAttribute(value = "port", defaultString = "0") @ValidPort final String port,
089            @PluginAttribute("username") final String username,
090            @PluginAttribute(value = "password", sensitive = true) final String password,
091            @PluginAttribute("factoryClassName") final String factoryClassName,
092            @PluginAttribute("factoryMethodName") final String factoryMethodName) {
093        CouchDbClient client;
094        String description;
095        if (Strings.isNotEmpty(factoryClassName) && Strings.isNotEmpty(factoryMethodName)) {
096            try {
097                final Class<?> factoryClass = LoaderUtil.loadClass(factoryClassName);
098                final Method method = factoryClass.getMethod(factoryMethodName);
099                final Object object = method.invoke(null);
100
101                if (object instanceof CouchDbClient) {
102                    client = (CouchDbClient) object;
103                    description = "uri=" + client.getDBUri();
104                } else if (object instanceof CouchDbProperties) {
105                    final CouchDbProperties properties = (CouchDbProperties) object;
106                    client = new CouchDbClient(properties);
107                    description = "uri=" + client.getDBUri() + ", username=" + properties.getUsername()
108                            + ", maxConnections=" + properties.getMaxConnections() + ", connectionTimeout="
109                            + properties.getConnectionTimeout() + ", socketTimeout=" + properties.getSocketTimeout();
110                } else {
111                    if (object == null) {
112                        LOGGER.error("The factory method [{}.{}()] returned null.", factoryClassName, factoryMethodName);
113                    } else {
114                        LOGGER.error("The factory method [{}.{}()] returned an unsupported type [{}].", factoryClassName,
115                                factoryMethodName, object.getClass().getName());
116                    }
117                    return null;
118                }
119            } catch (final ClassNotFoundException e) {
120                LOGGER.error("The factory class [{}] could not be loaded.", factoryClassName, e);
121                return null;
122            } catch (final NoSuchMethodException e) {
123                LOGGER.error("The factory class [{}] does not have a no-arg method named [{}].", factoryClassName,
124                        factoryMethodName, e);
125                return null;
126            } catch (final Exception e) {
127                LOGGER.error("The factory method [{}.{}()] could not be invoked.", factoryClassName, factoryMethodName,
128                        e);
129                return null;
130            }
131        } else if (Strings.isNotEmpty(databaseName)) {
132            if (protocol != null && protocol.length() > 0) {
133                protocol = protocol.toLowerCase();
134                if (!protocol.equals("http") && !protocol.equals("https")) {
135                    LOGGER.error("Only protocols [http] and [https] are supported, [{}] specified.", protocol);
136                    return null;
137                }
138            } else {
139                protocol = "http";
140                LOGGER.warn("No protocol specified, using default port [http].");
141            }
142
143            final int portInt = TypeConverters.convert(port, int.class, protocol.equals("https") ? HTTPS : HTTP);
144
145            if (Strings.isEmpty(username) || Strings.isEmpty(password)) {
146                LOGGER.error("You must provide a username and password for the CouchDB provider.");
147                return null;
148            }
149
150            client = new CouchDbClient(databaseName, false, protocol, server, portInt, username, password);
151            description = "uri=" + client.getDBUri() + ", username=" + username;
152        } else {
153            LOGGER.error("No factory method was provided so the database name is required.");
154            return null;
155        }
156
157        return new CouchDbProvider(client, description);
158    }
159}