Search in sources :

Example 51 with Server

use of org.wso2.broker.amqp.Server in project carbon-apimgt by wso2.

the class InMemoryAPIDeployer method deployAllAPIsAtGatewayStartup.

/**
 * Deploy an API in the gateway using the deployAPI method in gateway admin.
 *
 * @param assignedGatewayLabels - The labels which the gateway subscribed to
 * @param tenantDomain          tenantDomain of API.
 * @return True if all API artifacts retrieved from the storage and successfully deployed without any error. else
 * false
 */
public boolean deployAllAPIsAtGatewayStartup(Set<String> assignedGatewayLabels, String tenantDomain) throws ArtifactSynchronizerException {
    boolean result = false;
    if (gatewayArtifactSynchronizerProperties.isRetrieveFromStorageEnabled()) {
        if (artifactRetriever != null) {
            try {
                int errorCount = 0;
                String labelString = String.join("|", assignedGatewayLabels);
                String encodedString = Base64.encodeBase64URLSafeString(labelString.getBytes());
                APIGatewayAdmin apiGatewayAdmin = new APIGatewayAdmin();
                MessageContext.setCurrentMessageContext(org.wso2.carbon.apimgt.gateway.utils.GatewayUtils.createAxis2MessageContext());
                PrivilegedCarbonContext.startTenantFlow();
                PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(tenantDomain, true);
                List<String> gatewayRuntimeArtifacts = ServiceReferenceHolder.getInstance().getArtifactRetriever().retrieveAllArtifacts(encodedString, tenantDomain);
                if (gatewayRuntimeArtifacts.size() == 0) {
                    return true;
                }
                for (String runtimeArtifact : gatewayRuntimeArtifacts) {
                    GatewayAPIDTO gatewayAPIDTO = null;
                    try {
                        if (StringUtils.isNotEmpty(runtimeArtifact)) {
                            gatewayAPIDTO = new Gson().fromJson(runtimeArtifact, GatewayAPIDTO.class);
                            log.info("Deploying synapse artifacts of " + gatewayAPIDTO.getName());
                            apiGatewayAdmin.deployAPI(gatewayAPIDTO);
                            addDeployedCertificatesToAPIAssociation(gatewayAPIDTO);
                            addDeployedGraphqlQLToAPI(gatewayAPIDTO);
                            DataHolder.getInstance().addKeyManagerToAPIMapping(gatewayAPIDTO.getApiId(), gatewayAPIDTO.getKeyManagers());
                        }
                    } catch (AxisFault axisFault) {
                        log.error("Error in deploying " + gatewayAPIDTO.getName() + " to the Gateway ", axisFault);
                        errorCount++;
                    }
                }
                // reload dynamic profiles to avoid delays in loading certs in mutual ssl enabled APIs upon
                // server restart
                DynamicProfileReloaderHolder.getInstance().reloadAllHandlers();
                if (debugEnabled) {
                    log.debug("APIs deployed in gateway with the labels of " + labelString);
                }
                result = true;
                // Setting the result to false only if all the API deployments are failed
                if (gatewayRuntimeArtifacts.size() == errorCount) {
                    return false;
                }
            } catch (ArtifactSynchronizerException | AxisFault e) {
                String msg = "Error deploying APIs to the Gateway ";
                log.error(msg, e);
                return false;
            } finally {
                MessageContext.destroyCurrentMessageContext();
                PrivilegedCarbonContext.endTenantFlow();
            }
        } else {
            String msg = "Artifact retriever not found";
            log.error(msg);
            throw new ArtifactSynchronizerException(msg);
        }
    }
    return result;
}
Also used : GatewayAPIDTO(org.wso2.carbon.apimgt.api.gateway.GatewayAPIDTO) AxisFault(org.apache.axis2.AxisFault) ArtifactSynchronizerException(org.wso2.carbon.apimgt.impl.gatewayartifactsynchronizer.exception.ArtifactSynchronizerException) Gson(com.google.gson.Gson) APIGatewayAdmin(org.wso2.carbon.apimgt.gateway.service.APIGatewayAdmin)

Example 52 with Server

use of org.wso2.broker.amqp.Server in project carbon-apimgt by wso2.

the class CertificateMgtDAO method getCertificates.

