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.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          .reason(Optional.ofNullable(ldapException)
34              .map(LdapException::getMessage)
35              .orElse("Unknown"))
36          .errorCode(errorCode(ldapException))
37          .httpStatus(httpStatus(ldapException))
38          .cause(ldapException)
39          .build();
40    }
41  
42    private int httpStatus(LdapException ldapException) {
43      return Optional.ofNullable(ldapException)
44          .map(LdapException::getResultCode)
45          .map(this::httpStatus)
46          .orElse(500);
47    }
48  
49    private int httpStatus(ResultCode resultCode) {
50      ResultCode code = Optional.ofNullable(resultCode).orElse(ResultCode.OTHER);
51      return switch (code) {
52        case SUCCESS -> 200;
53        case INVALID_CREDENTIALS -> 400;
54        case NO_SUCH_OBJECT -> 404;
55        default -> 500;
56      };
57    }
58  
59    private String errorCode(LdapException ldapException) {
60      return Optional.ofNullable(ldapException)
61          .map(LdapException::getResultCode)
62          .map(ResultCode::name)
63          .orElse(null);
64    }
65  
66  }