001/*
002 * (C) Copyright 2018 Nuxeo (http://nuxeo.com/) and others.
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 *     http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 *
016 * Contributors:
017 *     Florent Guillaume
018 */
019package org.nuxeo.runtime.aws;
020
021import static org.apache.commons.lang3.StringUtils.defaultString;
022
023import org.nuxeo.runtime.api.Framework;
024
025import com.amazonaws.SdkClientException;
026import com.amazonaws.regions.AwsRegionProvider;
027import com.amazonaws.regions.DefaultAwsRegionProviderChain;
028
029/**
030 * AWS Region Provider that uses Nuxeo configuration, or uses the default AWS chain as a fallback.
031 *
032 * @since 10.3
033 */
034public class NuxeoAWSRegionProvider extends AwsRegionProvider {
035
036    protected static final AwsRegionProvider INSTANCE = new NuxeoAWSRegionProvider();
037
038    protected static final AwsRegionProvider DEFAULT = new DefaultAwsRegionProviderChain();
039
040    protected static final String DEFAULT_REGION = "us-east-1";
041
042    public static AwsRegionProvider getInstance() {
043        return INSTANCE;
044    }
045
046    @Override
047    public String getRegion() {
048        AWSConfigurationService service = Framework.getService(AWSConfigurationService.class);
049        if (service != null) {
050            String region = service.getAWSRegion();
051            if (region != null) {
052                return region;
053            }
054        }
055        String region;
056        try {
057            region = DEFAULT.getRegion();
058        } catch (SdkClientException e) {
059            // the DefaultAwsRegionProviderChain throws when there's no provider instead of defaulting to null
060            region = null;
061        }
062        return defaultString(region, DEFAULT_REGION);
063    }
064
065}