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