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.nosql.appender.couchdb;
018
019import java.util.Map;
020import java.util.concurrent.atomic.AtomicBoolean;
021
022import org.apache.logging.log4j.core.appender.AppenderLoggingException;
023import org.apache.logging.log4j.nosql.appender.DefaultNoSqlObject;
024import org.apache.logging.log4j.nosql.appender.NoSqlConnection;
025import org.apache.logging.log4j.nosql.appender.NoSqlObject;
026import org.lightcouch.CouchDbClient;
027import org.lightcouch.Response;
028
029/**
030 * The Apache CouchDB implementation of {@link NoSqlConnection}.
031 */
032public final class CouchDbConnection implements NoSqlConnection<Map<String, Object>, DefaultNoSqlObject> {
033    private final CouchDbClient client;
034    private final AtomicBoolean closed = new AtomicBoolean(false);
035
036    public CouchDbConnection(final CouchDbClient client) {
037        this.client = client;
038    }
039
040    @Override
041    public DefaultNoSqlObject createObject() {
042        return new DefaultNoSqlObject();
043    }
044
045    @Override
046    public DefaultNoSqlObject[] createList(final int length) {
047        return new DefaultNoSqlObject[length];
048    }
049
050    @Override
051    public void insertObject(final NoSqlObject<Map<String, Object>> object) {
052        try {
053            final Response response = this.client.save(object.unwrap());
054            if (response.getError() != null && response.getError().length() > 0) {
055                throw new AppenderLoggingException("Failed to write log event to CouchDB due to error: " +
056                        response.getError() + '.');
057            }
058        } catch (final Exception e) {
059            throw new AppenderLoggingException("Failed to write log event to CouchDB due to error: " + e.getMessage(),
060                    e);
061        }
062    }
063
064    @Override
065    public void close() {
066        if (this.closed.compareAndSet(false, true)) {
067            this.client.shutdown();
068        }
069    }
070
071    @Override
072    public boolean isClosed() {
073        return this.closed.get();
074    }
075}