View Javadoc
1   /*
2    * Copyright 2019 the original author or authors.
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    *
8    *      http://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS,
12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   * See the License for the specific language governing permissions and
14   * limitations under the License.
15   */
16  
17  package org.bremersee.data.ldaptive;
18  
19  import java.util.Optional;
20  import org.ldaptive.LdapException;
21  import org.ldaptive.ResultCode;
22  
23  /**
24   * The default ldaptive error handler.
25   *
26   * @author Christian Bremer
27   */
28  public class DefaultLdaptiveErrorHandler extends AbstractLdaptiveErrorHandler {
29  
30    @Override
31    public LdaptiveException map(LdapException ldapException) {
32      return LdaptiveException.builder()
33          .errorCode(errorCode(ldapException))
34          .httpStatus(httpStatus(ldapException))
35          .cause(ldapException)
36          .build();
37    }
38  
39    private int httpStatus(LdapException ldapException) {
40      return Optional.ofNullable(ldapException)
41          .map(LdapException::getResultCode)
42          .map(this::httpStatus)
43          .orElse(500);
44    }
45  
46    private int httpStatus(ResultCode resultCode) {
47      ResultCode code = Optional.ofNullable(resultCode).orElse(ResultCode.OTHER);
48      switch (code) {
49        case SUCCESS:
50          return 200;
51        case INVALID_CREDENTIALS:
52          return 400;
53        case NO_SUCH_OBJECT:
54          return 404;
55        default:
56          return 500;
57      }
58    }
59  
60    private String errorCode(LdapException ldapException) {
61      return Optional.ofNullable(ldapException)
62          .map(LdapException::getResultCode)
63          .map(ResultCode::name)
64          .orElse(null);
65    }
66  
67  }