All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.huawei.openstack4j.openstack.client.OSClientBuilder Maven / Gradle / Ivy

There is a newer version: 1.0.26
Show newest version
/*******************************************************************************
 * 	Copyright 2016 ContainX and OpenStack4j                                          
 * 	                                                                                 
 * 	Licensed under the Apache License, Version 2.0 (the "License"); you may not      
 * 	use this file except in compliance with the License. You may obtain a copy of    
 * 	the License at                                                                   
 * 	                                                                                 
 * 	    http://www.apache.org/licenses/LICENSE-2.0                                   
 * 	                                                                                 
 * 	Unless required by applicable law or agreed to in writing, software              
 * 	distributed under the License is distributed on an "AS IS" BASIS, WITHOUT        
 * 	WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the         
 * 	License for the specific language governing permissions and limitations under    
 * 	the License.                                                                     
 *******************************************************************************/
/******************************************************************************* 	                                                                                 
 *  Huawei has modified this source file.
 * 	Copyright 2018 Huawei Technologies Co.,Ltd.                                         
 * 	                                                                                 
 * 	Licensed under the Apache License, Version 2.0 (the "License"); you may not      
 * 	use this file except in compliance with the License. You may obtain a copy of    
 * 	the License at                                                                   
 * 	                                                                                 
 * 	    http://www.apache.org/licenses/LICENSE-2.0                                   
 * 	                                                                                 
 * 	Unless required by applicable law or agreed to in writing, software              
 * 	distributed under the License is distributed on an "AS IS" BASIS, WITHOUT        
 * 	WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the         
 * 	License for the specific language governing permissions and limitations under    
 * 	the License.                             
 * *******************************************************************************/
package com.huawei.openstack4j.openstack.client;

import static com.google.common.base.Preconditions.checkArgument;

import com.google.common.base.Strings;
import com.huawei.openstack4j.api.OSClient;
import com.huawei.openstack4j.api.OSClient.OSClientAKSK;
import com.huawei.openstack4j.api.OSClient.OSClientV2;
import com.huawei.openstack4j.api.OSClient.OSClientV3;
import com.huawei.openstack4j.api.ServiceEndpointProvider;
import com.huawei.openstack4j.api.client.CloudProvider;
import com.huawei.openstack4j.api.client.IOSClientBuilder;
import com.huawei.openstack4j.api.exceptions.ApiNotFoundException;
import com.huawei.openstack4j.api.exceptions.AuthenticationException;
import com.huawei.openstack4j.api.types.Facing;
import com.huawei.openstack4j.api.types.ServiceType;
import com.huawei.openstack4j.core.transport.Config;
import com.huawei.openstack4j.core.transport.HttpRequest;
import com.huawei.openstack4j.core.transport.HttpResponse;
import com.huawei.openstack4j.core.transport.internal.HttpExecutor;
import com.huawei.openstack4j.model.common.Identifier;
import com.huawei.openstack4j.model.identity.v3.Endpoint;
import com.huawei.openstack4j.model.identity.v3.Service;
import com.huawei.openstack4j.openstack.common.Auth;
import com.huawei.openstack4j.openstack.identity.v2.domain.Credentials;
import com.huawei.openstack4j.openstack.identity.v2.domain.RaxApiKeyCredentials;
import com.huawei.openstack4j.openstack.identity.v2.domain.TokenAuth;
import com.huawei.openstack4j.openstack.identity.v3.domain.KeystoneAuth;
import com.huawei.openstack4j.openstack.identity.v3.domain.KeystoneAuth.AuthScope;
import com.huawei.openstack4j.openstack.identity.v3.domain.KeystoneEndpoint;
import com.huawei.openstack4j.openstack.identity.v3.domain.KeystoneService;
import com.huawei.openstack4j.openstack.identity.v3.domain.KeystoneToken;
import com.huawei.openstack4j.openstack.internal.OSAuthenticator;
import com.huawei.openstack4j.openstack.internal.OSClientSessionAKSK;
import com.huawei.openstack4j.openstack.internal.OSClientSessionTempAKSK;
import com.huawei.openstack4j.openstack.internal.OSClientSessionV3;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * Builder definitions for creating a Client
 *
 * @author Jeremy Unruh
 *
 */
public abstract class OSClientBuilder> implements IOSClientBuilder {

    Config config;
    String endpoint;
    String user;
    String password;
    Facing perspective;
    CloudProvider provider = CloudProvider.UNKNOWN;

    @SuppressWarnings("unchecked")
    @Override
    public T withConfig(Config config) {
        this.config = config;
        return (T) this;
    }

    @SuppressWarnings("unchecked")
    @Override
    public T provider(CloudProvider provider) {
        this.provider = provider;
        return (T) this;
    }

    @SuppressWarnings("unchecked")
    @Override
    public T credentials(String user, String password) {
        this.user = user;
        this.password = password;
        return (T) this;
    }

