View Javadoc
1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one or more
3    * contributor license agreements. See the NOTICE file distributed with
4    * this work for additional information regarding copyright ownership.
5    * The ASF licenses this file to You under the Apache license, Version 2.0
6    * (the "License"); you may not use this file except in compliance with
7    * the License. You may obtain a copy of the License at
8    *
9    *      http://www.apache.org/licenses/LICENSE-2.0
10   *
11   * Unless required by applicable law or agreed to in writing, software
12   * distributed under the License is distributed on an "AS IS" BASIS,
13   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14   * See the license for the specific language governing permissions and
15   * limitations under the license.
16   */
17  package org.apache.logging.log4j.couchdb;
18  
19  import java.util.Map;
20  
21  import org.apache.logging.log4j.core.appender.AppenderLoggingException;
22  import org.apache.logging.log4j.core.appender.nosql.AbstractNoSqlConnection;
23  import org.apache.logging.log4j.core.appender.nosql.DefaultNoSqlObject;
24  import org.apache.logging.log4j.core.appender.nosql.NoSqlConnection;
25  import org.apache.logging.log4j.core.appender.nosql.NoSqlObject;
26  import org.apache.logging.log4j.util.Strings;
27  import org.lightcouch.CouchDbClient;
28  import org.lightcouch.Response;
29  
30  /**
31   * The Apache CouchDB implementation of {@link NoSqlConnection}.
32   */
33  public final class CouchDbConnection extends AbstractNoSqlConnection<Map<String, Object>, DefaultNoSqlObject> {
34      private final CouchDbClient client;
35  
36      public CouchDbConnection(final CouchDbClient client) {
37          this.client = client;
38      }
39  
40      @Override
41      public DefaultNoSqlObject createObject() {
42          return new DefaultNoSqlObject();
43      }
44  
45      @Override
46      public DefaultNoSqlObject[] createList(final int length) {
47          return new DefaultNoSqlObject[length];
48      }
49  
50      @Override
51      public void insertObject(final NoSqlObject<Map<String, Object>> object) {
52          try {
53              final Response response = this.client.save(object.unwrap());
54              if (Strings.isNotEmpty(response.getError())) {
55                  throw new AppenderLoggingException(
56                          "Failed to write log event to CouchDB due to error: " + response.getError() + '.');
57              }
58          } catch (final Exception e) {
59              throw new AppenderLoggingException("Failed to write log event to CouchDB due to error: " + e.getMessage(),
60                      e);
61          }
62      }
63  
64      @Override
65      protected void closeImpl() {
66          this.client.shutdown();
67      }
68  
69  }