/**
 * Method to retrieve certificate metadata from db for specific tenant which matches alias or endpoint.
 * From alias and endpoint, only one parameter is required.
 *
 * @param tenantId : The id of the tenant which the certificate belongs to.
 * @param alias    : Alias for the certificate. (Optional)
 * @param endpoint : The endpoint/ server url which the certificate is mapped to. (Optional)
 * @return : A CertificateMetadataDTO object if the certificate is retrieved successfully, null otherwise.
 */
public List<CertificateMetadataDTO> getCertificates(String alias, String endpoint, int tenantId) throws CertificateManagementException {
    String getCertQuery;
    CertificateMetadataDTO certificateMetadataDTO;
    List<CertificateMetadataDTO> certificateMetadataList = new ArrayList<>();
    if (StringUtils.isNotEmpty(alias) || StringUtils.isNotEmpty(endpoint)) {
        if (log.isDebugEnabled()) {
            log.debug("The alias and endpoint are not empty. Invoking the search query with parameters " + "alias = " + alias + " endpoint = " + endpoint);
        }
        getCertQuery = SQLConstants.CertificateConstants.GET_CERTIFICATE_TENANT;
    } else {
        if (log.isDebugEnabled()) {
            log.debug("The alias and endpoint are empty. Invoking the get all certificates for tenant " + tenantId);
        }
        getCertQuery = SQLConstants.CertificateConstants.GET_CERTIFICATES;
    }
    try (Connection connection = APIMgtDBUtil.getConnection()) {
        try (PreparedStatement preparedStatement = connection.prepareStatement(getCertQuery)) {
            preparedStatement.setInt(1, tenantId);
            if (StringUtils.isNotEmpty(alias) || StringUtils.isNotEmpty(endpoint)) {
                preparedStatement.setString(2, alias);
                preparedStatement.setString(3, endpoint);
            }
            try (ResultSet resultSet = preparedStatement.executeQuery()) {
                while (resultSet.next()) {
                    certificateMetadataDTO = new CertificateMetadataDTO();
                    certificateMetadataDTO.setAlias(resultSet.getString("ALIAS"));
                    certificateMetadataDTO.setEndpoint(resultSet.getString("END_POINT"));
                    try (InputStream certificate = resultSet.getBinaryStream("CERTIFICATE")) {
                        certificateMetadataDTO.setCertificate(APIMgtDBUtil.getStringFromInputStream(certificate));
                    }
                    certificateMetadataList.add(certificateMetadataDTO);
                }
            }
        }
    } catch (SQLException | IOException e) {
        handleException("Error while retrieving certificate metadata.", e);
    }
    return certificateMetadataList;
}
Also used : CertificateMetadataDTO(org.wso2.carbon.apimgt.api.dto.CertificateMetadataDTO) SQLException(java.sql.SQLException) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) ArrayList(java.util.ArrayList) Connection(java.sql.Connection) ResultSet(java.sql.ResultSet) PreparedStatement(java.sql.PreparedStatement) IOException(java.io.IOException)

Example 53 with Server

use of org.wso2.broker.amqp.Server in project carbon-apimgt by wso2.

the class CertificateMgtDAO method addCertificate.

/**
 * Method to add a new certificate to the database.
 *
 * @param alias    : Alias for the new certificate.
 * @param endpoint : The endpoint/ server url which the certificate will be mapped to.
 * @param tenantId : The Id of the tenant who uploaded the certificate.
 * @return : True if the information is added successfully, false otherwise.
 * @throws CertificateManagementException if existing entry is found for the given endpoint or alias.
 */
