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 java.util.Map; 020 021import org.apache.logging.log4j.core.appender.AppenderLoggingException; 022import org.apache.logging.log4j.core.appender.nosql.AbstractNoSqlConnection; 023import org.apache.logging.log4j.core.appender.nosql.DefaultNoSqlObject; 024import org.apache.logging.log4j.core.appender.nosql.NoSqlConnection; 025import org.apache.logging.log4j.core.appender.nosql.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 extends AbstractNoSqlConnection<Map<String, Object>, DefaultNoSqlObject> { 034 private final CouchDbClient client; 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 (Strings.isNotEmpty(response.getError())) { 055 throw new AppenderLoggingException( 056 "Failed to write log event to CouchDB due to error: " + 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 protected void closeImpl() { 066 this.client.shutdown(); 067 } 068 069}