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