    @SuppressWarnings("unchecked")
    @Override
    public T endpoint(String endpoint) {
        if(!endpoint.contains("/v3")){
            endpoint = endpoint+"/v3";
        }
        this.endpoint = endpoint;
        return (T) this;
    }

    @SuppressWarnings("unchecked")
    @Override
    public T perspective(Facing perspective) {
        this.perspective = perspective;
        return (T) this;
    }

    @SuppressWarnings("unchecked")
    @Override
    public T useNonStrictSSLClient(boolean useNonStrictSSL) {
        if (config == null)
            config = Config.newConfig().withSSLVerificationDisabled();
        return (T) this;
    }

    public static class ClientV2 extends OSClientBuilder implements IOSClientBuilder.V2 {

        String tenantName;
        String tenantId;
        String tokenId;
        boolean raxApiKey;

        @Override
        public ClientV2 tenantName(String tenantName) {
            this.tenantName = tenantName;
            return this;
        }

        @Override
        public ClientV2 tenantId(String tenantId) {
            this.tenantId = tenantId;
            return this;
        }

        @Override
        public ClientV2 raxApiKey(boolean raxApiKey) {
            this.raxApiKey = raxApiKey;
            return this;
        }

        @Override
        public OSClientV2 authenticate() throws AuthenticationException {
            if (tokenId != null) {
                checkArgument(tenantName != null || tenantId != null,
                        "TenantId or TenantName is required when using Token Auth");
                return (OSClientV2) OSAuthenticator.invoke(new TokenAuth(tokenId, tenantName, tenantId), endpoint, perspective,
                        config, provider);
            }

            if (raxApiKey) {
                return (OSClientV2) OSAuthenticator.invoke( new RaxApiKeyCredentials(user, password), endpoint, perspective, config, provider);
            }

            return (OSClientV2) OSAuthenticator.invoke( new Credentials(user, password, tenantName, tenantId), endpoint, perspective, config, provider);
        }

        @Override
        public ClientV2 token(String tokenId) {
            this.tokenId = tokenId;
            return this;
        }
        
    }

    public static class ClientV3 extends OSClientBuilder implements IOSClientBuilder.V3 {

        Identifier domain;
        AuthScope scope;
        String tokenId;
        String authToken;
        String language;

        @Override
        public ClientV3 domainName(String domainName) {
            this.domain = Identifier.byName(domainName);
            return this;
        }

        @Override
        public ClientV3 domainId(String domainId) {
            this.domain = Identifier.byId(domainId);
            return this;
        }

        @Override
        public ClientV3 credentials(String user, String password, Identifier domain) {
            this.user = user;
            this.password = password;
            this.domain = domain;
            return this;
        }

        @Override
        public ClientV3 token(String tokenId) {
            this.tokenId = tokenId;
            return this;
        }

        @Override
        public ClientV3 authToken(String authToken) {
            this.authToken = authToken;
            return this;
        }

        @Override
        public OSClientV3 authenticate() throws AuthenticationException {
            if (tokenId != null && tokenId.length() > 0)
                return (OSClientV3) OSAuthenticator.invoke(new KeystoneAuth(tokenId, scope), endpoint, perspective, config,
                        provider);
            if (authToken != null && authToken.length() > 0){
                List catalog = getKeystoneServices();
                KeystoneToken token = new KeystoneToken();
                token.setId(authToken);
                token.setCatalog(catalog);
                return OSClientSessionV3.createSession(token, perspective, provider, config);
            }
            if (user != null && user.length() > 0)
                return (OSClientV3) OSAuthenticator.invoke(new KeystoneAuth(user, password, domain, scope), endpoint, perspective,
                        config, provider);
            // Use tokenless auth finally
            return (OSClientV3) OSAuthenticator.invoke(new KeystoneAuth(scope, Auth.Type.TOKENLESS), endpoint, perspective,
                    config, provider);
        }

        private List getKeystoneServices() {
            String spath = null;
            String epath = null;
            if(endpoint.contains("/v3")){
                spath = "/services";
                epath = "/endpoints";
            }else{
                spath = "/v3/services";
                epath = "/v3/endpoints";
            }
            HttpResponse servicesRes = HttpExecutor.create().execute(HttpRequest.builder().endpoint(endpoint).path(spath).config(config)
                    .header("Content-Type","application/json;charset=utf8")
                    .header("X-Auth-Token",authToken).build());
            KeystoneService.Services services = servicesRes.getEntity(KeystoneService.Services.class);
            List serviceList = services.getList();
            HttpResponse endpointRes = HttpExecutor.create().execute(HttpRequest.builder().endpoint(endpoint).path(epath).config(config)
                    .header("Content-Type","application/json;charset=utf8")
                    .header("X-Auth-Token",authToken).build());
            KeystoneEndpoint.Endpoints endpoints = endpointRes.getEntity(KeystoneEndpoint.Endpoints.class);
            List endpointList = endpoints.getList();
            List catalog = new ArrayList<>();
            for(KeystoneService service : serviceList){
                for (KeystoneEndpoint endpoint : endpointList){
                    if(service.getId() ==null){
                        continue;
                    }
                    if(service.getId().equals(endpoint.getServiceId())){
                        if(!"PUBLIC".equalsIgnoreCase(endpoint.getIface().toString())){
                            continue;
                         }
                        if(endpoint.getRegion() == null){
                            service.setEndpoints(Arrays.asList(endpoint));
                            catalog.add(service);
                        }
                    }
                }
            }
            return catalog;
        }

