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.core.appender.db.nosql.couch;
18  
19  import java.util.Map;
20  
21  import org.apache.logging.log4j.Logger;
22  import org.apache.logging.log4j.core.appender.db.nosql.NoSQLConnection;
23  import org.apache.logging.log4j.core.appender.db.nosql.NoSQLObject;
24  import org.apache.logging.log4j.status.StatusLogger;
25  import org.lightcouch.CouchDbClient;
26  import org.lightcouch.Response;
27  
28  /**
29   * The Apache CouchDB implementation of {@link NoSQLConnection}.
30   */
31  public final class CouchDBConnection implements NoSQLConnection<Map<String, Object>, CouchDBObject> {
32      private static final Logger LOGGER = StatusLogger.getLogger();
33  
34      private final CouchDbClient client;
35      private boolean closed = false;
36  
37      public CouchDBConnection(final CouchDbClient client) {
38          this.client = client;
39      }
40  
41      @Override
42      public CouchDBObject createObject() {
43          return new CouchDBObject();
44      }
45  
46      @Override
47      public CouchDBObject[] createList(final int length) {
48          return new CouchDBObject[length];
49      }
50  
51      @Override
52      public void insertObject(final NoSQLObject<Map<String, Object>> object) {
53          try {
54              final Response response = this.client.save(object.unwrap());
55              if (response.getError() != null && response.getError().length() > 0) {
56                  LOGGER.error("Failed to write log event to CouchDB due to error: [{}].", response.getError());
57              }
58          } catch (final Exception e) {
59              LOGGER.error("Failed to write log event to CouchDB due to error.", e);
60          }
61      }
62  
63      @Override
64      public synchronized void close() {
65          this.closed = true;
66          this.client.shutdown();
67      }
68  
69      @Override
70      public synchronized boolean isClosed() {
71          return this.closed;
72      }
73  }