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