        @Override
        public ClientV3 scopeToProject(Identifier project, Identifier domain) {
            this.scope = AuthScope.project(project, domain);
            return this;
        }

        @Override
        public ClientV3 scopeToProject(Identifier project) {
            this.scope = AuthScope.project(project);
            return this;
        }

        @Override
        public ClientV3 scopeToDomain(Identifier domain) {
            this.scope = AuthScope.domain(domain);
            return this;
        }

    }
    
    public static class ClientAKSK extends OSClientBuilder
	implements IOSClientBuilder.AKSK {

		private String accessKey;
		private String secretKey;
		private String cloudDomainName;
		private String projectId;
		private String region;
		private String domainId;

		/*
		 * {@inheritDoc}
		 */
		@Override
		public OSClientAKSK authenticate() throws AuthenticationException {
            OSClientAKSK session = null;

            if (!Strings.isNullOrEmpty(domainId)){
                session = new OSClientSessionAKSK().perspective(perspective).useConfig(config).credentials(accessKey, secretKey, region, projectId, domainId, cloudDomainName);
            }else if(!Strings.isNullOrEmpty(projectId)){
                session = new OSClientSessionAKSK().perspective(perspective).useConfig(config).credentials(accessKey, secretKey, region, projectId, cloudDomainName);
            }else {
                session = new OSClientSessionAKSK().perspective(perspective).useConfig(config).credentials(accessKey, secretKey, region, cloudDomainName);
            }
			return session;
		}
		
		/*
		 * {@inheritDoc}
		 */
		@Override
		public com.huawei.openstack4j.api.client.IOSClientBuilder.AKSK credentials(String accessKey, String secretKey,
				String region, String projectId, String cloudDomainName) {
			
			checkArgument(!Strings.isNullOrEmpty(accessKey),"parameter `accessKey` should not be empty");
			checkArgument(!Strings.isNullOrEmpty(secretKey),"parameter `secretKey` should not be empty");
			checkArgument(!Strings.isNullOrEmpty(region),"parameter `region` should not be empty");
			checkArgument(!Strings.isNullOrEmpty(projectId),"parameter `projectId` should not be empty");
			checkArgument(!Strings.isNullOrEmpty(cloudDomainName),"parameter `cloudDomainName` should not be empty");
			
			this.accessKey = accessKey;
			this.secretKey = secretKey;
			this.cloudDomainName = cloudDomainName;
			this.projectId = projectId;
			this.region = region;
			return this;
		}

        /*
         * {@inheritDoc}
         */
        @Override
        public com.huawei.openstack4j.api.client.IOSClientBuilder.AKSK credentials(String accessKey, String secretKey,
                                                                                   String region, String cloudDomainName) {

            checkArgument(!Strings.isNullOrEmpty(accessKey),"parameter `accessKey` should not be empty");
            checkArgument(!Strings.isNullOrEmpty(secretKey),"parameter `secretKey` should not be empty");
            checkArgument(!Strings.isNullOrEmpty(region),"parameter `region` should not be empty");
            checkArgument(!Strings.isNullOrEmpty(cloudDomainName),"parameter `cloudDomainName` should not be empty");

            this.accessKey = accessKey;
            this.secretKey = secretKey;
            this.cloudDomainName = cloudDomainName;
            this.region = region;
            return this;
        }

        /*
         * {@inheritDoc}
         */
        @Override
        public com.huawei.openstack4j.api.client.IOSClientBuilder.AKSK credentials(String accessKey, String secretKey,
                                                                                   String region, String projectId, String domainId,String cloudDomainName) {

            checkArgument(!Strings.isNullOrEmpty(accessKey),"parameter `accessKey` should not be empty");
            checkArgument(!Strings.isNullOrEmpty(secretKey),"parameter `secretKey` should not be empty");
//            checkArgument(!Strings.isNullOrEmpty(region),"parameter `region` should not be empty");
            checkArgument(!Strings.isNullOrEmpty(cloudDomainName),"parameter `domain` should not be empty");
            checkArgument(!Strings.isNullOrEmpty(domainId),"parameter `domainId` should not be empty");

            this.accessKey = accessKey;
            this.secretKey = secretKey;
            this.cloudDomainName = cloudDomainName;
            this.region = region;
            this.domainId = domainId;
            this.projectId = projectId;
            return this;
        }
		//TODO add more quick build method later?
		}