public boolean addCertificate(String certificate, String alias, String endpoint, int tenantId) throws CertificateManagementException, CertificateAliasExistsException {
    boolean result = false;
    String addCertQuery = SQLConstants.CertificateConstants.INSERT_CERTIFICATE;
    try (Connection connection = APIMgtDBUtil.getConnection()) {
        boolean certificateExist = isCertificateExist(connection, alias, tenantId);
        if (certificateExist) {
            if (log.isDebugEnabled()) {
                log.debug("A certificate for the endpoint " + endpoint + " has already added with alias " + alias);
            }
            String message = "Alias or Endpoint exists in the database!";
            throw new CertificateAliasExistsException(message);
        }
        connection.setAutoCommit(false);
        try (PreparedStatement preparedStatement = connection.prepareStatement(addCertQuery)) {
            preparedStatement.setInt(1, tenantId);
            preparedStatement.setString(2, endpoint);
            preparedStatement.setString(3, alias);
            preparedStatement.setBinaryStream(4, getInputStream(certificate));
            result = preparedStatement.executeUpdate() == 1;
            connection.commit();
        } catch (SQLException e) {
            handleConnectionRollBack(connection);
            if (log.isDebugEnabled()) {
                log.debug("Error occurred while adding certificate metadata to database.", e);
            }
            handleException("Error while persisting certificate metadata.", e);
        }
    } catch (SQLException e) {
        handleException("Error while retrieving connection", e);
    }
    return result;
}
Also used : SQLException(java.sql.SQLException) CertificateAliasExistsException(org.wso2.carbon.apimgt.impl.certificatemgt.exceptions.CertificateAliasExistsException) Connection(java.sql.Connection) PreparedStatement(java.sql.PreparedStatement)

Example 54 with Server

use of org.wso2.broker.amqp.Server in project carbon-apimgt by wso2.

the class CertificateMgtDAO method getCertificate.

/**
 * Method to retrieve certificate metadata from db for specific tenant which matches alias or endpoint.
 * From alias and endpoint, only one parameter is required.
 *
 * @param tenantId : The id of the tenant which the certificate belongs to.
 * @param alias    : Alias for the certificate. (Optional)
 * @param endpoint : The endpoint/ server url which the certificate is mapped to. (Optional)
 * @return : A CertificateMetadataDTO object if the certificate is retrieved successfully, null otherwise.
 */
public CertificateMetadataDTO getCertificate(String alias, String endpoint, int tenantId) throws CertificateManagementException {
    String getCertQuery;
    getCertQuery = SQLConstants.CertificateConstants.GET_CERTIFICATE_TENANT_ALIAS_ENDPOINT;
    try (Connection connection = APIMgtDBUtil.getConnection()) {
        try (PreparedStatement preparedStatement = connection.prepareStatement(getCertQuery)) {
            preparedStatement.setInt(1, tenantId);
            preparedStatement.setString(2, alias);
            preparedStatement.setString(3, endpoint);
            try (ResultSet resultSet = preparedStatement.executeQuery()) {
                if (resultSet.next()) {
                    CertificateMetadataDTO certificateMetadataDTO = new CertificateMetadataDTO();
                    certificateMetadataDTO.setAlias(resultSet.getString("ALIAS"));
                    certificateMetadataDTO.setEndpoint(resultSet.getString("END_POINT"));
                    try (InputStream certificate = resultSet.getBinaryStream("CERTIFICATE")) {
                        certificateMetadataDTO.setCertificate(APIMgtDBUtil.getStringFromInputStream(certificate));
                    }
                    return certificateMetadataDTO;
                }
            }
        }
    } catch (SQLException | IOException e) {
        handleException("Error while retrieving certificate metadata.", e);
    }
    throw new CertificateManagementException("Certificate didn't exist with alias" + alias);
}
Also used : CertificateMetadataDTO(org.wso2.carbon.apimgt.api.dto.CertificateMetadataDTO) SQLException(java.sql.SQLException) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) Connection(java.sql.Connection) ResultSet(java.sql.ResultSet) CertificateManagementException(org.wso2.carbon.apimgt.impl.certificatemgt.exceptions.CertificateManagementException) PreparedStatement(java.sql.PreparedStatement) IOException(java.io.IOException)

Example 55 with Server

use of org.wso2.broker.amqp.Server in project carbon-apimgt by wso2.

the class APIManagerConfiguration method setEnvironmentConfig.

/**
 * Set property values for each gateway environments defined in the api-manager.xml config file
 *
 * @param environmentElem OMElement of a single environment in the gateway environments list
 */
void setEnvironmentConfig(OMElement environmentElem) throws APIManagementException {
    Environment environment = new Environment();
    environment.setType(environmentElem.getAttributeValue(new QName("type")));
    String showInConsole = environmentElem.getAttributeValue(new QName("api-console"));
    if (showInConsole != null) {
        environment.setShowInConsole(Boolean.parseBoolean(showInConsole));
    } else {
        environment.setShowInConsole(true);
    }
    String isDefault = environmentElem.getAttributeValue(new QName("isDefault"));
    if (isDefault != null) {
        environment.setDefault(Boolean.parseBoolean(isDefault));
    } else {
        environment.setDefault(false);
    }
    environment.setName(APIUtil.replaceSystemProperty(environmentElem.getFirstChildWithName(new QName(APIConstants.API_GATEWAY_NAME)).getText()));
    environment.setDisplayName(APIUtil.replaceSystemProperty(environmentElem.getFirstChildWithName(new QName(APIConstants.API_GATEWAY_DISPLAY_NAME)).getText()));
    if (StringUtils.isEmpty(environment.getDisplayName())) {
        environment.setDisplayName(environment.getName());
    }
    environment.setServerURL(APIUtil.replaceSystemProperty(environmentElem.getFirstChildWithName(new QName(APIConstants.API_GATEWAY_SERVER_URL)).getText()));
    environment.setUserName(APIUtil.replaceSystemProperty(environmentElem.getFirstChildWithName(new QName(APIConstants.API_GATEWAY_USERNAME)).getText()));
    OMElement passwordElement = environmentElem.getFirstChildWithName(new QName(APIConstants.API_GATEWAY_PASSWORD));
    String resolvedPassword = MiscellaneousUtil.resolve(passwordElement, secretResolver);
    environment.setPassword(APIUtil.replaceSystemProperty(resolvedPassword));
    String provider = environmentElem.getFirstChildWithName(new QName(APIConstants.API_GATEWAY_PROVIDER)).getText();
    if (StringUtils.isNotEmpty(provider)) {
        environment.setProvider(APIUtil.replaceSystemProperty(provider));
    } else {
        environment.setProvider(APIUtil.replaceSystemProperty(DEFAULT_PROVIDER));
    }
    environment.setApiGatewayEndpoint(APIUtil.replaceSystemProperty(environmentElem.getFirstChildWithName(new QName(APIConstants.API_GATEWAY_ENDPOINT)).getText()));
    OMElement websocketGatewayEndpoint = environmentElem.getFirstChildWithName(new QName(APIConstants.API_WEBSOCKET_GATEWAY_ENDPOINT));
    if (websocketGatewayEndpoint != null) {
        environment.setWebsocketGatewayEndpoint(APIUtil.replaceSystemProperty(websocketGatewayEndpoint.getText()));
    } else {
        environment.setWebsocketGatewayEndpoint(WEBSOCKET_DEFAULT_GATEWAY_URL);
    }
    OMElement webSubGatewayEndpoint = environmentElem.getFirstChildWithName(new QName(APIConstants.API_WEBSUB_GATEWAY_ENDPOINT));
    if (webSubGatewayEndpoint != null) {
        environment.setWebSubGatewayEndpoint(APIUtil.replaceSystemProperty(webSubGatewayEndpoint.getText()));
    } else {
        environment.setWebSubGatewayEndpoint(WEBSUB_DEFAULT_GATEWAY_URL);
    }
    OMElement description = environmentElem.getFirstChildWithName(new QName("Description"));
    if (description != null) {
        environment.setDescription(description.getText());
    } else {
        environment.setDescription("");
    }
    environment.setReadOnly(true);
    List<VHost> vhosts = new LinkedList<>();
    environment.setVhosts(vhosts);
    environment.setEndpointsAsVhost();
    Iterator vhostIterator = environmentElem.getFirstChildWithName(new QName(APIConstants.API_GATEWAY_VIRTUAL_HOSTS)).getChildrenWithLocalName(APIConstants.API_GATEWAY_VIRTUAL_HOST);
    while (vhostIterator.hasNext()) {
        OMElement vhostElem = (OMElement) vhostIterator.next();
        String httpEp = APIUtil.replaceSystemProperty(vhostElem.getFirstChildWithName(new QName(APIConstants.API_GATEWAY_VIRTUAL_HOST_HTTP_ENDPOINT)).getText());
        String httpsEp = APIUtil.replaceSystemProperty(vhostElem.getFirstChildWithName(new QName(APIConstants.API_GATEWAY_VIRTUAL_HOST_HTTPS_ENDPOINT)).getText());
        String wsEp = APIUtil.replaceSystemProperty(vhostElem.getFirstChildWithName(new QName(APIConstants.API_GATEWAY_VIRTUAL_HOST_WS_ENDPOINT)).getText());
        String wssEp = APIUtil.replaceSystemProperty(vhostElem.getFirstChildWithName(new QName(APIConstants.API_GATEWAY_VIRTUAL_HOST_WSS_ENDPOINT)).getText());
        String webSubHttpEp = APIUtil.replaceSystemProperty(vhostElem.getFirstChildWithName(new QName(APIConstants.API_GATEWAY_VIRTUAL_HOST_WEBSUB_HTTP_ENDPOINT)).getText());
        String webSubHttpsEp = APIUtil.replaceSystemProperty(vhostElem.getFirstChildWithName(new QName(APIConstants.API_GATEWAY_VIRTUAL_HOST_WEBSUB_HTTPS_ENDPOINT)).getText());
        // Prefix websub endpoints with 'websub_' so that the endpoint URL
        // would begin with: 'websub_http://', since API type is identified by the URL protocol below.
        webSubHttpEp = "websub_" + webSubHttpEp;
        webSubHttpsEp = "websub_" + webSubHttpsEp;
        VHost vhost = VHost.fromEndpointUrls(new String[] { httpEp, httpsEp, wsEp, wssEp, webSubHttpEp, webSubHttpsEp });
        vhosts.add(vhost);
    }
    OMElement properties = environmentElem.getFirstChildWithName(new QName(APIConstants.API_GATEWAY_ADDITIONAL_PROPERTIES));
    Map<String, String> additionalProperties = new HashMap<>();
    if (properties != null) {
        Iterator gatewayAdditionalProperties = properties.getChildrenWithLocalName(APIConstants.API_GATEWAY_ADDITIONAL_PROPERTY);
        while (gatewayAdditionalProperties.hasNext()) {
            OMElement propertyElem = (OMElement) gatewayAdditionalProperties.next();
            String propName = propertyElem.getAttributeValue(new QName("name"));
            String resolvedValue = MiscellaneousUtil.resolve(propertyElem, secretResolver);
            additionalProperties.put(propName, resolvedValue);
        }
    }
    environment.setAdditionalProperties(additionalProperties);
    if (!apiGatewayEnvironments.containsKey(environment.getName())) {
        apiGatewayEnvironments.put(environment.getName(), environment);
    } else {
        // This will happen only on server startup therefore we log and continue the startup
        log.error("Duplicate environment name found in api-manager.xml " + environment.getName());
    }
}
Also used : VHost(org.wso2.carbon.apimgt.api.model.VHost) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) QName(javax.xml.namespace.QName) Iterator(java.util.Iterator) Environment(org.wso2.carbon.apimgt.api.model.Environment) RecommendationEnvironment(org.wso2.carbon.apimgt.impl.recommendationmgt.RecommendationEnvironment) OMElement(org.apache.axiom.om.OMElement) LinkedList(java.util.LinkedList)

Aggregations

APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)28 IOException (java.io.IOException)19 ArrayList (java.util.ArrayList)14 HashMap (java.util.HashMap)14 APIManagementException (org.wso2.carbon.apimgt.core.exception.APIManagementException)10 File (java.io.File)8 JSONObject (org.json.simple.JSONObject)7 MalformedURLException (java.net.MalformedURLException)6 URL (java.net.URL)6 OMElement (org.apache.axiom.om.OMElement)6 JSONObject (org.json.JSONObject)6 URI (java.net.URI)5 URISyntaxException (java.net.URISyntaxException)5 Test (org.testng.annotations.Test)5 KeyManager (org.wso2.carbon.apimgt.api.model.KeyManager)5 APIMgtAdminService (org.wso2.carbon.apimgt.core.api.APIMgtAdminService)5 BadRequestException (org.wso2.charon3.core.exceptions.BadRequestException)5 Connection (java.sql.Connection)4 SQLException (java.sql.SQLException)4 APIProvider (org.wso2.carbon.apimgt.api.APIProvider)4