Complete Identity Server create/delete/update APIs

merge-requests/849/head
Mohamed Rashd 3 years ago
parent 3f60a0cdda
commit c58f837585

@ -1,35 +0,0 @@
/*
* Copyright (c) 2022, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you 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 io.entgra.application.mgt.common;
import io.entgra.application.mgt.common.dto.IdentityServerDTO;
import java.util.List;
public class IdentityServerList {
private List<IdentityServerDTO> identityServers;
public List<IdentityServerDTO> getIdentityServers() {
return identityServers;
}
public void setIdentityServers(List<IdentityServerDTO> identityServers) {
this.identityServers = identityServers;
}
}

@ -18,16 +18,20 @@
package io.entgra.application.mgt.common;
public class IdentityServer {
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
public class IdentityServerResponse {
private int id;
private String providerName;
private String name;
private String description;
private String url;
private String apiUrl;
private String serviceProviderAppsUrl;
private String userName;
private String password;
private String username;
private List<Map<String, String>> apiParamList;
public int getId() {
return id;
@ -61,20 +65,12 @@ public class IdentityServer {
this.url = url;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
public String getUsername() {
return username;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
public void setUsername(String username) {
this.username = username;
}
public String getProviderName() {
@ -85,14 +81,6 @@ public class IdentityServer {
this.providerName = providerName;
}
public String getApiUrl() {
return apiUrl;
}
public void setApiUrl(String apiUrl) {
this.apiUrl = apiUrl;
}
public String getServiceProviderAppsUrl() {
return serviceProviderAppsUrl;
}
@ -100,4 +88,16 @@ public class IdentityServer {
public void setServiceProviderAppsUrl(String serviceProviderAppsUrl) {
this.serviceProviderAppsUrl = serviceProviderAppsUrl;
}
public List<Map<String, String>> getApiParamList() {
return apiParamList;
}
public void setApiParamList(Map<String, String> apiParams) {
this.apiParamList = apiParams.entrySet().stream().map(param -> {
Map<String, String> paramMap = new HashMap<>();
paramMap.put(param.getKey(), param.getValue());
return paramMap;
}).collect(Collectors.toList());
}
}

@ -18,15 +18,26 @@
package io.entgra.application.mgt.common.dto;
import com.google.gson.Gson;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
public class IdentityServerDTO {
private int id;
private String providerName;
private String name;
private String description;
private String url;
private String apiUrl;
private String userName;
private String username;
private String password;
private Map<String, String> apiParams;
public IdentityServerDTO() {
this.apiParams = new HashMap<>();
}
public int getId() {
return id;
@ -68,12 +79,12 @@ public class IdentityServerDTO {
this.password = password;
}
public String getUserName() {
return userName;
public String getUsername() {
return username;
}
public void setUserName(String userName) {
this.userName = userName;
public void setUsername(String username) {
this.username = username;
}
public String getProviderName() {
@ -84,11 +95,19 @@ public class IdentityServerDTO {
this.providerName = providerName;
}
public String getApiUrl() {
return apiUrl;
public String constructApiParamsJsonString() {
return new Gson().toJson(apiParams);
}
public Set<String> getApiParamKeys() {
return apiParams.keySet();
}
public Map<String, String> getApiParams() {
return apiParams;
}
public void setApiUrl(String apiUrl) {
this.apiUrl = apiUrl;
public void setApiParams(Map<String, String> apiParams) {
this.apiParams = apiParams;
}
}

@ -0,0 +1,24 @@
package io.entgra.application.mgt.common.dto;
import java.util.List;
public class IdentityServiceProviderDTO {
private String name;
private List<String> requiredApiParams;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<String> getRequiredApiParams() {
return requiredApiParams;
}
public void setRequiredApiParams(List<String> requiredApiParams) {
this.requiredApiParams = requiredApiParams;
}
}

@ -0,0 +1,28 @@
/* Copyright (c) 2022, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
*
* Entgra (Pvt) Ltd. licenses this file to you 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 io.entgra.application.mgt.common.exception;
/**
* Exception that will be thrown if any error occurs while calling identity server services .
*/
public class IdentityServerManagementException extends ApplicationManagementException {
public IdentityServerManagementException(String message) {
super(message);
setMessage(message);
}
}

@ -18,9 +18,10 @@
package io.entgra.application.mgt.common.services;
import io.entgra.application.mgt.common.IdentityServer;
import io.entgra.application.mgt.common.IdentityServerResponse;
import io.entgra.application.mgt.common.SPApplicationListResponse;
import io.entgra.application.mgt.common.dto.IdentityServerDTO;
import io.entgra.application.mgt.common.SPApplication;
import io.entgra.application.mgt.common.dto.IdentityServiceProviderDTO;
import io.entgra.application.mgt.common.exception.ApplicationManagementException;
import io.entgra.application.mgt.common.exception.RequestValidatingException;
import io.entgra.application.mgt.common.response.Application;
@ -28,15 +29,6 @@ import java.util.List;
public interface SPApplicationManager {
/**
* This method adds existing consumer applications of service providers to the SPApplication bean
*
* @param identityServerId identity server id of the service provider
* @param applications Service providers list to which the existing applications should be added
* @throws ApplicationManagementException if error occurred while adding existing applications
*/
void addExistingApps(int identityServerId, List<SPApplication> applications) throws ApplicationManagementException;
/**
* Removes consumer application from service provider
*
@ -63,16 +55,65 @@ public interface SPApplicationManager {
* @return Identity server for the given ID
* @throws ApplicationManagementException if error occurred while getting identity server
*/
IdentityServer getIdentityServer(int identityServerId) throws ApplicationManagementException;
IdentityServerResponse getIdentityServerResponse(int identityServerId) throws ApplicationManagementException;
/**
*
* @return Available identity servers
* @throws ApplicationManagementException if error occurred while getting identity servers
*/
List<IdentityServer> getIdentityServers() throws ApplicationManagementException;
List<IdentityServerResponse> getIdentityServers() throws ApplicationManagementException;
/**
* Create a new Identity Server
*
* @return {@link IdentityServerResponse}
* @throws ApplicationManagementException if error occurred while getting identity servers
*/
IdentityServerResponse createIdentityServer(IdentityServerDTO identityServerDTO) throws ApplicationManagementException;
/**
* Update existing Identity Server
*
* @param id of the identity server to be updated
* @param updateIdentityServerDTO identity server dto bean with updated fields
* @throws ApplicationManagementException if error occurred while getting identity servers
*/
IdentityServerResponse updateIdentityServer(IdentityServerDTO updateIdentityServerDTO, int id) throws ApplicationManagementException;
/**
* Delete Identity Server
*
* @param id of the identity server to be deleted
* @throws ApplicationManagementException if error occurred while getting identity servers
*/
void deleteIdentityServer(int id) throws ApplicationManagementException;
IdentityServer createIdentityServer(IdentityServerDTO identityServerDTO) throws ApplicationManagementException;
/**
* Check if Identity Server exists with the same name
*
* @param name of the identity server
* @return if name already exists for identity server
*/
boolean isIdentityServerNameExist(String name) throws ApplicationManagementException;
/**
* Check if Identity Server exists with the same url
*
* @param url of the identity server
* @return if url already exists for identity server
*/
boolean isIdentityServerUrlExist(String url) throws ApplicationManagementException;
/**
* Retrieve service provider apps from identity server
*
* @param identityServerId Id of the identity server
* @return {@link SPApplicationListResponse}
* @throws ApplicationManagementException if error while retrieving sp applications
*/
SPApplicationListResponse retrieveSPApplicationFromIdentityServer(int identityServerId, Integer offset, Integer limit)
throws ApplicationManagementException;
/**
*
@ -101,9 +142,9 @@ public interface SPApplicationManager {
* Validates application ids of the applications that should be attached
*
* @param appIds application ids to be validated
* @throws ApplicationManagementException
* @throws ApplicationManagementException if invalid service provider, identity server Id or app Ids provided
*/
void validateAttachAppsRequest(int identityServerId, List<Integer> appIds) throws ApplicationManagementException;
void validateAttachAppsRequest(int identityServerId, String serviceProviderId, List<Integer> appIds) throws ApplicationManagementException;
/**
* Validates application ids of the applications that should be detached
@ -115,4 +156,10 @@ public interface SPApplicationManager {
*/
void validateDetachAppsRequest(int identityServerId, String spId, List<Integer> appIds) throws ApplicationManagementException;
/**
* Get available identity service providers
*
* @return list of available service providers' names
*/
List<IdentityServiceProviderDTO> getIdentityServiceProviders() throws ApplicationManagementException;
}

@ -90,6 +90,7 @@
!io.entgra.application.mgt.core.internal.*,
io.entgra.application.mgt.core.*
</Export-Package>
<DynamicImport-Package>*</DynamicImport-Package>
</instructions>
</configuration>
</plugin>

@ -36,7 +36,7 @@ public class ConfigurationManager {
private Configuration configuration;
private IdentityServerConfiguration identityServerConfiguration;
private IdentityServiceProviderConfiguration identityServiceProviderConfiguration;
private static String configPath;
@ -58,6 +58,12 @@ public class ConfigurationManager {
} catch (ApplicationManagementException e) {
log.error(e);
}
} else {
try {
configurationManager.initConfig();
} catch (ApplicationManagementException e) {
log.error(e);
}
}
}
}
@ -83,14 +89,18 @@ public class ConfigurationManager {
private void initConfig() throws ApplicationManagementException {
try {
JAXBContext jaxbContext = JAXBContext.newInstance(Configuration.class);
JAXBContext jaxbISConfigContext = JAXBContext.newInstance(IdentityServiceProviderConfiguration.class);
Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
Unmarshaller identityServerConfigUnmarshaller = jaxbISConfigContext.createUnmarshaller();
if (configPath == null) {
configPath = Constants.DEFAULT_CONFIG_FILE_LOCATION;
}
if (identityServerConfigPath == null) {
identityServerConfigPath = Constants.DEFAULT_IDENTITY_SERVERS_CONFIG_FILE_LOCATION;
}
//TODO: Add validation for the configurations
this.configuration = (Configuration) unmarshaller.unmarshal(new File(configPath));
this.identityServerConfiguration = (IdentityServerConfiguration) unmarshaller.unmarshal(new File(identityServerConfigPath));
this.identityServiceProviderConfiguration = (IdentityServiceProviderConfiguration) identityServerConfigUnmarshaller.unmarshal(new File(identityServerConfigPath));
} catch (Exception e) {
log.error(e);
throw new InvalidConfigurationException("Error occurred while initializing application config: "
@ -102,8 +112,8 @@ public class ConfigurationManager {
return configuration;
}
public IdentityServerConfiguration getIdentityServerConfiguration() {
return identityServerConfiguration;
public IdentityServiceProviderConfiguration getIdentityServerConfiguration() {
return identityServiceProviderConfiguration;
}
public Extension getExtension(Extension.Name extName) throws InvalidConfigurationException {

@ -1,37 +1,38 @@
package io.entgra.application.mgt.core.config;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
public class IdentityServerDetail {
@XmlRootElement(name = "IdentityServiceProvider")
public class IdentityServiceProvider {
private String providerName;
private String providerClassName;
private String serviceProvidersPageUri;
private String serviceProvidersAPIContextPath;
@XmlAttribute(name = "ProviderName")
@XmlElement(name = "ProviderName")
public String getProviderName() {
return providerName;
}
public void setProviderName(String providerName) {
this.providerName = providerName;
@XmlElement(name = "ProviderClassName")
public String getProviderClassName() {
return providerClassName;
}
@XmlAttribute(name = "ServiceProvidersPageUri")
@XmlElement(name = "ServiceProvidersPageUri")
public String getServiceProvidersPageUri() {
return serviceProvidersPageUri;
}
public void setServiceProvidersPageUri(String serviceProvidersPageUri) {
this.serviceProvidersPageUri = serviceProvidersPageUri;
public void setProviderName(String providerName) {
this.providerName = providerName;
}
@XmlAttribute(name = "ServiceProvidersAPIContextPath")
public String getServiceProvidersAPIContextPath() {
return serviceProvidersAPIContextPath;
public void setServiceProvidersPageUri(String serviceProvidersPageUri) {
this.serviceProvidersPageUri = serviceProvidersPageUri;
}
public void setServiceProvidersAPIContextPath(String serviceProvidersAPIContextPath) {
this.serviceProvidersAPIContextPath = serviceProvidersAPIContextPath;
public void setProviderClassName(String providerClassName) {
this.providerClassName = providerClassName;
}
}

@ -25,28 +25,28 @@ import java.util.List;
/**
* Represents the Application Management Configuration.
*/
@XmlRootElement(name = "IdentityServerConfiguration")
public class IdentityServerConfiguration {
@XmlRootElement(name = "IdentityServiceProviderConfiguration")
public class IdentityServiceProviderConfiguration {
private List<IdentityServerDetail> identityServers;
private List<IdentityServiceProvider> identityServiceProviders;
@XmlElementWrapper(name = "IdentityServers")
@XmlElement(name = "IdentityServerDTO")
public List<IdentityServerDetail> getIdentityServers() {
return identityServers;
@XmlElementWrapper(name = "IdentityServiceProviders")
@XmlElement(name = "IdentityServiceProvider")
public List<IdentityServiceProvider> getIdentityServiceProviders() {
return identityServiceProviders;
}
public IdentityServerDetail getIdentityServerDetailByProviderName(String identityServerProviderName) {
for (IdentityServerDetail identityServerDetail : identityServers) {
if (identityServerDetail.getProviderName().equals(identityServerProviderName)) {
return identityServerDetail;
public IdentityServiceProvider getIdentityServerDetailByProviderName(String identityServiceProviderName) {
for (IdentityServiceProvider identityServiceProvider : identityServiceProviders) {
if (identityServiceProvider.getProviderName().equals(identityServiceProviderName)) {
return identityServiceProvider;
}
}
return null;
}
public void setIdentityServers(List<IdentityServerDetail> identityServers) {
this.identityServers = identityServers;
public void setIdentityServiceProviders(List<IdentityServiceProvider> identityServiceProviders) {
this.identityServiceProviders = identityServiceProviders;
}
}

@ -26,6 +26,36 @@ import java.util.List;
public interface SPApplicationDAO {
/**
* Use to check if an identity server exists with the same name
*
* @param name name of the identity server
* @return if identity server with the given name exists
*/
boolean isExistingIdentityServerName(String name, int tenantId) throws ApplicationManagementDAOException;
/**
* Use to check if an identity server exists with the same url
*
* @param url name of the identity server
* @return if identity server with the given url exists
*/
boolean isExistingIdentityServerUrl(String url, int tenantId) throws ApplicationManagementDAOException;
/**
* Update existing identity server in the database
*
* @param updatedIdentityServerDTO bean with the updated fields of the identity server
*/
void updateIdentityServer(IdentityServerDTO updatedIdentityServerDTO, int tenantId, int identityServerId)
throws ApplicationManagementDAOException;
/**
* Create new identity server in the database
*
* @param identityServerDTO DTO bean with the details of identity server to be created
* @return id of the newly created identity server
*/
int createIdentityServer(IdentityServerDTO identityServerDTO, int tenantId) throws ApplicationManagementDAOException;
/**
@ -91,4 +121,11 @@ public interface SPApplicationDAO {
*/
void deleteApplicationFromServiceProviders(int applicationId, int tenantId) throws ApplicationManagementDAOException;
/**
* Delete identity server from db
*
* @param id of the identity server to be deleted
* @throws ApplicationManagementDAOException if any db error occurred
*/
void deleteIdentityServer(int id, int tenantId) throws ApplicationManagementDAOException;
}

@ -29,6 +29,7 @@ import io.entgra.application.mgt.core.exception.UnexpectedServerErrorException;
import io.entgra.application.mgt.core.util.DAOUtil;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
@ -41,7 +42,7 @@ public class GenericSPApplicationDAOImpl extends AbstractDAOImpl implements SPAp
private static final Log log = LogFactory.getLog(GenericApplicationDAOImpl.class);
@Override
public List<IdentityServerDTO> getIdentityServers(int tenantId) throws ApplicationManagementDAOException {
String sql = "SELECT ID, PROVIDER_NAME, NAME, DESCRIPTION, URL, API_URL, USERNAME, PASSWORD, TENANT_ID "
String sql = "SELECT ID, PROVIDER_NAME, NAME, DESCRIPTION, URL, API_PARAMS, USERNAME, PASSWORD, TENANT_ID "
+ "FROM AP_IDENTITY_SERVER "
+ "WHERE TENANT_ID = ?";
try {
@ -68,7 +69,7 @@ public class GenericSPApplicationDAOImpl extends AbstractDAOImpl implements SPAp
@Override
public IdentityServerDTO getIdentityServerById(int id, int tenantId) throws ApplicationManagementDAOException {
String sql = "SELECT ID, PROVIDER_NAME, NAME, DESCRIPTION, URL, API_URL, USERNAME, PASSWORD, TENANT_ID "
String sql = "SELECT ID, PROVIDER_NAME, NAME, DESCRIPTION, URL, API_PARAMS, USERNAME, PASSWORD, TENANT_ID "
+ "FROM AP_IDENTITY_SERVER "
+ "WHERE TENANT_ID = ? AND "
+ "ID = ?";
@ -99,16 +100,136 @@ public class GenericSPApplicationDAOImpl extends AbstractDAOImpl implements SPAp
}
}
@Override
public boolean isExistingIdentityServerName(String name, int tenantId) throws ApplicationManagementDAOException {
String sql = "SELECT ID AS ID "
+ "FROM AP_IDENTITY_SERVER "
+ "WHERE "
+ "LOWER(NAME) = LOWER(?) AND "
+ "TENANT_ID = ?";
try {
Connection conn = this.getDBConnection();
try (PreparedStatement stmt = conn.prepareStatement(sql)){
stmt.setString(1, name);
stmt.setInt(2, tenantId);
try (ResultSet rs = stmt.executeQuery()){
return rs.next();
}
}
} catch (DBConnectionException e) {
String msg = "Error occurred while obtaining the DB connection to check if identity server name: " + name +
" already exist";
log.error(msg, e);
throw new ApplicationManagementDAOException(msg, e);
} catch (SQLException e) {
String msg = "Error occurred while executing query to check if identity server with the name " + name +
" already exists.";
log.error(msg, e);
throw new ApplicationManagementDAOException(msg, e);
}
}
@Override
public boolean isExistingIdentityServerUrl(String url, int tenantId) throws ApplicationManagementDAOException {
String sql = "SELECT ID AS ID "
+ "FROM AP_IDENTITY_SERVER "
+ "WHERE "
+ "LOWER(URL) = LOWER(?) AND "
+ "TENANT_ID = ?";
try {
Connection conn = this.getDBConnection();
try (PreparedStatement stmt = conn.prepareStatement(sql)){
stmt.setString(1, url);
stmt.setInt(2, tenantId);
try (ResultSet rs = stmt.executeQuery()){
return rs.next();
}
}
} catch (DBConnectionException e) {
String msg = "Error occurred while obtaining the DB connection to check if identity server url: " + url +
" already exist";
log.error(msg, e);
throw new ApplicationManagementDAOException(msg, e);
} catch (SQLException e) {
String msg = "Error occurred while executing query to check if identity server with the url " + url +
" already exists.";
log.error(msg, e);
throw new ApplicationManagementDAOException(msg, e);
}
}
@Override
public void updateIdentityServer(IdentityServerDTO updatedIdentityServerDTO, int tenantId, int identityServerId)
throws ApplicationManagementDAOException {
String sql = "UPDATE AP_IDENTITY_SERVER " +
"SET ";
if (updatedIdentityServerDTO.getName() != null) {
sql += "NAME = ?, ";
}
if (updatedIdentityServerDTO.getUrl() != null) {
sql += "URL = ?, ";
}
if (updatedIdentityServerDTO.getProviderName() != null) {
sql += "PROVIDER_NAME = ?, ";
}
if (updatedIdentityServerDTO.getUsername() != null) {
sql += "USERNAME = ?, ";
}
if (updatedIdentityServerDTO.getPassword() != null) {
sql += "PASSWORD = ?, ";
}
if (updatedIdentityServerDTO.getDescription() != null) {
sql += "DESCRIPTION = ?, ";
}
sql += "API_PARAMS = ? " +
"WHERE ID = ? AND TENANT_ID = ?";
try {
int index = 1;
Connection conn = this.getDBConnection();
try (PreparedStatement stmt = conn.prepareStatement(sql)) {
if (updatedIdentityServerDTO.getName() != null) {
stmt.setString(index++, updatedIdentityServerDTO.getName());
}
if (updatedIdentityServerDTO.getUrl() != null) {
stmt.setString(index++, updatedIdentityServerDTO.getUrl());
}
if (updatedIdentityServerDTO.getProviderName() != null) {
stmt.setString(index++, updatedIdentityServerDTO.getProviderName());
}
if (updatedIdentityServerDTO.getUsername() != null) {
stmt.setString(index++, updatedIdentityServerDTO.getUsername());
}
if (updatedIdentityServerDTO.getPassword() != null) {
stmt.setString(index++, updatedIdentityServerDTO.getPassword());
}
if (updatedIdentityServerDTO.getDescription() != null) {
stmt.setString(index++, updatedIdentityServerDTO.getDescription());
}
stmt.setString(index++, updatedIdentityServerDTO.constructApiParamsJsonString());
stmt.setInt(index++, identityServerId);
stmt.setInt(index, tenantId);
stmt.executeUpdate();
}
} catch (DBConnectionException e) {
String msg = "Error occurred while obtaining the DB connection to update identity server.";
log.error(msg, e);
throw new ApplicationManagementDAOException(msg, e);
} catch (SQLException e) {
String msg = "Error occurred when executing SQL to update identity server. Executed query: " + sql;
log.error(msg, e);
throw new ApplicationManagementDAOException(msg, e);
}
}
@Override
public int createIdentityServer(IdentityServerDTO identityServerDTO, int tenantId) throws ApplicationManagementDAOException {
if (log.isDebugEnabled()) {
log.debug("Request received in DAO Layer to create an identity server");
}
String sql = "INSERT INTO AP_IDENTITY_SERVER "
+ "(PROVIDER_NAME, "
+ "NAME, "
+ "DESCRIPTION, URL, API_URL, USERNAME, PASSWORD, TENANT_ID) "
+ "VALUES (?, ?, ?, ?)";
+ "(PROVIDER_NAME, NAME, DESCRIPTION, URL, API_PARAMS, USERNAME, PASSWORD, TENANT_ID) "
+ "VALUES (?, ?, ?, ?, ?, ?, ?, ?)";
try {
Connection conn = this.getDBConnection();
try (PreparedStatement stmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS)) {
@ -116,8 +237,8 @@ public class GenericSPApplicationDAOImpl extends AbstractDAOImpl implements SPAp
stmt.setString(2, identityServerDTO.getName());
stmt.setString(3, identityServerDTO.getDescription());
stmt.setString(4, identityServerDTO.getUrl());
stmt.setString(5, identityServerDTO.getApiUrl());
stmt.setString(6, identityServerDTO.getUserName());
stmt.setString(5, identityServerDTO.constructApiParamsJsonString());
stmt.setString(6, identityServerDTO.getUsername());
stmt.setString(7, identityServerDTO.getPassword());
stmt.setInt(8, tenantId);
stmt.executeUpdate();
@ -338,4 +459,29 @@ public class GenericSPApplicationDAOImpl extends AbstractDAOImpl implements SPAp
}
}
@Override
public void deleteIdentityServer(int id, int tenantId) throws ApplicationManagementDAOException {
if (log.isDebugEnabled()) {
log.debug("Request received in DAO Layer to delete identity server with the id: " + id);
}
String sql = "DELETE FROM AP_IDENTITY_SERVER WHERE ID = ? AND TENANT_ID = ?";
try {
Connection conn = this.getDBConnection();
try (PreparedStatement stmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS)) {
stmt.setInt(1, id);
stmt.setInt(2, tenantId);
stmt.executeUpdate();
}
} catch (DBConnectionException e) {
String msg = "Error occurred while obtaining the DB connection to delete an identity server with the id " + id;
log.error(msg, e);
throw new ApplicationManagementDAOException(msg, e);
} catch (SQLException e) {
String msg = "Error occurred while executing SQL to delete an identity server which has the id "
+ id;
log.error(msg, e);
throw new ApplicationManagementDAOException(msg, e);
}
}
}

@ -41,7 +41,7 @@ public class OracleSPApplicationDAOImpl extends AbstractDAOImpl implements SPAp
@Override
public List<IdentityServerDTO> getIdentityServers(int tenantId) throws ApplicationManagementDAOException {
String sql = "SELECT ID, PROVIDER_NAME, NAME, DESCRIPTION, URL, API_URL, USERNAME, PASSWORD, TENANT_ID "
String sql = "SELECT ID, PROVIDER_NAME, NAME, DESCRIPTION, URL, API_PARAMS, USERNAME, PASSWORD, TENANT_ID "
+ "FROM AP_IDENTITY_SERVER "
+ "WHERE TENANT_ID = ?";
try {
@ -68,7 +68,7 @@ public class OracleSPApplicationDAOImpl extends AbstractDAOImpl implements SPAp
@Override
public IdentityServerDTO getIdentityServerById(int id, int tenantId) throws ApplicationManagementDAOException {
String sql = "SELECT ID, PROVIDER_NAME, NAME, DESCRIPTION, URL, API_URL, USERNAME, PASSWORD, TENANT_ID "
String sql = "SELECT ID, PROVIDER_NAME, NAME, DESCRIPTION, URL, API_PARAMS, USERNAME, PASSWORD, TENANT_ID "
+ "FROM AP_IDENTITY_SERVER "
+ "WHERE TENANT_ID = ? AND "
+ "ID = ?";
@ -99,6 +99,128 @@ public class OracleSPApplicationDAOImpl extends AbstractDAOImpl implements SPAp
}
}
@Override
public boolean isExistingIdentityServerUrl(String url, int tenantId) throws ApplicationManagementDAOException {
String sql = "SELECT AP_APP.ID AS ID "
+ "FROM AP_IDENTITY_SERVER "
+ "WHERE "
+ "LOWER(URL) = LOWER(?) AND "
+ "AP_APP.TENANT_ID = ?";
try {
Connection conn = this.getDBConnection();
try (PreparedStatement stmt = conn.prepareStatement(sql)){
stmt.setString(1, url);
stmt.setInt(2, tenantId);
try (ResultSet rs = stmt.executeQuery()){
return rs.next();
}
}
} catch (DBConnectionException e) {
String msg = "Error occurred while obtaining the DB connection to check if identity server url: " + url +
" already exist";
log.error(msg, e);
throw new ApplicationManagementDAOException(msg, e);
} catch (SQLException e) {
String msg = "Error occurred while executing query to check if identity server with the url " + url +
" already exists.";
log.error(msg, e);
throw new ApplicationManagementDAOException(msg, e);
}
}
@Override
public boolean isExistingIdentityServerName(String name, int tenantId) throws ApplicationManagementDAOException {
String sql = "SELECT AP_APP.ID AS ID "
+ "FROM AP_IDENTITY_SERVER "
+ "WHERE "
+ "LOWER(NAME) = LOWER(?) AND "
+ "AP_APP.TENANT_ID = ?";
try {
Connection conn = this.getDBConnection();
try (PreparedStatement stmt = conn.prepareStatement(sql)){
stmt.setString(1, name);
stmt.setInt(2, tenantId);
try (ResultSet rs = stmt.executeQuery()){
return rs.next();
}
}
} catch (DBConnectionException e) {
String msg = "Error occurred while obtaining the DB connection to check if identity server name: " + name +
" already exist";
log.error(msg, e);
throw new ApplicationManagementDAOException(msg, e);
} catch (SQLException e) {
String msg = "Error occurred while executing query to check if identity server with the name " + name +
" already exists.";
log.error(msg, e);
throw new ApplicationManagementDAOException(msg, e);
}
}
@Override
public void updateIdentityServer(IdentityServerDTO updatedIdentityServerDTO, int tenantId, int identityServerId)
throws ApplicationManagementDAOException {
String sql = "UPDATE AP_IDENTITY_SERVER " +
"SET ";
if (updatedIdentityServerDTO.getName() != null) {
sql += "NAME = ?, ";
}
if (updatedIdentityServerDTO.getUrl() != null) {
sql += "URL = ?, ";
}
if (updatedIdentityServerDTO.getProviderName() != null) {
sql += "PROVIDER_NAME = ?, ";
}
if (updatedIdentityServerDTO.getUsername() != null) {
sql += "USERNAME = ?, ";
}
if (updatedIdentityServerDTO.getPassword() != null) {
sql += "PASSWORD = ?, ";
}
if (updatedIdentityServerDTO.getDescription() != null) {
sql += "DESCRIPTION = ?, ";
}
sql += "API_PARAMS = ? " +
"WHERE ID = ? AND TENANT_ID = ?";
try {
int index = 1;
Connection conn = this.getDBConnection();
try (PreparedStatement stmt = conn.prepareStatement(sql)) {
if (updatedIdentityServerDTO.getName() != null) {
stmt.setString(index++, updatedIdentityServerDTO.getName());
}
if (updatedIdentityServerDTO.getUrl() != null) {
stmt.setString(index++, updatedIdentityServerDTO.getUrl());
}
if (updatedIdentityServerDTO.getProviderName() != null) {
stmt.setString(index++, updatedIdentityServerDTO.getProviderName());
}
if (updatedIdentityServerDTO.getUsername() != null) {
stmt.setString(index++, updatedIdentityServerDTO.getUsername());
}
if (updatedIdentityServerDTO.getPassword() != null) {
stmt.setString(index++, updatedIdentityServerDTO.getPassword());
}
if (updatedIdentityServerDTO.getDescription() != null) {
stmt.setString(index++, updatedIdentityServerDTO.getDescription());
}
stmt.setString(index++, updatedIdentityServerDTO.constructApiParamsJsonString());
stmt.setInt(index++, identityServerId);
stmt.setInt(index, tenantId);
stmt.executeUpdate();
}
} catch (DBConnectionException e) {
String msg = "Error occurred while obtaining the DB connection to update identity server.";
log.error(msg, e);
throw new ApplicationManagementDAOException(msg, e);
} catch (SQLException e) {
String msg = "Error occurred when executing SQL to update identity server. Executed query: " + sql;
log.error(msg, e);
throw new ApplicationManagementDAOException(msg, e);
}
}
@Override
public int createIdentityServer(IdentityServerDTO identityServerDTO, int tenantId) throws ApplicationManagementDAOException {
if (log.isDebugEnabled()) {
@ -107,8 +229,8 @@ public class OracleSPApplicationDAOImpl extends AbstractDAOImpl implements SPAp
String sql = "INSERT INTO AP_IDENTITY_SERVER "
+ "(PROVIDER_NAME, "
+ "NAME, "
+ "DESCRIPTION, URL, API_URL, USERNAME, PASSWORD, TENANT_ID) "
+ "VALUES (?, ?, ?, ?)";
+ "DESCRIPTION, URL, API_PARAMS, USERNAME, PASSWORD, TENANT_ID) "
+ "VALUES (?, ?, ?, ?, ?, ?, ?, ?)";
try {
Connection conn = this.getDBConnection();
try (PreparedStatement stmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS)) {
@ -116,8 +238,8 @@ public class OracleSPApplicationDAOImpl extends AbstractDAOImpl implements SPAp
stmt.setString(2, identityServerDTO.getName());
stmt.setString(3, identityServerDTO.getDescription());
stmt.setString(4, identityServerDTO.getUrl());
stmt.setString(5, identityServerDTO.getApiUrl());
stmt.setString(6, identityServerDTO.getUserName());
stmt.setString(5, identityServerDTO.constructApiParamsJsonString());
stmt.setString(6, identityServerDTO.getUsername());
stmt.setString(7, identityServerDTO.getPassword());
stmt.setInt(8, tenantId);
stmt.executeUpdate();
@ -338,4 +460,29 @@ public class OracleSPApplicationDAOImpl extends AbstractDAOImpl implements SPAp
}
}
@Override
public void deleteIdentityServer(int id, int tenantId) throws ApplicationManagementDAOException {
if (log.isDebugEnabled()) {
log.debug("Request received in DAO Layer to delete identity server with the id: " + id);
}
String sql = "DELETE FROM AP_IDENTITY_SERVER WHERE ID = ? AND TENANT_ID = ?";
try {
Connection conn = this.getDBConnection();
try (PreparedStatement stmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS)) {
stmt.setInt(1, id);
stmt.setInt(2, tenantId);
stmt.executeUpdate();
}
} catch (DBConnectionException e) {
String msg = "Error occurred while obtaining the DB connection to delete an identity server with the id " + id;
log.error(msg, e);
throw new ApplicationManagementDAOException(msg, e);
} catch (SQLException e) {
String msg = "Error occurred while executing SQL to delete an identity server which has the id "
+ id;
log.error(msg, e);
throw new ApplicationManagementDAOException(msg, e);
}
}
}

@ -41,7 +41,7 @@ public class PostgreSQLSPApplicationDAOImpl extends AbstractDAOImpl implements S
@Override
public List<IdentityServerDTO> getIdentityServers(int tenantId) throws ApplicationManagementDAOException {
String sql = "SELECT ID, PROVIDER_NAME, NAME, DESCRIPTION, URL, API_URL, USERNAME, PASSWORD, TENANT_ID "
String sql = "SELECT ID, PROVIDER_NAME, NAME, DESCRIPTION, URL, API_PARAMS, USERNAME, PASSWORD, TENANT_ID "
+ "FROM AP_IDENTITY_SERVER "
+ "WHERE TENANT_ID = ?";
try {
@ -68,7 +68,7 @@ public class PostgreSQLSPApplicationDAOImpl extends AbstractDAOImpl implements S
@Override
public IdentityServerDTO getIdentityServerById(int id, int tenantId) throws ApplicationManagementDAOException {
String sql = "SELECT ID, PROVIDER_NAME, NAME, DESCRIPTION, URL, API_URL, USERNAME, PASSWORD, TENANT_ID "
String sql = "SELECT ID, PROVIDER_NAME, NAME, DESCRIPTION, URL, API_PARAMS, USERNAME, PASSWORD, TENANT_ID "
+ "FROM AP_IDENTITY_SERVER "
+ "WHERE TENANT_ID = ? AND "
+ "ID = ?";
@ -99,6 +99,128 @@ public class PostgreSQLSPApplicationDAOImpl extends AbstractDAOImpl implements S
}
}
@Override
public boolean isExistingIdentityServerUrl(String url, int tenantId) throws ApplicationManagementDAOException {
String sql = "SELECT AP_APP.ID AS ID "
+ "FROM AP_IDENTITY_SERVER "
+ "WHERE "
+ "LOWER(URL) = LOWER(?) AND "
+ "AP_APP.TENANT_ID = ?";
try {
Connection conn = this.getDBConnection();
try (PreparedStatement stmt = conn.prepareStatement(sql)){
stmt.setString(1, url);
stmt.setInt(2, tenantId);
try (ResultSet rs = stmt.executeQuery()){
return rs.next();
}
}
} catch (DBConnectionException e) {
String msg = "Error occurred while obtaining the DB connection to check if identity server url: " + url +
" already exist";
log.error(msg, e);
throw new ApplicationManagementDAOException(msg, e);
} catch (SQLException e) {
String msg = "Error occurred while executing query to check if identity server with the url " + url +
" already exists.";
log.error(msg, e);
throw new ApplicationManagementDAOException(msg, e);
}
}
@Override
public boolean isExistingIdentityServerName(String name, int tenantId) throws ApplicationManagementDAOException {
String sql = "SELECT AP_APP.ID AS ID "
+ "FROM AP_IDENTITY_SERVER "
+ "WHERE "
+ "LOWER(NAME) = LOWER(?) AND "
+ "AP_APP.TENANT_ID = ?";
try {
Connection conn = this.getDBConnection();
try (PreparedStatement stmt = conn.prepareStatement(sql)){
stmt.setString(1, name);
stmt.setInt(2, tenantId);
try (ResultSet rs = stmt.executeQuery()){
return rs.next();
}
}
} catch (DBConnectionException e) {
String msg = "Error occurred while obtaining the DB connection to check if identity server name: " + name +
" already exist";
log.error(msg, e);
throw new ApplicationManagementDAOException(msg, e);
} catch (SQLException e) {
String msg = "Error occurred while executing query to check if identity server with the name " + name +
" already exists.";
log.error(msg, e);
throw new ApplicationManagementDAOException(msg, e);
}
}
@Override
public void updateIdentityServer(IdentityServerDTO updatedIdentityServerDTO, int tenantId, int identityServerId)
throws ApplicationManagementDAOException {
String sql = "UPDATE AP_IDENTITY_SERVER " +
"SET ";
if (updatedIdentityServerDTO.getName() != null) {
sql += "NAME = ?, ";
}
if (updatedIdentityServerDTO.getUrl() != null) {
sql += "URL = ?, ";
}
if (updatedIdentityServerDTO.getProviderName() != null) {
sql += "PROVIDER_NAME = ?, ";
}
if (updatedIdentityServerDTO.getUsername() != null) {
sql += "USERNAME = ?, ";
}
if (updatedIdentityServerDTO.getPassword() != null) {
sql += "PASSWORD = ?, ";
}
if (updatedIdentityServerDTO.getDescription() != null) {
sql += "DESCRIPTION = ?, ";
}
sql += "API_PARAMS = ? " +
"WHERE ID = ? AND TENANT_ID = ?";
try {
int index = 1;
Connection conn = this.getDBConnection();
try (PreparedStatement stmt = conn.prepareStatement(sql)) {
if (updatedIdentityServerDTO.getName() != null) {
stmt.setString(index++, updatedIdentityServerDTO.getName());
}
if (updatedIdentityServerDTO.getUrl() != null) {
stmt.setString(index++, updatedIdentityServerDTO.getUrl());
}
if (updatedIdentityServerDTO.getProviderName() != null) {
stmt.setString(index++, updatedIdentityServerDTO.getProviderName());
}
if (updatedIdentityServerDTO.getUsername() != null) {
stmt.setString(index++, updatedIdentityServerDTO.getUsername());
}
if (updatedIdentityServerDTO.getPassword() != null) {
stmt.setString(index++, updatedIdentityServerDTO.getPassword());
}
if (updatedIdentityServerDTO.getDescription() != null) {
stmt.setString(index++, updatedIdentityServerDTO.getDescription());
}
stmt.setString(index++, updatedIdentityServerDTO.constructApiParamsJsonString());
stmt.setInt(index++, identityServerId);
stmt.setInt(index, tenantId);
stmt.executeUpdate();
}
} catch (DBConnectionException e) {
String msg = "Error occurred while obtaining the DB connection to update identity server.";
log.error(msg, e);
throw new ApplicationManagementDAOException(msg, e);
} catch (SQLException e) {
String msg = "Error occurred when executing SQL to update identity server. Executed query: " + sql;
log.error(msg, e);
throw new ApplicationManagementDAOException(msg, e);
}
}
@Override
public int createIdentityServer(IdentityServerDTO identityServerDTO, int tenantId) throws ApplicationManagementDAOException {
if (log.isDebugEnabled()) {
@ -107,8 +229,8 @@ public class PostgreSQLSPApplicationDAOImpl extends AbstractDAOImpl implements S
String sql = "INSERT INTO AP_IDENTITY_SERVER "
+ "(PROVIDER_NAME, "
+ "NAME, "
+ "DESCRIPTION, URL, API_URL, USERNAME, PASSWORD, TENANT_ID) "
+ "VALUES (?, ?, ?, ?)";
+ "DESCRIPTION, URL, API_PARAMS, USERNAME, PASSWORD, TENANT_ID) "
+ "VALUES (?, ?, ?, ?, ?, ?, ?, ?)";
try {
Connection conn = this.getDBConnection();
try (PreparedStatement stmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS)) {
@ -116,8 +238,8 @@ public class PostgreSQLSPApplicationDAOImpl extends AbstractDAOImpl implements S
stmt.setString(2, identityServerDTO.getName());
stmt.setString(3, identityServerDTO.getDescription());
stmt.setString(4, identityServerDTO.getUrl());
stmt.setString(5, identityServerDTO.getApiUrl());
stmt.setString(6, identityServerDTO.getUserName());
stmt.setString(5, identityServerDTO.constructApiParamsJsonString());
stmt.setString(6, identityServerDTO.getUsername());
stmt.setString(7, identityServerDTO.getPassword());
stmt.setInt(8, tenantId);
stmt.executeUpdate();
@ -338,4 +460,29 @@ public class PostgreSQLSPApplicationDAOImpl extends AbstractDAOImpl implements S
}
}
@Override
public void deleteIdentityServer(int id, int tenantId) throws ApplicationManagementDAOException {
if (log.isDebugEnabled()) {
log.debug("Request received in DAO Layer to delete identity server with the id: " + id);
}
String sql = "DELETE FROM AP_IDENTITY_SERVER WHERE ID = ? AND TENANT_ID = ?";
try {
Connection conn = this.getDBConnection();
try (PreparedStatement stmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS)) {
stmt.setInt(1, id);
stmt.setInt(2, tenantId);
stmt.executeUpdate();
}
} catch (DBConnectionException e) {
String msg = "Error occurred while obtaining the DB connection to delete an identity server with the id " + id;
log.error(msg, e);
throw new ApplicationManagementDAOException(msg, e);
} catch (SQLException e) {
String msg = "Error occurred while executing SQL to delete an identity server which has the id "
+ id;
log.error(msg, e);
throw new ApplicationManagementDAOException(msg, e);
}
}
}

@ -41,7 +41,7 @@ public class SQLServerSPApplicationDAOImpl extends AbstractDAOImpl implements S
@Override
public List<IdentityServerDTO> getIdentityServers(int tenantId) throws ApplicationManagementDAOException {
String sql = "SELECT ID, PROVIDER_NAME, NAME, DESCRIPTION, URL, API_URL, USERNAME, PASSWORD, TENANT_ID "
String sql = "SELECT ID, PROVIDER_NAME, NAME, DESCRIPTION, URL, API_PARAMS, USERNAME, PASSWORD, TENANT_ID "
+ "FROM AP_IDENTITY_SERVER "
+ "WHERE TENANT_ID = ?";
try {
@ -68,7 +68,7 @@ public class SQLServerSPApplicationDAOImpl extends AbstractDAOImpl implements S
@Override
public IdentityServerDTO getIdentityServerById(int id, int tenantId) throws ApplicationManagementDAOException {
String sql = "SELECT ID, PROVIDER_NAME, NAME, DESCRIPTION, URL, API_URL, USERNAME, PASSWORD, TENANT_ID "
String sql = "SELECT ID, PROVIDER_NAME, NAME, DESCRIPTION, URL, API_PARAMS, USERNAME, PASSWORD, TENANT_ID "
+ "FROM AP_IDENTITY_SERVER "
+ "WHERE TENANT_ID = ? AND "
+ "ID = ?";
@ -99,6 +99,128 @@ public class SQLServerSPApplicationDAOImpl extends AbstractDAOImpl implements S
}
}
@Override
public boolean isExistingIdentityServerUrl(String url, int tenantId) throws ApplicationManagementDAOException {
String sql = "SELECT AP_APP.ID AS ID "
+ "FROM AP_IDENTITY_SERVER "
+ "WHERE "
+ "LOWER(URL) = LOWER(?) AND "
+ "AP_APP.TENANT_ID = ?";
try {
Connection conn = this.getDBConnection();
try (PreparedStatement stmt = conn.prepareStatement(sql)){
stmt.setString(1, url);
stmt.setInt(2, tenantId);
try (ResultSet rs = stmt.executeQuery()){
return rs.next();
}
}
} catch (DBConnectionException e) {
String msg = "Error occurred while obtaining the DB connection to check if identity server url: " + url +
" already exist";
log.error(msg, e);
throw new ApplicationManagementDAOException(msg, e);
} catch (SQLException e) {
String msg = "Error occurred while executing query to check if identity server with the url " + url +
" already exists.";
log.error(msg, e);
throw new ApplicationManagementDAOException(msg, e);
}
}
@Override
public boolean isExistingIdentityServerName(String name, int tenantId) throws ApplicationManagementDAOException {
String sql = "SELECT AP_APP.ID AS ID "
+ "FROM AP_IDENTITY_SERVER "
+ "WHERE "
+ "LOWER(NAME) = LOWER(?) AND "
+ "AP_APP.TENANT_ID = ?";
try {
Connection conn = this.getDBConnection();
try (PreparedStatement stmt = conn.prepareStatement(sql)){
stmt.setString(1, name);
stmt.setInt(2, tenantId);
try (ResultSet rs = stmt.executeQuery()){
return rs.next();
}
}
} catch (DBConnectionException e) {
String msg = "Error occurred while obtaining the DB connection to check if identity server name: " + name +
" already exist";
log.error(msg, e);
throw new ApplicationManagementDAOException(msg, e);
} catch (SQLException e) {
String msg = "Error occurred while executing query to check if identity server with the name " + name +
" already exists.";
log.error(msg, e);
throw new ApplicationManagementDAOException(msg, e);
}
}
@Override
public void updateIdentityServer(IdentityServerDTO updatedIdentityServerDTO, int tenantId, int identityServerId)
throws ApplicationManagementDAOException {
String sql = "UPDATE AP_IDENTITY_SERVER " +
"SET ";
if (updatedIdentityServerDTO.getName() != null) {
sql += "NAME = ?, ";
}
if (updatedIdentityServerDTO.getUrl() != null) {
sql += "URL = ?, ";
}
if (updatedIdentityServerDTO.getProviderName() != null) {
sql += "PROVIDER_NAME = ?, ";
}
if (updatedIdentityServerDTO.getUsername() != null) {
sql += "USERNAME = ?, ";
}
if (updatedIdentityServerDTO.getPassword() != null) {
sql += "PASSWORD = ?, ";
}
if (updatedIdentityServerDTO.getDescription() != null) {
sql += "DESCRIPTION = ?, ";
}
sql += "API_PARAMS = ? " +
"WHERE ID = ? AND TENANT_ID = ?";
try {
int index = 1;
Connection conn = this.getDBConnection();
try (PreparedStatement stmt = conn.prepareStatement(sql)) {
if (updatedIdentityServerDTO.getName() != null) {
stmt.setString(index++, updatedIdentityServerDTO.getName());
}
if (updatedIdentityServerDTO.getUrl() != null) {
stmt.setString(index++, updatedIdentityServerDTO.getUrl());
}
if (updatedIdentityServerDTO.getProviderName() != null) {
stmt.setString(index++, updatedIdentityServerDTO.getProviderName());
}
if (updatedIdentityServerDTO.getUsername() != null) {
stmt.setString(index++, updatedIdentityServerDTO.getUsername());
}
if (updatedIdentityServerDTO.getPassword() != null) {
stmt.setString(index++, updatedIdentityServerDTO.getPassword());
}
if (updatedIdentityServerDTO.getDescription() != null) {
stmt.setString(index++, updatedIdentityServerDTO.getDescription());
}
stmt.setString(index++, updatedIdentityServerDTO.constructApiParamsJsonString());
stmt.setInt(index++, identityServerId);
stmt.setInt(index, tenantId);
stmt.executeUpdate();
}
} catch (DBConnectionException e) {
String msg = "Error occurred while obtaining the DB connection to update identity server.";
log.error(msg, e);
throw new ApplicationManagementDAOException(msg, e);
} catch (SQLException e) {
String msg = "Error occurred when executing SQL to update identity server. Executed query: " + sql;
log.error(msg, e);
throw new ApplicationManagementDAOException(msg, e);
}
}
@Override
public int createIdentityServer(IdentityServerDTO identityServerDTO, int tenantId) throws ApplicationManagementDAOException {
if (log.isDebugEnabled()) {
@ -107,8 +229,8 @@ public class SQLServerSPApplicationDAOImpl extends AbstractDAOImpl implements S
String sql = "INSERT INTO AP_IDENTITY_SERVER "
+ "(PROVIDER_NAME, "
+ "NAME, "
+ "DESCRIPTION, URL, API_URL, USERNAME, PASSWORD, TENANT_ID) "
+ "VALUES (?, ?, ?, ?)";
+ "DESCRIPTION, URL, API_PARAMS, USERNAME, PASSWORD, TENANT_ID) "
+ "VALUES (?, ?, ?, ?, ?, ?, ?, ?)";
try {
Connection conn = this.getDBConnection();
try (PreparedStatement stmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS)) {
@ -116,8 +238,8 @@ public class SQLServerSPApplicationDAOImpl extends AbstractDAOImpl implements S
stmt.setString(2, identityServerDTO.getName());
stmt.setString(3, identityServerDTO.getDescription());
stmt.setString(4, identityServerDTO.getUrl());
stmt.setString(5, identityServerDTO.getApiUrl());
stmt.setString(6, identityServerDTO.getUserName());
stmt.setString(5, identityServerDTO.constructApiParamsJsonString());
stmt.setString(6, identityServerDTO.getUsername());
stmt.setString(7, identityServerDTO.getPassword());
stmt.setInt(8, tenantId);
stmt.executeUpdate();
@ -326,16 +448,41 @@ public class SQLServerSPApplicationDAOImpl extends AbstractDAOImpl implements S
stmt.executeUpdate();
}
} catch (DBConnectionException e) {
String msg = "Error occurred while obtaining the DB connection to create an sp application mapping which has "
String msg = "Error occurred while obtaining the DB connection to delete an sp application mapping which has "
+ "application id " + applicationId;
log.error(msg, e);
throw new ApplicationManagementDAOException(msg, e);
} catch (SQLException e) {
String msg = "Error occurred while executing SQL to create an application which has application id "
String msg = "Error occurred while executing SQL to delete an application which has application id "
+ applicationId;
log.error(msg, e);
throw new ApplicationManagementDAOException(msg, e);
}
}
@Override
public void deleteIdentityServer(int id, int tenantId) throws ApplicationManagementDAOException {
if (log.isDebugEnabled()) {
log.debug("Request received in DAO Layer to delete identity server with the id: " + id);
}
String sql = "DELETE FROM AP_IDENTITY_SERVER WHERE ID = ? AND TENANT_ID = ?";
try {
Connection conn = this.getDBConnection();
try (PreparedStatement stmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS)) {
stmt.setInt(1, id);
stmt.setInt(2, tenantId);
stmt.executeUpdate();
}
} catch (DBConnectionException e) {
String msg = "Error occurred while obtaining the DB connection to delete an identity server with the id " + id;
log.error(msg, e);
throw new ApplicationManagementDAOException(msg, e);
} catch (SQLException e) {
String msg = "Error occurred while executing SQL to delete an identity server which has the id "
+ id;
log.error(msg, e);
throw new ApplicationManagementDAOException(msg, e);
}
}
}

@ -0,0 +1,68 @@
package io.entgra.application.mgt.core.identityserver.serviceprovider;
import io.entgra.application.mgt.common.SPApplication;
import io.entgra.application.mgt.common.SPApplicationListResponse;
import io.entgra.application.mgt.common.dto.IdentityServerDTO;
import io.entgra.application.mgt.common.exception.ApplicationManagementException;
import io.entgra.application.mgt.common.exception.InvalidConfigurationException;
import io.entgra.application.mgt.core.config.ConfigurationManager;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import java.lang.reflect.Constructor;
import java.util.List;
public interface ISServiceProviderApplicationService {
Log log = LogFactory.getLog(ISServiceProviderApplicationService.class);
static ISServiceProviderApplicationService of(String identityServerName) throws InvalidConfigurationException {
String className = ConfigurationManager.getInstance().getIdentityServerConfiguration().
getIdentityServerDetailByProviderName(identityServerName).getProviderClassName();
try {
Class theClass = Class.forName(className);
Constructor<ISServiceProviderApplicationService> constructor = theClass.getConstructor();
return constructor.newInstance();
} catch (Exception e) {
String msg = "Unable to get instance of " + className;
log.error(msg, e);
throw new InvalidConfigurationException(msg, e);
}
}
/**
* Use to get IS Service specific api params
*
* @return IS Service specific api params
*/
List<String> getRequiredApiParams();
/**
* Check if service provider application exists
*
* @param identityServer {@link IdentityServerDTO}
* @param spAppId uid of the service provider
* @return if service provider exist
* @throws ApplicationManagementException
*/
boolean isSPApplicationExist(IdentityServerDTO identityServer, String spAppId) throws ApplicationManagementException;
/**
* Get service provider by identity server id and service provider uid
* @param identityServer {@link IdentityServerDTO}
* @param spAppId uid of service provider to be retrieved
* @return {@link SPApplication}
* @throws ApplicationManagementException
*/
SPApplication retrieveSPApplication(IdentityServerDTO identityServer, String spAppId) throws ApplicationManagementException;
/**
* Retrieve service provider apps from identity server
*
* @param identityServer {@link IdentityServerDTO}
* @return {@link SPApplicationListResponse}
* @throws ApplicationManagementException
*/
SPApplicationListResponse retrieveSPApplications(IdentityServerDTO identityServer, Integer limit, Integer offset)
throws ApplicationManagementException;
}

@ -0,0 +1,156 @@
/*
* Copyright (c) 2022, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you 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 io.entgra.application.mgt.core.identityserver.serviceprovider.impl;
import com.google.gson.Gson;
import io.entgra.application.mgt.common.SPApplication;
import io.entgra.application.mgt.common.SPApplicationListResponse;
import io.entgra.application.mgt.common.dto.IdentityServerDTO;
import io.entgra.application.mgt.common.exception.ApplicationManagementException;
import io.entgra.application.mgt.common.exception.IdentityServerManagementException;
import io.entgra.application.mgt.core.identityserver.serviceprovider.ISServiceProviderApplicationService;
import io.entgra.application.mgt.core.util.Constants;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.wso2.carbon.device.mgt.core.common.util.HttpUtil;
import javax.ws.rs.core.HttpHeaders;
import java.io.IOException;
import java.util.Collections;
import java.util.List;
public class WSO2IAMSPApplicationService implements ISServiceProviderApplicationService {
private static final List<String> REQUIRED_API_PARAM_LIST;
private static final String TENANT_DOMAIN = "Tenant domain";
private static final String SP_APPLICATION_API_CONTEXT = "/t/%s/api/server/v1/applications";
private static final Log log = LogFactory.getLog(WSO2IAMSPApplicationService.class);
static {
REQUIRED_API_PARAM_LIST = Collections.singletonList(TENANT_DOMAIN);
}
public List<String> getRequiredApiParams() {
return REQUIRED_API_PARAM_LIST;
}
public boolean isSPApplicationExist(IdentityServerDTO identityServer, String spAppId) throws ApplicationManagementException {
SPApplication application = retrieveSPApplication(identityServer, spAppId);
return application != null;
}
public SPApplication retrieveSPApplication(IdentityServerDTO identityServer, String spAppId) throws ApplicationManagementException {
HttpGet req = new HttpGet();
String uriString = constructAPIUrl(identityServer);
uriString += Constants.FORWARD_SLASH + spAppId;
req.setURI(HttpUtil.createURI(uriString));
CloseableHttpClient client = HttpClients.createDefault();
try {
HttpResponse response = invokeISAPI(identityServer, client, req);
String responseBody = HttpUtil.getResponseString(response);
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
return new Gson().fromJson(responseBody,
SPApplication.class);
}
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_NOT_FOUND) {
return null;
}
String msg = constructErrorMessage(response);
log.error(msg);
throw new IdentityServerManagementException(msg);
} catch (IOException e) {
String msg = "Error occurred while calling SP Applications API. Make sure identity server is up and running";
log.error(msg, e);
throw new IdentityServerManagementException(msg);
} finally {
try {
client.close();
} catch (IOException e) {
log.error("Error occurred while closing http connection");
}
}
}
private String constructErrorMessage(HttpResponse response) {
String msg = "Error occurred while calling SP Applications API";
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_UNAUTHORIZED) {
msg += ". Make sure provided identity Server credentials are valid";
}
return msg;
}
public SPApplicationListResponse retrieveSPApplications(IdentityServerDTO identityServer, Integer limit, Integer offset)
throws ApplicationManagementException {
HttpGet req = new HttpGet();
String uriString = constructAPIUrl(identityServer);
uriString += Constants.URI_QUERY_SEPARATOR + Constants.LIMIT_QUERY_PARAM + Constants.QUERY_KEY_VALUE_SEPARATOR
+ limit;
uriString += Constants.QUERY_STRING_SEPARATOR + Constants.OFFSET_QUERY_PARAM + Constants.QUERY_KEY_VALUE_SEPARATOR
+ offset;
req.setURI(HttpUtil.createURI(uriString));
CloseableHttpClient client = HttpClients.createDefault();
try {
HttpResponse response = invokeISAPI(identityServer, client, req);
String responseBody = HttpUtil.getResponseString(response);
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
return new Gson().fromJson(responseBody,
SPApplicationListResponse.class);
}
String msg = constructErrorMessage(response);
log.error(msg);
throw new IdentityServerManagementException(msg);
} catch (IOException e) {
String msg = "Error occurred while calling SP Applications API. Make sure identity server is up and running";
log.error(msg, e);
throw new IdentityServerManagementException(msg);
} finally {
try {
client.close();
} catch (IOException e) {
log.error("Error occurred while closing http connection");
}
}
}
private HttpResponse invokeISAPI(IdentityServerDTO identityServer, HttpClient client, HttpGet request) throws IOException {
setBasicAuthHeader(identityServer, request);
return client.execute(request);
}
private void setBasicAuthHeader(IdentityServerDTO identityServer, HttpRequestBase request) {
String basicAuthHeader = HttpUtil.getBasicAuthBase64Header(identityServer.getUsername(),
identityServer.getPassword());
request.setHeader(HttpHeaders.AUTHORIZATION, basicAuthHeader);
}
private String constructAPIUrl(IdentityServerDTO identityServer) {
String identityServerUrl = identityServer.getUrl();
// add "/" at the end, if the server url doesn't contain "/" at the end
if (identityServerUrl.charAt(identityServerUrl.length() - 1) != Constants.FORWARD_SLASH.charAt(0)) {
identityServerUrl += Constants.FORWARD_SLASH;
}
return identityServerUrl + String.format(SP_APPLICATION_API_CONTEXT, identityServer.getApiParams().get(TENANT_DOMAIN));
}
}

@ -18,32 +18,42 @@
package io.entgra.application.mgt.core.impl;
import io.entgra.application.mgt.common.IdentityServer;
import io.entgra.application.mgt.common.IdentityServerResponse;
import io.entgra.application.mgt.common.SPApplicationListResponse;
import io.entgra.application.mgt.common.dto.IdentityServerDTO;
import io.entgra.application.mgt.common.SPApplication;
import io.entgra.application.mgt.common.dto.ApplicationDTO;
import io.entgra.application.mgt.common.dto.IdentityServiceProviderDTO;
import io.entgra.application.mgt.common.exception.ApplicationManagementException;
import io.entgra.application.mgt.common.exception.DBConnectionException;
import io.entgra.application.mgt.common.exception.TransactionManagementException;
import io.entgra.application.mgt.common.response.Application;
import io.entgra.application.mgt.common.services.ApplicationManager;
import io.entgra.application.mgt.common.services.SPApplicationManager;
import io.entgra.application.mgt.core.config.ConfigurationManager;
import io.entgra.application.mgt.core.config.IdentityServiceProvider;
import io.entgra.application.mgt.core.dao.ApplicationDAO;
import io.entgra.application.mgt.core.dao.SPApplicationDAO;
import io.entgra.application.mgt.core.dao.VisibilityDAO;
import io.entgra.application.mgt.core.dao.common.ApplicationManagementDAOFactory;
import io.entgra.application.mgt.core.exception.ApplicationManagementDAOException;
import io.entgra.application.mgt.core.exception.BadRequestException;
import io.entgra.application.mgt.core.exception.NotFoundException;
import io.entgra.application.mgt.core.identityserver.serviceprovider.ISServiceProviderApplicationService;
import io.entgra.application.mgt.core.internal.DataHolder;
import io.entgra.application.mgt.core.lifecycle.LifecycleStateManager;
import io.entgra.application.mgt.core.util.APIUtil;
import io.entgra.application.mgt.core.util.ApplicationManagementUtil;
import io.entgra.application.mgt.core.util.ConnectionManagerUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.commons.validator.routines.UrlValidator;
import org.wso2.carbon.context.PrivilegedCarbonContext;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
public class SPApplicationManagerImpl implements SPApplicationManager {
@ -65,20 +75,27 @@ public class SPApplicationManagerImpl implements SPApplicationManager {
this.spApplicationDAO = ApplicationManagementDAOFactory.getSPApplicationDAO();
}
public void addExistingApps(int identityServerId, List<SPApplication> applications) throws ApplicationManagementException {
for (SPApplication application : applications) {
List<Application> existingApplications = getSPApplications(identityServerId, application.getId());
application.setExistingApplications(existingApplications);
@Override
public IdentityServerResponse getIdentityServerResponse(int identityServerId) throws ApplicationManagementException {
IdentityServerDTO identityServerDTO = getIdentityServer(identityServerId);
return APIUtil.identityServerDtoToIdentityServerResponse(identityServerDTO);
}
private IdentityServerDTO getIdentityServer(int identityServerId) throws ApplicationManagementException {
IdentityServerDTO identityServerDTO = getIdentityServerFromDB(identityServerId);
if (identityServerDTO == null) {
String msg = "Identity server with the id: " + identityServerId + " does not exist";
log.error(msg);
throw new NotFoundException(msg);
}
return identityServerDTO;
}
@Override
public IdentityServer getIdentityServer(int identityServerId) throws ApplicationManagementException {
private IdentityServerDTO getIdentityServerFromDB(int identityServerId) throws ApplicationManagementException {
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();
try {
ConnectionManagerUtil.openDBConnection();
IdentityServerDTO identityServerDTO = spApplicationDAO.getIdentityServerById(identityServerId, tenantId);
return APIUtil.identityServerDtoToIdentityServerResponse(identityServerDTO);
return spApplicationDAO.getIdentityServerById(identityServerId, tenantId);
} catch (DBConnectionException e) {
String msg = "Error occurred when getting database connection to get identity server with the id: " + identityServerId;
log.error(msg, e);
@ -94,7 +111,7 @@ public class SPApplicationManagerImpl implements SPApplicationManager {
}
@Override
public List<IdentityServer> getIdentityServers() throws ApplicationManagementException {
public List<IdentityServerResponse> getIdentityServers() throws ApplicationManagementException {
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();
try {
ConnectionManagerUtil.openDBConnection();
@ -115,16 +132,276 @@ public class SPApplicationManagerImpl implements SPApplicationManager {
}
@Override
public IdentityServer createIdentityServer(IdentityServerDTO identityServerDTO) throws ApplicationManagementException {
public IdentityServerResponse createIdentityServer(IdentityServerDTO identityServerDTO) throws ApplicationManagementException {
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();
validateIdentityServerCreateRequest(identityServerDTO);
try {
ConnectionManagerUtil.beginDBTransaction();
int id = spApplicationDAO.createIdentityServer(identityServerDTO, tenantId);
identityServerDTO.setId(id);
ConnectionManagerUtil.commitDBTransaction();
return APIUtil.identityServerDtoToIdentityServerResponse(identityServerDTO);
} catch (ApplicationManagementDAOException e) {
ConnectionManagerUtil.rollbackDBTransaction();
String msg = "Error occurred while creating identity server " + identityServerDTO.getName();
log.error(msg, e);
throw new ApplicationManagementException(msg, e);
} finally {
ConnectionManagerUtil.closeDBConnection();
}
}
@Override
public IdentityServerResponse updateIdentityServer(IdentityServerDTO updateIdentityServerDTO, int id)
throws ApplicationManagementException {
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();
IdentityServerDTO existingIdentityServerDTO = getIdentityServer(id);
validateIdentityServerUpdateRequest(updateIdentityServerDTO, existingIdentityServerDTO);
Map<String, String> updatedApiParams = constructUpdatedApiParams(updateIdentityServerDTO, existingIdentityServerDTO);
updateIdentityServerDTO.setApiParams(updatedApiParams);
try {
ConnectionManagerUtil.beginDBTransaction();
spApplicationDAO.updateIdentityServer(updateIdentityServerDTO, tenantId, id);
ConnectionManagerUtil.commitDBTransaction();
} catch (ApplicationManagementDAOException e) {
ConnectionManagerUtil.rollbackDBTransaction();
String msg = "Error occurred while creating identity server " + updateIdentityServerDTO.getName();
log.error(msg, e);
throw new ApplicationManagementException(msg, e);
} finally {
ConnectionManagerUtil.closeDBConnection();
}
return getIdentityServerResponse(id);
}
@Override
public void deleteIdentityServer(int id) throws ApplicationManagementException {
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();
validateIdentityServerDeleteRequest(id);
try {
ConnectionManagerUtil.beginDBTransaction();
spApplicationDAO.deleteIdentityServer(id, tenantId);
ConnectionManagerUtil.commitDBTransaction();
} catch (ApplicationManagementDAOException e) {
ConnectionManagerUtil.rollbackDBTransaction();
String msg = "Error occurred while creating identity server with the id " + id;
log.error(msg, e);
throw new ApplicationManagementException(msg, e);
} finally {
ConnectionManagerUtil.closeDBConnection();
}
}
private void validateIdentityServerDeleteRequest(int identityServerId) throws ApplicationManagementException {
IdentityServerDTO identityServerDTO = getIdentityServerFromDB(identityServerId);
if (identityServerDTO == null) {
String msg = "Identity server with the id: " + identityServerId + " does not exist to delete";
log.error(msg);
throw new BadRequestException(msg);
}
}
private Map<String, String> constructUpdatedApiParams(IdentityServerDTO updatedIdentityServerDTO,
IdentityServerDTO existingIdentityServerDTO) {
Map<String, String> updatedApiParams = updatedIdentityServerDTO.getApiParams();
Map<String, String> existingApiParams = existingIdentityServerDTO.getApiParams();
if (updatedIdentityServerDTO.getProviderName().equals(existingIdentityServerDTO.getProviderName())) {
existingApiParams.putAll(updatedApiParams);
return existingApiParams;
}
return updatedApiParams;
}
/**
* Validate the identity server update request payload
*
* @param updateIdentityServerDTO of identity server update request
* @throws BadRequestException if any invalid payload found
*/
private void validateIdentityServerUpdateRequest(IdentityServerDTO updateIdentityServerDTO,
IdentityServerDTO existingIdentityServerDTO) throws ApplicationManagementException {
if (updateIdentityServerDTO.getProviderName() != null &&
isIdentityServiceProviderNotConfigured(updateIdentityServerDTO.getProviderName())) {
String msg = "No such providers configured. Provider name: " + updateIdentityServerDTO.getProviderName();
log.error(msg);
throw new BadRequestException(msg);
}
if (updateIdentityServerDTO.getName() != null) {
if (!updateIdentityServerDTO.getName().equalsIgnoreCase(existingIdentityServerDTO.getName())
&& isIdentityServerNameExist(updateIdentityServerDTO.getName())) {
String msg = "Identity server already exist with the given name. Identity server name: " + updateIdentityServerDTO.getName();
log.error(msg);
throw new BadRequestException(msg);
}
}
if (updateIdentityServerDTO.getUrl() != null) {
validateIdentityServerUrl(updateIdentityServerDTO.getUrl());
if(!updateIdentityServerDTO.getUrl().equalsIgnoreCase(existingIdentityServerDTO.getUrl()) &&
isIdentityServerUrlExist(updateIdentityServerDTO.getUrl())) {
String msg = "Identity server already exist with the given url. Identity server url: " + updateIdentityServerDTO.getUrl();
log.error(msg);
throw new BadRequestException(msg);
}
}
validateUpdateIdentityServerRequestApiParam(updateIdentityServerDTO, existingIdentityServerDTO);
}
/**
* Validate the identity server create request payload
*
* @param identityServerDTO of identity server create request
* @throws BadRequestException if any invalid payload found
*/
private void validateIdentityServerCreateRequest(IdentityServerDTO identityServerDTO) throws ApplicationManagementException {
if (identityServerDTO.getUsername() == null) {
String msg = "Identity server username can not be null";
log.error(msg);
throw new BadRequestException(msg);
}
if (identityServerDTO.getPassword() == null) {
String msg = "Identity server password can not be null";
log.error(msg);
throw new BadRequestException(msg);
}
if (identityServerDTO.getName() == null) {
String msg = "Identity server name can not be null";
log.error(msg);
throw new BadRequestException(msg);
}
if (identityServerDTO.getUrl() == null) {
String msg = "Identity server url can not be null";
log.error(msg);
throw new BadRequestException(msg);
}
if (isIdentityServiceProviderNotConfigured(identityServerDTO.getProviderName())) {
String msg = "No such providers configured. Provider name: " + identityServerDTO.getProviderName();
log.error(msg);
throw new BadRequestException(msg);
}
if (isIdentityServerNameExist(identityServerDTO.getName())) {
String msg = "Identity server already exist with the given name. Identity server name: " + identityServerDTO.getName();
log.error(msg);
throw new BadRequestException(msg);
}
if (isIdentityServerUrlExist(identityServerDTO.getUrl())) {
String msg = "Identity server already exist with the given url. Identity server url: " + identityServerDTO.getUrl();
log.error(msg);
throw new BadRequestException(msg);
}
validateCreateIdentityServerRequestApiParams(identityServerDTO);
validateIdentityServerUrl(identityServerDTO.getUrl());
}
private void validateIdentityServerUrl(String url) throws BadRequestException {
String[] schemes = {"http","https"};
UrlValidator urlValidator = new UrlValidator(schemes, UrlValidator.ALLOW_LOCAL_URLS);
if (!urlValidator.isValid(url)) {
String msg = "Identity server url is not a valid url";
log.error(msg);
throw new BadRequestException(msg);
}
}
private void validateUpdateIdentityServerRequestApiParam(IdentityServerDTO identityServerUpdateDTO,
IdentityServerDTO existingIdentityServerDTO) throws ApplicationManagementException {
ISServiceProviderApplicationService serviceProviderApplicationService =
ISServiceProviderApplicationService.of(existingIdentityServerDTO.getProviderName());
List<String> requiredApiParams = serviceProviderApplicationService.getRequiredApiParams();
if (!identityServerUpdateDTO.getProviderName().equals(existingIdentityServerDTO.getProviderName())) {
validateAllRequiredParamsExists(identityServerUpdateDTO, requiredApiParams);
}
validateIfAnyInvalidParamExists(identityServerUpdateDTO, requiredApiParams);
}
private void validateCreateIdentityServerRequestApiParams(IdentityServerDTO identityServerDTO) throws ApplicationManagementException {
ISServiceProviderApplicationService serviceProviderApplicationService =
ISServiceProviderApplicationService.of(identityServerDTO.getProviderName());
List<String> requiredApiParams = serviceProviderApplicationService.getRequiredApiParams();
validateAllRequiredParamsExists(identityServerDTO, requiredApiParams);
validateIfAnyInvalidParamExists(identityServerDTO, requiredApiParams);
}
private void validateAllRequiredParamsExists(IdentityServerDTO identityServerDTO, List<String> requiredApiParams)
throws BadRequestException {
for (String param : requiredApiParams) {
if (identityServerDTO.getApiParams().get(param) == null) {
String msg = param + " api parameter is required for " + identityServerDTO.getProviderName() + ". " +
"Required api parameters: " + StringUtils.join(requiredApiParams, ",");
log.error(msg);
throw new BadRequestException(msg);
}
}
}
private void validateIfAnyInvalidParamExists(IdentityServerDTO identityServerDTO, List<String> requiredApiParams)
throws BadRequestException {
for (String param : identityServerDTO.getApiParamKeys()) {
if (!requiredApiParams.contains(param)) {
String msg = "Invalid api parameter. " + param + " is not required for " + identityServerDTO.getProviderName() + ". " +
"Required api parameters: " + StringUtils.join(requiredApiParams, ",");
throw new BadRequestException(msg);
}
}
}
private boolean isIdentityServiceProviderNotConfigured(String providerName) {
List<IdentityServiceProvider> identityServiceProviders = ConfigurationManager.getInstance().getIdentityServerConfiguration().
getIdentityServiceProviders();
return identityServiceProviders.stream().noneMatch(provider -> provider.getProviderName().equals(providerName));
}
@Override
public boolean isIdentityServerNameExist(String name) throws ApplicationManagementException {
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();
try {
ConnectionManagerUtil.openDBConnection();
return spApplicationDAO.isExistingIdentityServerName(name, tenantId);
} catch (ApplicationManagementDAOException | DBConnectionException e) {
String msg = "Error occurred while checking if identity server with the name " + name + " exists.";
log.error(msg, e);
throw new ApplicationManagementException(msg, e);
} finally {
ConnectionManagerUtil.closeDBConnection();
}
}
@Override
public boolean isIdentityServerUrlExist(String url) throws ApplicationManagementException {
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();
try {
ConnectionManagerUtil.openDBConnection();
return spApplicationDAO.isExistingIdentityServerUrl(url, tenantId);
} catch (ApplicationManagementDAOException | DBConnectionException e) {
String msg = "Error occurred while checking if identity server with the url " + url + " exists.";
log.error(msg, e);
throw new ApplicationManagementException(msg, e);
} finally {
ConnectionManagerUtil.closeDBConnection();
}
}
@Override
public SPApplicationListResponse retrieveSPApplicationFromIdentityServer(int identityServerId, Integer offset, Integer limit)
throws ApplicationManagementException {
IdentityServerDTO identityServer = getIdentityServer(identityServerId);
ISServiceProviderApplicationService serviceProviderApplicationService = ISServiceProviderApplicationService.of(identityServer.getProviderName());
SPApplicationListResponse spApplicationListResponse = serviceProviderApplicationService.retrieveSPApplications(identityServer, offset, limit);
addExistingApps(identityServerId, spApplicationListResponse.getApplications());
return spApplicationListResponse;
}
/**
* This method adds existing consumer applications of service providers to the SPApplication bean
*
* @param identityServerId identity server id of the service provider
* @param spApplications Service providers list to which the existing applications should be added
* @throws ApplicationManagementException if error occurred while adding existing applications
*/
private void addExistingApps(int identityServerId, List<SPApplication> spApplications) throws ApplicationManagementException {
for (SPApplication spApplication : spApplications) {
List<Application> existingApplications = getSPApplications(identityServerId, spApplication.getId());
spApplication.setExistingApplications(existingApplications);
}
}
@ -174,7 +451,8 @@ public class SPApplicationManagerImpl implements SPApplicationManager {
}
}
public void validateAttachAppsRequest(int identityServerId, List<Integer> appIds) throws ApplicationManagementException {
public void validateAttachAppsRequest(int identityServerId, String serviceProviderId, List<Integer> appIds) throws ApplicationManagementException {
validateServiceProviderUID(identityServerId, serviceProviderId);
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true);
try {
ConnectionManagerUtil.openDBConnection();
@ -197,6 +475,7 @@ public class SPApplicationManagerImpl implements SPApplicationManager {
}
public void validateDetachAppsRequest(int identityServerId, String spId, List<Integer> appIds) throws ApplicationManagementException {
validateServiceProviderUID(identityServerId, spId);
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true);
try {
ConnectionManagerUtil.openDBConnection();
@ -219,6 +498,50 @@ public class SPApplicationManagerImpl implements SPApplicationManager {
}
}
@Override
public List<IdentityServiceProviderDTO> getIdentityServiceProviders() throws ApplicationManagementException {
List<IdentityServiceProvider> identityServiceProviders = ConfigurationManager.getInstance().
getIdentityServerConfiguration().getIdentityServiceProviders();
List<IdentityServiceProviderDTO> identityServiceProviderDTOS = new ArrayList<>();
for (IdentityServiceProvider identityServiceProvider : identityServiceProviders) {
try {
identityServiceProviderDTOS.add(APIUtil.identityServiceProviderToDTO(identityServiceProvider));
} catch (ApplicationManagementException e) {
String msg = "Identity service provider configuration file is invalid. Hence failed to proceed.";
log.error(msg);
throw new ApplicationManagementException(msg);
}
}
return identityServiceProviderDTOS;
}
/**
* Responsible for validating service provider in requests
*
* @param identityServerId identity server id of the service provider
* @param spUID uid of the service provider
* @throws ApplicationManagementException if invalid service provider
*/
private void validateServiceProviderUID(int identityServerId, String spUID) throws
ApplicationManagementException {
IdentityServerDTO identityServer = getIdentityServer(identityServerId);
ISServiceProviderApplicationService serviceProviderApplicationService = ISServiceProviderApplicationService.of(identityServer.getProviderName());
try {
boolean isSPAppExists = serviceProviderApplicationService.
isSPApplicationExist(identityServer, spUID);
if (!isSPAppExists) {
String errMsg = "Service provider with the uid " + spUID + " does not exist.";
log.error(errMsg);
throw new BadRequestException(errMsg);
}
} catch (ApplicationManagementException e) {
String errMsg = "Error occurred while trying to validate service provider uid";
log.error(errMsg, e);
throw new ApplicationManagementException(errMsg, e);
}
}
public void attachSPApplications(int identityServerId, String spUID, List<Integer> appIds) throws ApplicationManagementException {
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();
try {
@ -259,6 +582,7 @@ public class SPApplicationManagerImpl implements SPApplicationManager {
@Override
public <T> Application createSPApplication(T app, int identityServerId, String spId) throws ApplicationManagementException {
validateServiceProviderUID(identityServerId, spId);
ApplicationManager applicationManager = ApplicationManagementUtil.getApplicationManagerInstance();
ApplicationDTO applicationDTO = applicationManager.uploadReleaseArtifactIfExist(app);
if (log.isDebugEnabled()) {

@ -18,9 +18,12 @@
package io.entgra.application.mgt.core.util;
import io.entgra.application.mgt.common.IdentityServer;
import io.entgra.application.mgt.common.IdentityServerResponse;
import io.entgra.application.mgt.common.dto.IdentityServerDTO;
import io.entgra.application.mgt.core.config.IdentityServerDetail;
import io.entgra.application.mgt.common.dto.IdentityServiceProviderDTO;
import io.entgra.application.mgt.common.exception.InvalidConfigurationException;
import io.entgra.application.mgt.core.config.IdentityServiceProvider;
import io.entgra.application.mgt.core.identityserver.serviceprovider.ISServiceProviderApplicationService;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
@ -366,19 +369,28 @@ public class APIUtil {
return applicationReleaseDTO;
}
public static IdentityServer identityServerDtoToIdentityServerResponse(IdentityServerDTO identityServerDTO) {
IdentityServer identityServer = new IdentityServer();
public static IdentityServiceProviderDTO identityServiceProviderToDTO(IdentityServiceProvider identityServiceProvider)
throws InvalidConfigurationException {
ISServiceProviderApplicationService serviceProviderApplicationService =
ISServiceProviderApplicationService.of(identityServiceProvider.getProviderName());
IdentityServiceProviderDTO identityServiceProviderDTO = new IdentityServiceProviderDTO();
identityServiceProviderDTO.setName(identityServiceProvider.getProviderName());
identityServiceProviderDTO.setRequiredApiParams(serviceProviderApplicationService.getRequiredApiParams());
return identityServiceProviderDTO;
}
public static IdentityServerResponse identityServerDtoToIdentityServerResponse(IdentityServerDTO identityServerDTO) {
IdentityServerResponse identityServer = new IdentityServerResponse();
identityServer.setId(identityServerDTO.getId());
identityServer.setProviderName(identityServerDTO.getProviderName());
identityServer.setName(identityServerDTO.getName());
identityServer.setDescription(identityServerDTO.getDescription());
identityServer.setUrl(identityServerDTO.getUrl());
identityServer.setApiUrl(identityServerDTO.getApiUrl());
identityServer.setUserName(identityServerDTO.getUserName());
identityServer.setPassword(identityServerDTO.getPassword());
IdentityServerDetail identityServerDetail = ConfigurationManager.getInstance().getIdentityServerConfiguration()
identityServer.setApiParamList(identityServerDTO.getApiParams());
identityServer.setUsername(identityServerDTO.getUsername());
IdentityServiceProvider identityServiceProvider = ConfigurationManager.getInstance().getIdentityServerConfiguration()
.getIdentityServerDetailByProviderName(identityServerDTO.getProviderName());
String serviceProviderAppsUrl = identityServerDTO.getUrl() + Constants.FORWARD_SLASH + identityServerDetail.getServiceProvidersPageUri();
String serviceProviderAppsUrl = identityServerDTO.getUrl() + identityServiceProvider.getServiceProvidersPageUri();
identityServer.setServiceProviderAppsUrl(serviceProviderAppsUrl);
return identityServer;
}

@ -60,6 +60,9 @@ public class Constants {
public static final String IS_APP_DEFAULT_PAYMENT_CURRENCY = "$";
public static final String IS_APP_DEFAULT_VERSION = "1.0";
public static final String FORWARD_SLASH = "/";
public static final String URI_QUERY_SEPARATOR = "?";
public static final String QUERY_STRING_SEPARATOR = "&";
public static final String QUERY_KEY_VALUE_SEPARATOR = "=";
public static final String ANY = "ANY";
public static final String DEFAULT_PCK_NAME = "default.app.com";
public static final String ALL = "ALL";

@ -40,7 +40,9 @@ import java.sql.SQLException;
import java.sql.Timestamp;
import java.time.Instant;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
@ -207,8 +209,10 @@ public class DAOUtil {
identityServerDTO.setName(rs.getString("NAME"));
identityServerDTO.setDescription(rs.getString("DESCRIPTION"));
identityServerDTO.setUrl(rs.getString("URL"));
identityServerDTO.setApiUrl(rs.getString("API_URI"));
identityServerDTO.setUserName(rs.getString("USERNAME"));
String apiParamsJson = rs.getString("API_PARAMS");
Map<String, String> apiParams = new Gson().fromJson(apiParamsJson, new TypeToken<HashMap<String, String>>() {}.getType());
identityServerDTO.setApiParams(apiParams);
identityServerDTO.setUsername(rs.getString("USERNAME"));
identityServerDTO.setPassword(rs.getString("PASSWORD"));
identityServerDTOS.add(identityServerDTO);
}

@ -33,8 +33,10 @@ import io.swagger.annotations.Tag;
import org.wso2.carbon.apimgt.annotations.api.Scope;
import org.wso2.carbon.apimgt.annotations.api.Scopes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
@ -104,6 +106,22 @@ public interface SPApplicationService {
String SCOPE = "scope";
@GET
@Produces(MediaType.APPLICATION_JSON)
@Path("/identity-servers/identity-service-providers")
@ApiOperation(
produces = MediaType.APPLICATION_JSON,
httpMethod = "GET",
value = "get available identity service providers",
tags = "Identity Server Management",
extensions = {
@Extension(properties = {
@ExtensionProperty(name = SCOPE, value = "perm:app:publisher:service-provider:view")
})
}
)
Response getIdentityServiceProviders();
@GET
@Produces(MediaType.APPLICATION_JSON)
@Path("/identity-servers")
@ -120,6 +138,21 @@ public interface SPApplicationService {
)
Response getIdentityServers();
@Path("/identity-servers/{id}")
@DELETE
@ApiOperation(
produces = MediaType.APPLICATION_JSON,
httpMethod = "DELETE",
value = "get identity server by id",
tags = "Identity Server Management",
extensions = {
@Extension(properties = {
@ExtensionProperty(name = SCOPE, value = "perm:app:publisher:service-provider:connect")
})
}
)
Response deleteIdentityServer(@PathParam("id") int id);
@GET
@Produces(MediaType.APPLICATION_JSON)
@Path("/identity-servers/{id}")
@ -152,6 +185,54 @@ public interface SPApplicationService {
)
Response createIdentityServer(IdentityServerDTO identityServerDTO);
@PUT
@Produces(MediaType.APPLICATION_JSON)
@Path("/identity-servers/{id}")
@ApiOperation(
produces = MediaType.APPLICATION_JSON,
httpMethod = "PUT",
value = "edit existing identity server",
tags = "Identity Server Management",
extensions = {
@Extension(properties = {
@ExtensionProperty(name = SCOPE, value = "perm:app:publisher:service-provider:connect")
})
}
)
Response updateIdentityServer(IdentityServerDTO identityServerDTO, @PathParam("id") int id);
@GET
@Path("/identity-servers/identity-server-name")
@ApiOperation(
produces = MediaType.APPLICATION_JSON,
httpMethod = "GET",
value = "Check if identity server name is already exists",
tags = "Identity Server Management",
extensions = {
@Extension(properties = {
@ExtensionProperty(name = SCOPE, value = "perm:app:publisher:service-provider:view")
})
}
)
Response isIdentityServerNameExists(
@QueryParam("identityServerName") String identityServerName);
@GET
@Path("/identity-servers/identity-server-url")
@ApiOperation(
produces = MediaType.APPLICATION_JSON,
httpMethod = "GET",
value = "Check if identity server url is already exists",
tags = "Identity Server Management",
extensions = {
@Extension(properties = {
@ExtensionProperty(name = SCOPE, value = "perm:app:publisher:service-provider:view")
})
}
)
Response isIdentityServerUrlExists(
@QueryParam("identityServerUrl") String identityServerUrl);
/**
* This method is used to register an APIM application for tenant domain.
*/

@ -18,10 +18,10 @@
package io.entgra.application.mgt.publisher.api.services.impl;
import io.entgra.application.mgt.common.IdentityServer;
import io.entgra.application.mgt.common.IdentityServerResponse;
import io.entgra.application.mgt.common.dto.IdentityServerDTO;
import io.entgra.application.mgt.common.IdentityServerList;
import io.entgra.application.mgt.common.SPApplicationListResponse;
import io.entgra.application.mgt.common.dto.IdentityServiceProviderDTO;
import io.entgra.application.mgt.common.exception.ApplicationManagementException;
import io.entgra.application.mgt.common.exception.RequestValidatingException;
import io.entgra.application.mgt.common.response.Application;
@ -31,13 +31,17 @@ import io.entgra.application.mgt.common.wrapper.CustomAppWrapper;
import io.entgra.application.mgt.common.wrapper.PublicAppWrapper;
import io.entgra.application.mgt.common.wrapper.WebAppWrapper;
import io.entgra.application.mgt.core.exception.BadRequestException;
import io.entgra.application.mgt.core.exception.NotFoundException;
import io.entgra.application.mgt.core.util.APIUtil;
import io.entgra.application.mgt.publisher.api.services.SPApplicationService;
import io.entgra.application.mgt.publisher.api.services.util.SPAppRequestHandlerUtil;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import javax.ws.rs.DELETE;
import javax.ws.rs.DefaultValue;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
@ -49,15 +53,31 @@ import java.util.List;
@Produces(MediaType.APPLICATION_JSON)
@Path("/identity-server-applications")
public class SPApplicationServiceImpl implements SPApplicationService {
private static final Log log = LogFactory.getLog(SPApplicationServiceImpl.class);
@Path("/identity-servers/identity-service-providers")
@GET
@Override
public Response getIdentityServiceProviders() {
SPApplicationManager spAppManager = APIUtil.getSPApplicationManager();
try {
List<IdentityServiceProviderDTO> identityServiceProviders = spAppManager.getIdentityServiceProviders();
return Response.status(Response.Status.OK).entity(identityServiceProviders).build();
} catch (ApplicationManagementException e) {
String msg = "Error occurred while getting identity service providers";
log.error(msg, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
}
}
@Path("/identity-servers")
@GET
@Override
public Response getIdentityServers() {
try {
SPApplicationManager spAppManager = APIUtil.getSPApplicationManager();
List<IdentityServer> identityServers = spAppManager.getIdentityServers();
List<IdentityServerResponse> identityServers = spAppManager.getIdentityServers();
return Response.status(Response.Status.OK).entity(identityServers).build();
} catch (ApplicationManagementException e) {
String errMsg = "Error occurred while trying to merge identity server apps with existing apps";
@ -66,14 +86,37 @@ public class SPApplicationServiceImpl implements SPApplicationService {
}
}
@Path("/identity-servers/{id}")
@DELETE
@Override
public Response deleteIdentityServer(@PathParam("id") int id) {
try {
SPApplicationManager spAppManager = APIUtil.getSPApplicationManager();
spAppManager.deleteIdentityServer(id);
return Response.status(Response.Status.OK).entity("Successfully deleted identity server").build();
} catch (NotFoundException e) {
String msg = "Identity server with the id " + id + " does not exist.";
log.error(msg);
return Response.status(Response.Status.BAD_REQUEST).entity(msg).build();
} catch (ApplicationManagementException e) {
String errMsg = "Error occurred while trying to merge identity server apps with existing apps";
log.error(errMsg, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(errMsg).build();
}
}
@Path("/identity-servers/{id}")
@GET
@Override
public Response getIdentityServer(@PathParam("id") int id) {
try {
SPApplicationManager spAppManager = APIUtil.getSPApplicationManager();
IdentityServer identityServer = spAppManager.getIdentityServer(id);
IdentityServerResponse identityServer = spAppManager.getIdentityServerResponse(id);
return Response.status(Response.Status.OK).entity(identityServer).build();
} catch (NotFoundException e) {
String msg = "Identity server with the id " + id + " does not exist.";
log.error(msg);
return Response.status(Response.Status.BAD_REQUEST).entity(msg).build();
} catch (ApplicationManagementException e) {
String errMsg = "Error occurred while trying to merge identity server apps with existing apps";
log.error(errMsg, e);
@ -81,14 +124,96 @@ public class SPApplicationServiceImpl implements SPApplicationService {
}
}
@Path("/identity-servers/{id}")
@PUT
@Override
public Response updateIdentityServer(IdentityServerDTO identityServerDTO, @PathParam("id") int id) {
try {
SPApplicationManager spAppManager = APIUtil.getSPApplicationManager();
IdentityServerResponse identityServerResponse = spAppManager.updateIdentityServer(identityServerDTO, id);
return Response.status(Response.Status.OK).entity(identityServerResponse).build();
} catch (NotFoundException e) {
String msg = "Identity server with the id " + id + " does not exist.";
log.error(msg);
return Response.status(Response.Status.BAD_REQUEST).entity(msg).build();
} catch (BadRequestException e) {
String errMsg = "Identity server request payload is invalid";
log.error(errMsg, e);
return Response.status(Response.Status.BAD_REQUEST).entity(errMsg).build();
} catch (ApplicationManagementException e) {
String errMsg = "Error occurred while trying to merge identity server apps with existing apps";
log.error(errMsg, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(errMsg).build();
}
}
@Path("/identity-servers")
@POST
@Override
public Response createIdentityServer(IdentityServerDTO identityServerDTO) {
try {
SPApplicationManager spAppManager = APIUtil.getSPApplicationManager();
IdentityServer identityServer = spAppManager.createIdentityServer(identityServerDTO);
IdentityServerResponse identityServer = spAppManager.createIdentityServer(identityServerDTO);
return Response.status(Response.Status.CREATED).entity(identityServer).build();
} catch (BadRequestException e) {
String errMsg = "Identity server request payload is invalid";
log.error(errMsg, e);
return Response.status(Response.Status.BAD_REQUEST).entity(errMsg).build();
} catch (ApplicationManagementException e) {
String errMsg = "Error occurred while trying to merge identity server apps with existing apps";
log.error(errMsg, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(errMsg).build();
}
}
@GET
@Path("/identity-servers/identity-server-name")
@Override
public Response isIdentityServerNameExists(
@QueryParam("identityServerName") String identityServerName) {
try {
if (identityServerName == null) {
String msg = "Invalid identity server name, identityServerName query param cannot be empty/null.";
log.error(msg);
return Response.status(Response.Status.BAD_REQUEST).build();
}
SPApplicationManager spAppManager = APIUtil.getSPApplicationManager();
if (spAppManager.isIdentityServerNameExist(identityServerName)) {
return Response.status(Response.Status.CONFLICT).build();
}
return Response.status(Response.Status.OK).build();
} catch (BadRequestException e) {
String errMsg = "Identity server request payload is invalid";
log.error(errMsg, e);
return Response.status(Response.Status.BAD_REQUEST).entity(errMsg).build();
} catch (ApplicationManagementException e) {
String errMsg = "Error occurred while trying to merge identity server apps with existing apps";
log.error(errMsg, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(errMsg).build();
}
}
@GET
@Path("/identity-servers/identity-server-url")
@Override
public Response isIdentityServerUrlExists(
@QueryParam("identityServerUrl") String identityServerUrl) {
try {
if (identityServerUrl == null) {
String msg = "Invalid identity server url, identityServerName query param cannot be empty/null.";
log.error(msg);
return Response.status(Response.Status.BAD_REQUEST).build();
}
SPApplicationManager spAppManager = APIUtil.getSPApplicationManager();
if (spAppManager.isIdentityServerUrlExist(identityServerUrl)) {
return Response.status(Response.Status.CONFLICT).build();
}
return Response.status(Response.Status.OK).build();
} catch (BadRequestException e) {
String errMsg = "Identity server request payload is invalid";
log.error(errMsg, e);
return Response.status(Response.Status.BAD_REQUEST).entity(errMsg).build();
} catch (ApplicationManagementException e) {
String errMsg = "Error occurred while trying to merge identity server apps with existing apps";
log.error(errMsg, e);
@ -99,14 +224,16 @@ public class SPApplicationServiceImpl implements SPApplicationService {
@Path("/{identity-server-id}/service-providers")
@GET
@Override
public Response getServiceProviders(@QueryParam("limit") Integer limit, @QueryParam("offset") Integer offset,
public Response getServiceProviders(@DefaultValue("30") @QueryParam("limit") Integer limit,@DefaultValue("0") @QueryParam("offset") Integer offset,
@PathParam("identity-server-id") int identityServerId) {
try {
SPApplicationManager spAppManager = APIUtil.getSPApplicationManager();
SPApplicationListResponse applications = SPAppRequestHandlerUtil.
retrieveSPApplications(identityServerId, limit, offset);
spAppManager.addExistingApps(identityServerId, applications.getApplications());
SPApplicationListResponse applications = spAppManager.retrieveSPApplicationFromIdentityServer(identityServerId, limit, offset);
return Response.status(Response.Status.OK).entity(applications).build();
} catch (NotFoundException e) {
String errMsg = "No Identity server exist with the id: " + identityServerId;
log.error(errMsg, e);
return Response.status(Response.Status.BAD_REQUEST).entity(errMsg).build();
} catch (ApplicationManagementException e) {
String errMsg = "Error occurred while trying to merge identity server apps with existing apps";
log.error(errMsg, e);
@ -121,9 +248,16 @@ public class SPApplicationServiceImpl implements SPApplicationService {
@PathParam("service-provider-id") String serviceProviderId, List<Integer> appIds) {
SPApplicationManager spApplicationManager = APIUtil.getSPApplicationManager();
try {
validateServiceProviderUID(identityServerId, serviceProviderId);
spApplicationManager.validateAttachAppsRequest(identityServerId, appIds);
spApplicationManager.validateAttachAppsRequest(identityServerId, serviceProviderId, appIds);
spApplicationManager.attachSPApplications(identityServerId, serviceProviderId, appIds);
} catch (NotFoundException e) {
String msg = "No identity server exist with the id " + identityServerId;
log.error(msg, e);
return Response.status(Response.Status.BAD_REQUEST).entity(msg).build();
} catch (BadRequestException e) {
String msg = "Invalid appIds provided";
log.error(msg, e);
return Response.status(Response.Status.BAD_REQUEST).entity(msg).build();
} catch (ApplicationManagementException e) {
String msg = "Error occurred while attaching apps to service provider with the id" + serviceProviderId;
log.error(msg, e);
@ -139,9 +273,16 @@ public class SPApplicationServiceImpl implements SPApplicationService {
@PathParam("service-provider-id") String serviceProviderId, List<Integer> appIds) {
SPApplicationManager spApplicationManager = APIUtil.getSPApplicationManager();
try {
validateServiceProviderUID(identityServerId, serviceProviderId);
spApplicationManager.validateDetachAppsRequest(identityServerId, serviceProviderId, appIds);
spApplicationManager.detachSPApplications(identityServerId, serviceProviderId, appIds);
} catch (NotFoundException e) {
String msg = "No identity server exist with the id " + identityServerId;
log.error(msg, e);
return Response.status(Response.Status.BAD_REQUEST).entity(msg).build();
} catch (BadRequestException e) {
String msg = "Invalid appIds provided";
log.error(msg, e);
return Response.status(Response.Status.BAD_REQUEST).entity(msg).build();
} catch (ApplicationManagementException e) {
String msg = "Error occurred while attaching apps to service provider with the id" + serviceProviderId;
log.error(msg, e);
@ -193,10 +334,13 @@ public class SPApplicationServiceImpl implements SPApplicationService {
*/
private <T> Response createSPApplication(int identityServerId, String spUID, T appWrapper) {
try {
validateServiceProviderUID(identityServerId, spUID);
SPApplicationManager spApplicationManager = APIUtil.getSPApplicationManager();
Application createdApp = spApplicationManager.createSPApplication(appWrapper, identityServerId, spUID);
return Response.status(Response.Status.CREATED).entity(createdApp).build();
} catch (NotFoundException e) {
String msg = "No identity server exist with the id " + identityServerId;
log.error(msg, e);
return Response.status(Response.Status.BAD_REQUEST).entity(msg).build();
} catch (BadRequestException e) {
String msg = "Found incompatible payload with create service provider app request.";
log.error(msg, e);
@ -213,28 +357,4 @@ public class SPApplicationServiceImpl implements SPApplicationService {
}
}
/**
* Responsible for validating service provider in requests
*
* @param identityServerId identity server id of the service provider
* @param spUID uid of the service provider
* @throws ApplicationManagementException
*/
private void validateServiceProviderUID(int identityServerId, String spUID) throws
ApplicationManagementException {
try {
boolean isSPAppExists = SPAppRequestHandlerUtil.
isSPApplicationExist(identityServerId, spUID);
if (!isSPAppExists) {
String errMsg = "Service provider with the uid " + spUID + " does not exist.";
log.error(errMsg);
throw new BadRequestException(errMsg);
}
} catch (ApplicationManagementException e) {
String errMsg = "Error occurred while trying to validate service provider uid";
log.error(errMsg, e);
throw new ApplicationManagementException(errMsg, e);
}
}
}

@ -1,177 +0,0 @@
/*
* Copyright (c) 2022, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you 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 io.entgra.application.mgt.publisher.api.services.util;
import com.google.gson.Gson;
import io.entgra.application.mgt.common.IdentityServer;
import io.entgra.application.mgt.common.SPApplication;
import io.entgra.application.mgt.common.SPApplicationListResponse;
import io.entgra.application.mgt.common.exception.ApplicationManagementException;
import io.entgra.application.mgt.common.services.SPApplicationManager;
import io.entgra.application.mgt.core.config.ConfigurationManager;
import io.entgra.application.mgt.core.config.IdentityServerDetail;
import io.entgra.application.mgt.core.util.APIUtil;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.wso2.carbon.device.mgt.core.common.util.HttpUtil;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.UriBuilder;
import java.io.IOException;
import java.net.URI;
public class SPAppRequestHandlerUtil {
private static final Log log = LogFactory.getLog(SPAppRequestHandlerUtil.class);
/**
* Check if service provider application exists
*
* @param identityServerId id of the identity server
* @param spAppId uid of the service provider
* @return if service provider exist
* @throws ApplicationManagementException
*/
public static boolean isSPApplicationExist(int identityServerId, String spAppId) throws ApplicationManagementException {
SPApplication application = retrieveSPApplication(identityServerId, spAppId);
return application != null;
}
/**
* Get service provider by identity server id and service provider uid
* @param identityServerId id of the identity server
* @param spAppId uid of service provider to be retrieved
* @return {@link SPApplication}
* @throws ApplicationManagementException
*/
public static SPApplication retrieveSPApplication(int identityServerId, String spAppId)
throws ApplicationManagementException {
IdentityServer identityServer = getIdentityServer(identityServerId);
HttpGet req = new HttpGet();
URI uri = HttpUtil.createURI(getSPApplicationsAPI(identityServer));
uri = UriBuilder.fromUri(uri).path(spAppId).build();
req.setURI(uri);
CloseableHttpClient client = HttpClients.createDefault();
try {
HttpResponse response = invokeISAPI(identityServer, client, req);
String responseBody = HttpUtil.getResponseString(response);
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
return new Gson().fromJson(responseBody,
SPApplication.class);
}
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_NOT_FOUND) {
return null;
}
String msg = "Error occurred while calling SP Applications API";
log.error(msg);
throw new ApplicationManagementException(msg);
} catch (IOException e) {
String msg = "Error occurred while calling SP Applications API";
log.error(msg, e);
throw new ApplicationManagementException(msg, e);
} finally {
try {
client.close();
} catch (IOException e) {
log.error("Error occurred while closing http connection");
}
}
}
/**
* Retrieve service provider apps from identity server
*
* @param identityServerId id of the identity server
* @return {@link SPApplicationListResponse}
* @throws ApplicationManagementException
*/
public static SPApplicationListResponse retrieveSPApplications(int identityServerId, Integer limit, Integer offset)
throws ApplicationManagementException {
IdentityServer identityServer = getIdentityServer(identityServerId);
HttpGet req = new HttpGet();
URI uri = HttpUtil.createURI(getSPApplicationsAPI(identityServer));
UriBuilder uriBuilder = UriBuilder.fromUri(uri);
if (limit != null) {
uriBuilder = uriBuilder.queryParam(io.entgra.application.mgt.core.util.Constants.LIMIT_QUERY_PARAM, limit);
}
if (offset != null) {
uriBuilder = uriBuilder.queryParam(io.entgra.application.mgt.core.util.Constants.OFFSET_QUERY_PARAM, offset);
}
uri = uriBuilder.build();
req.setURI(uri);
CloseableHttpClient client = HttpClients.createDefault();
try {
HttpResponse response = invokeISAPI(identityServer, client, req);
String responseBody = HttpUtil.getResponseString(response);
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
return new Gson().fromJson(responseBody,
SPApplicationListResponse.class);
}
String msg = "Error occurred while calling SP Applications API";
log.error(msg);
throw new ApplicationManagementException(msg);
} catch (IOException e) {
String msg = "Error occurred while calling SP Applications API";
log.error(msg, e);
throw new ApplicationManagementException(msg, e);
} finally {
try {
client.close();
} catch (IOException e) {
log.error("Error occurred while closing http connection");
}
}
}
/**
*
* @param identityServerId id of the identity server
* @return {@link IdentityServer}
* @throws ApplicationManagementException
*/
public static IdentityServer getIdentityServer(int identityServerId) throws ApplicationManagementException {
SPApplicationManager spApplicationManager = APIUtil.getSPApplicationManager();
return spApplicationManager.getIdentityServer(identityServerId);
}
private static HttpResponse invokeISAPI(IdentityServer identityServer, HttpClient client, HttpRequestBase request) throws IOException {
setBasicAuthHeader(identityServer, request);
return client.execute(request);
}
private static void setBasicAuthHeader(IdentityServer identityServer, HttpRequestBase request) {
String basicAuthHeader = HttpUtil.getBasicAuthBase64Header(identityServer.getUserName(),
identityServer.getPassword());
request.setHeader(HttpHeaders.AUTHORIZATION, basicAuthHeader);
}
private static String getSPApplicationsAPI(IdentityServer identityServer) {
IdentityServerDetail identityServerDetail = ConfigurationManager.getInstance().getIdentityServerConfiguration().
getIdentityServerDetailByProviderName(identityServer.getProviderName());
return identityServer.getApiUrl() + identityServerDetail.getServiceProvidersAPIContextPath();
}
}
Loading…
Cancel
Save