    public static class ClientTempAKSK extends OSClientBuilder
            implements IOSClientBuilder.TempAKSK {

        private String accessKey;
        private String secretKey;
        private String cloudDomainName;
        private String projectId;
        private String region;
        private String domainId;
        private String securityToken;

        /*
         * {@inheritDoc}
         */
        @Override
        public OSClient.OSClientTempAKSK authenticate() throws AuthenticationException {
            OSClient.OSClientTempAKSK session = null;

            if (!Strings.isNullOrEmpty(domainId)){
                session = new OSClientSessionTempAKSK().credentials(accessKey, secretKey, region, projectId, domainId, cloudDomainName, securityToken)
                        .perspective(perspective).useConfig(config);
            }else if(!Strings.isNullOrEmpty(projectId)){
                session = new OSClientSessionTempAKSK().credentials(accessKey, secretKey, region, projectId, cloudDomainName, securityToken)
                        .perspective(perspective).useConfig(config);
            }else {
                session = new OSClientSessionTempAKSK().credentials(accessKey, secretKey, region, cloudDomainName, securityToken)
                        .perspective(perspective).useConfig(config);
            }
            return session;
        }

        /*
         * {@inheritDoc}
         */
        @Override
        public com.huawei.openstack4j.api.client.IOSClientBuilder.TempAKSK credentials(String accessKey, String secretKey,
                                                                                   String region, String projectId, String cloudDomainName,String securityToken) {

            checkArgument(!Strings.isNullOrEmpty(accessKey),"parameter `accessKey` should not be empty");
            checkArgument(!Strings.isNullOrEmpty(secretKey),"parameter `secretKey` should not be empty");
            checkArgument(!Strings.isNullOrEmpty(region),"parameter `region` should not be empty");
            checkArgument(!Strings.isNullOrEmpty(projectId),"parameter `projectId` should not be empty");
            checkArgument(!Strings.isNullOrEmpty(cloudDomainName),"parameter `cloudDomainName` should not be empty");
            checkArgument(!Strings.isNullOrEmpty(securityToken),"parameter `securityToken` should not be empty");
            this.accessKey = accessKey;
            this.secretKey = secretKey;
            this.cloudDomainName = cloudDomainName;
            this.projectId = projectId;
            this.region = region;
            this.securityToken = securityToken;
            return this;
        }

        /*
         * {@inheritDoc}
         */
        @Override
        public com.huawei.openstack4j.api.client.IOSClientBuilder.TempAKSK credentials(String accessKey, String secretKey,
                                                                                   String region, String cloudDomainName, String securityToken) {

            checkArgument(!Strings.isNullOrEmpty(accessKey),"parameter `accessKey` should not be empty");
            checkArgument(!Strings.isNullOrEmpty(secretKey),"parameter `secretKey` should not be empty");
            checkArgument(!Strings.isNullOrEmpty(region),"parameter `region` should not be empty");
            checkArgument(!Strings.isNullOrEmpty(cloudDomainName),"parameter `cloudDomainName` should not be empty");
            checkArgument(!Strings.isNullOrEmpty(securityToken),"parameter `securityToken` should not be empty");

            this.accessKey = accessKey;
            this.secretKey = secretKey;
            this.cloudDomainName = cloudDomainName;
            this.region = region;
            this.securityToken = securityToken;
            return this;
        }

        /*
         * {@inheritDoc}
         */
        @Override
        public com.huawei.openstack4j.api.client.IOSClientBuilder.TempAKSK credentials(String accessKey, String secretKey,
                                                                                   String region, String projectId, String domainId,String cloudDomainName, String securityToken) {

            checkArgument(!Strings.isNullOrEmpty(accessKey),"parameter `accessKey` should not be empty");
            checkArgument(!Strings.isNullOrEmpty(secretKey),"parameter `secretKey` should not be empty");
            checkArgument(!Strings.isNullOrEmpty(region),"parameter `region` should not be empty");
            checkArgument(!Strings.isNullOrEmpty(cloudDomainName),"parameter `domain` should not be empty");
            checkArgument(!Strings.isNullOrEmpty(domainId),"parameter `domainId` should not be empty");
            checkArgument(!Strings.isNullOrEmpty(securityToken),"parameter `securityToken` should not be empty");

            this.accessKey = accessKey;
            this.secretKey = secretKey;
            this.cloudDomainName = cloudDomainName;
            this.region = region;
            this.domainId = domainId;
            this.projectId = projectId;
            this.securityToken = securityToken;
            return this;
        }
        //TODO add more quick build method later?
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy