001/*
002 * Licensed to the Apache Software Foundation (ASF) under one
003 * or more contributor license agreements.  See the NOTICE file
004 * distributed with this work for additional information
005 * regarding copyright ownership.  The ASF licenses this file
006 * to you under the Apache License, Version 2.0 (the
007 * "License"); you may not use this file except in compliance
008 * with the License.  You may obtain a copy of the License at
009 *
010 * http://www.apache.org/licenses/LICENSE-2.0
011 *
012 * Unless required by applicable law or agreed to in writing,
013 * software distributed under the License is distributed on an
014 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
015 * KIND, either express or implied.  See the License for the
016 * specific language governing permissions and limitations
017 * under the License.
018 *
019 * Contributors:
020 *     Florent Guillaume
021 */
022package org.nuxeo.ecm.core.opencmis.bindings;
023
024import org.apache.commons.lang3.StringUtils;
025import org.nuxeo.runtime.api.Framework;
026
027/**
028 * Helper to deal with HTTP errors.
029 *
030 * @since 7.1
031 */
032public class NuxeoCmisErrorHelper {
033
034    public static final String EXTRACTOR_CLASS_PROP = "org.nuxeo.cmis.errorextractor";
035
036    protected static ErrorExtractor errorExtractor;
037
038    /**
039     * Interface for a helper able to extract the error from an exception.
040     *
041     * @since 7.4
042     */
043    public interface ErrorExtractor {
044
045        /**
046         * Extracts the error from the exception.
047         *
048         * @param ex the exception
049         * @return the error info
050         */
051        ErrorInfo extractError(Exception ex);
052    }
053
054    /**
055     * Info about an error to return to client code.
056     *
057     * @since 7.1
058     */
059    public static class ErrorInfo {
060        public int statusCode;
061
062        public String exceptionName;
063
064        public String message;
065
066        public ErrorInfo(int statusCode, String exceptionName, String message) {
067            this.statusCode = statusCode;
068            this.exceptionName = exceptionName;
069            this.message = message;
070        }
071    }
072
073    public static ErrorInfo extractError(Exception ex) {
074        if (errorExtractor == null) {
075            String className = Framework.getProperty(EXTRACTOR_CLASS_PROP);
076            if (StringUtils.isBlank(className)) {
077                className = DefaultErrorExtractor.class.getName();
078            }
079            try {
080                errorExtractor = (ErrorExtractor) Class.forName(className).getDeclaredConstructor().newInstance();
081            } catch (ReflectiveOperationException | ClassCastException e) {
082                throw new RuntimeException("Cannot instantiate " + className, e);
083            }
084        }
085        return errorExtractor.extractError(ex);
086    }
087
088}