Search in sources :

Example 1 with Status

use of org.wso2.balana.ctx.Status in project product-mi-tooling by wso2.

the class GroupsApi method updateLogLevelByNodeId.

@PATCH
@Path("/{group-id}/log-configs/nodes/{node-id}")
@Consumes({ "application/json" })
@Produces({ "application/json" })
@Operation(summary = "Update log level by nodeId", description = "", tags = { "logConfigs" })
@ApiResponses(value = { @ApiResponse(responseCode = "200", description = "Logger update status", content = @Content(schema = @Schema(implementation = SuccessStatus.class))), @ApiResponse(responseCode = "200", description = "Unexpected error", content = @Content(schema = @Schema(implementation = Error.class))) })
public Response updateLogLevelByNodeId(@PathParam("group-id") @Parameter(description = "Group ID of the node") String groupId, @PathParam("node-id") @Parameter(description = "NodeId") String nodeId, @Valid LogConfigUpdateRequest request) throws ManagementApiException {
    LogConfigDelegate logConfigDelegate = new LogConfigDelegate();
    Ack ack = logConfigDelegate.updateLogLevelByNodeId(groupId, nodeId, request);
    return Response.ok().entity(ack).build();
}
Also used : LogConfigDelegate(org.wso2.ei.dashboard.micro.integrator.delegates.LogConfigDelegate) Ack(org.wso2.ei.dashboard.core.rest.model.Ack) Operation(io.swagger.v3.oas.annotations.Operation) ApiResponses(io.swagger.v3.oas.annotations.responses.ApiResponses)

Example 2 with Status

use of org.wso2.balana.ctx.Status in project product-mi-tooling by wso2.

the class GroupsApi method addLogger.

@POST
@Path("/{group-id}/log-configs")
@Consumes({ "application/json" })
@Produces({ "application/json" })
@Operation(summary = "Add logger", description = "", tags = { "logConfigs" })
@ApiResponses(value = { @ApiResponse(responseCode = "200", description = "Logger insert status", content = @Content(schema = @Schema(implementation = SuccessStatus.class))), @ApiResponse(responseCode = "200", description = "Unexpected error", content = @Content(schema = @Schema(implementation = Error.class))) })
public Response addLogger(@PathParam("group-id") @Parameter(description = "Group ID of the node") String groupId, @Valid LogConfigAddRequest request) throws ManagementApiException {
    LogConfigDelegate logConfigDelegate = new LogConfigDelegate();
    Ack ack = logConfigDelegate.addLogger(groupId, request);
    Response.ResponseBuilder responseBuilder = Response.ok().entity(ack);
    HttpUtils.setHeaders(responseBuilder);
    return responseBuilder.build();
}
Also used : Response(javax.ws.rs.core.Response) ApiResponse(io.swagger.v3.oas.annotations.responses.ApiResponse) LogConfigDelegate(org.wso2.ei.dashboard.micro.integrator.delegates.LogConfigDelegate) Ack(org.wso2.ei.dashboard.core.rest.model.Ack) Operation(io.swagger.v3.oas.annotations.Operation) ApiResponses(io.swagger.v3.oas.annotations.responses.ApiResponses)

Example 3 with Status

use of org.wso2.balana.ctx.Status in project product-microgateway by wso2.

the class RESTAPIServiceImpl method getClientCertificates.

/**
 * @see RESTAPIService#getClientCertificates(String)
 */
public List<ClientCertMetadataDTO> getClientCertificates(String accessToken) {
    Config config = CmdUtils.getConfig();
    URL url;
    HttpsURLConnection urlConn = null;
    ClientCertificatesDTO certList;
    List<ClientCertMetadataDTO> selectedCertificates = new ArrayList<>();
    // calling token endpoint
    publisherEp = publisherEp.endsWith("/") ? publisherEp : publisherEp + "/";
    try {
        String urlStr = publisherEp + "clientCertificates";
        url = new URL(urlStr);
        urlConn = (HttpsURLConnection) url.openConnection();
        if (inSecure) {
            urlConn.setHostnameVerifier((s, sslSession) -> true);
        }
        urlConn.setDoOutput(true);
        urlConn.setRequestMethod(RESTServiceConstants.GET);
        urlConn.setRequestProperty(RESTServiceConstants.AUTHORIZATION, RESTServiceConstants.BEARER + " " + accessToken);
        int responseCode = urlConn.getResponseCode();
        if (responseCode == 200) {
            ObjectMapper mapper = new ObjectMapper();
            String responseStr = RESTAPIUtils.getResponseString(urlConn.getInputStream());
            // convert json string to object
            certList = mapper.readValue(responseStr, ClientCertificatesDTO.class);
            List<ClientCertMetadataDTO> certDTOS = certList.getCertificates();
            for (ClientCertMetadataDTO certDTO : certDTOS) {
                if (!RESTServiceConstants.UNLIMITED.equalsIgnoreCase(certDTO.getTier())) {
                    selectedCertificates.add(certDTO);
                }
            }
        } else if (responseCode == 401) {
            throw new CLIRuntimeException("Invalid user credentials or the user does not have required permissions");
        } else if (responseCode == 404 || responseCode == 400) {
            selectedCertificates = null;
        } else {
            throw new RuntimeException("Error occurred while getting token. Status code: " + responseCode);
        }
    } catch (IOException e) {
        String msg = "Error while creating the new token for token regeneration.";
        throw new RuntimeException(msg, e);
    } finally {
        if (urlConn != null) {
            urlConn.disconnect();
        }
    }
    if (selectedCertificates != null) {
        MutualSSL clientDetails = new MutualSSL();
        clientDetails.setClientCertificates(selectedCertificates);
        // todo: check usage of this.
        config.setMutualSSL(clientDetails);
    }
    return selectedCertificates;
}
Also used : Config(org.wso2.apimgt.gateway.cli.model.config.Config) ArrayList(java.util.ArrayList) IOException(java.io.IOException) CLIRuntimeException(org.wso2.apimgt.gateway.cli.exception.CLIRuntimeException) URL(java.net.URL) CLIRuntimeException(org.wso2.apimgt.gateway.cli.exception.CLIRuntimeException) ClientCertMetadataDTO(org.wso2.apimgt.gateway.cli.model.rest.ClientCertMetadataDTO) MutualSSL(org.wso2.apimgt.gateway.cli.model.config.MutualSSL) ClientCertificatesDTO(org.wso2.apimgt.gateway.cli.model.rest.ClientCertificatesDTO) HttpsURLConnection(javax.net.ssl.HttpsURLConnection) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper)

Example 4 with Status

use of org.wso2.balana.ctx.Status in project product-microgateway by wso2.

the class RESTAPIServiceImpl method getAPIs.

/**
 * @see RESTAPIService#getAPIs(String, String)
 */
public List<ExtendedAPI> getAPIs(String labelName, String accessToken) {
    logger.debug("Retrieving APIs with label {}", labelName);
    URL url;
    HttpsURLConnection urlConn = null;
    APIListDTO apiListDTO;
    boolean isExpand = false;
    // calling token endpoint
    try {
        publisherEp = publisherEp.endsWith("/") ? publisherEp : publisherEp + "/";
        String urlStr = publisherEp + RESTServiceConstants.APIS_GET_URI.replace(CliConstants.LABEL_PLACEHOLDER, URLEncoder.encode(labelName, CliConstants.CHARSET_UTF8));
        // Expand property is not used from APIM v3 onwards.
        if (restVersion.startsWith(CliConstants.REST_API_V1_PREFIX)) {
            urlStr = urlStr.replace(CliConstants.EXPAND_PLACEHOLDER, "false");
        } else {
            urlStr = urlStr.replace(CliConstants.EXPAND_PLACEHOLDER, "true");
            isExpand = true;
        }
        logger.debug("GET APIs URL: {}", urlStr);
        url = new URL(urlStr);
        urlConn = (HttpsURLConnection) url.openConnection();
        if (inSecure) {
            urlConn.setHostnameVerifier((s, sslSession) -> true);
        }
        urlConn.setDoOutput(true);
        urlConn.setRequestMethod(RESTServiceConstants.GET);
        urlConn.setRequestProperty(RESTServiceConstants.AUTHORIZATION, RESTServiceConstants.BEARER + " " + accessToken);
        int responseCode = urlConn.getResponseCode();
        logger.debug("Response code: {}", responseCode);
        if (responseCode == 200) {
            ObjectMapper mapper = new ObjectMapper();
            String responseStr = RESTAPIUtils.getResponseString(urlConn.getInputStream());
            logger.trace("Response body: {}", responseStr);
            // convert json string to object
            apiListDTO = mapper.readValue(responseStr, APIListDTO.class);
            for (ExtendedAPI api : apiListDTO.getList()) {
                setAdditionalConfigs(api);
                // if using APIM v3, then open API should be fetched separately and set to the API object.
                if (!isExpand) {
                    api.setApiDefinition(getOpenAPIFromAPIId(api.getId(), accessToken));
                }
            }
        } else if (responseCode == 401) {
            throw new CLIRuntimeException("Invalid user credentials or the user does not have required permissions");
        } else {
            throw new RuntimeException("Error occurred while getting token. Status code: " + responseCode);
        }
    } catch (IOException e) {
        String msg = "Error while getting all APIs with label " + labelName;
        throw new RuntimeException(msg, e);
    } finally {
        if (urlConn != null) {
            urlConn.disconnect();
        }
    }
    logger.debug("Retrieving APIs with label {} was successful.", labelName);
    return apiListDTO.getList();
}
Also used : CLIRuntimeException(org.wso2.apimgt.gateway.cli.exception.CLIRuntimeException) APIListDTO(org.wso2.apimgt.gateway.cli.model.rest.APIListDTO) ExtendedAPI(org.wso2.apimgt.gateway.cli.model.rest.ext.ExtendedAPI) IOException(java.io.IOException) CLIRuntimeException(org.wso2.apimgt.gateway.cli.exception.CLIRuntimeException) URL(java.net.URL) HttpsURLConnection(javax.net.ssl.HttpsURLConnection) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper)

Example 5 with Status

use of org.wso2.balana.ctx.Status in project product-microgateway by wso2.

the class OAuthServiceImpl method generateClientIdAndSecret.

/**
 * @see OAuthService#generateClientIdAndSecret(String, String, char[], boolean)
 */
public String[] generateClientIdAndSecret(String dcrEndpoint, String username, char[] password, boolean inSecure) {
    URL url;
    if (inSecure) {
        CmdUtils.useInsecureSSL();
    }
    HttpsURLConnection urlConn = null;
    try {
        String requestBody = new DCRRequestBuilder().setCallbackUrl(TokenManagementConstants.APPLICATION_CALLBACK_URL).setClientName(TokenManagementConstants.APPLICATION_NAME).setOwner(username).setSaasApp(true).setGrantTypes(new String[] { TokenManagementConstants.PASSWORD_GRANT_TYPE }).setTokenScope(TokenManagementConstants.TOKEN_SCOPE_PRODUCTION).requestBody();
        ObjectMapper mapper = new ObjectMapper();
        url = new URL(dcrEndpoint);
        urlConn = (HttpsURLConnection) url.openConnection();
        urlConn.setRequestMethod(TokenManagementConstants.POST);
        urlConn.setRequestProperty(TokenManagementConstants.CONTENT_TYPE, TokenManagementConstants.CONTENT_TYPE_APPLICATION_JSON);
        urlConn.setDoOutput(true);
        String clientEncoded = DatatypeConverter.printBase64Binary((username + ':' + new String(password)).getBytes(StandardCharsets.UTF_8));
        urlConn.setRequestProperty(TokenManagementConstants.AUTHORIZATION, TokenManagementConstants.BASIC + " " + clientEncoded);
        urlConn.getOutputStream().write(requestBody.getBytes(TokenManagementConstants.UTF_8));
        logger.debug("DCR URL: {}", dcrEndpoint);
        logger.trace("Request body for DCR call: {}", requestBody);
        int responseCode = urlConn.getResponseCode();
        if (responseCode == 200) {
            // If the DCR call is success
            String responseStr = RESTAPIUtils.getResponseString(urlConn.getInputStream());
            logger.debug("Received response status code for DCR call: {}", responseCode);
            logger.trace("Received response body for DCR call: {}", responseStr);
            JsonNode rootNode = mapper.readTree(responseStr);
            JsonNode clientIdNode = rootNode.path(TokenManagementConstants.CLIENT_ID);
            JsonNode clientSecretNode = rootNode.path(TokenManagementConstants.CLIENT_SECRET);
            String clientId = clientIdNode.asText();
            String clientSecret = clientSecretNode.asText();
            String[] clientInfo = { clientId, clientSecret };
            logger.debug("Successfully received client id:{} from DCR endpoint", clientId);
            return clientInfo;
        } else if (responseCode == 401) {
            throw new CLIRuntimeException("Invalid user credentials or the user does not have required permissions");
        } else {
            // If DCR call fails
            throw new CLIInternalException("Error occurred while creating oAuth application Status code: " + responseCode);
        }
    } catch (IOException e) {
        String serverUrl = getServerUrl(dcrEndpoint);
        throw new CLIRuntimeException("Error occurred while trying to connect with server. Is the server running at " + serverUrl + "?", "Error occurred while communicate with DCR endpoint: " + dcrEndpoint, 1, e);
    } finally {
        if (urlConn != null) {
            urlConn.disconnect();
        }
    }
}
Also used : DCRRequestBuilder(org.wso2.apimgt.gateway.cli.oauth.builder.DCRRequestBuilder) CLIInternalException(org.wso2.apimgt.gateway.cli.exception.CLIInternalException) JsonNode(com.fasterxml.jackson.databind.JsonNode) IOException(java.io.IOException) CLIRuntimeException(org.wso2.apimgt.gateway.cli.exception.CLIRuntimeException) URL(java.net.URL) HttpsURLConnection(javax.net.ssl.HttpsURLConnection) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper)

Aggregations

Test (org.testng.annotations.Test)99 APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)91 ArrayList (java.util.ArrayList)87 Response (javax.ws.rs.core.Response)85 HashMap (java.util.HashMap)81 SQLException (java.sql.SQLException)61 Connection (java.sql.Connection)58 PreparedStatement (java.sql.PreparedStatement)54 IOException (java.io.IOException)51 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)50 ErrorResponse (org.wso2.carbon.identity.api.server.common.error.ErrorResponse)46 APIError (org.wso2.carbon.identity.api.server.common.error.APIError)45 API (org.wso2.carbon.apimgt.api.model.API)40 RegistryException (org.wso2.carbon.registry.core.exceptions.RegistryException)35 SubscribedAPI (org.wso2.carbon.apimgt.api.model.SubscribedAPI)34 JSONObject (org.json.simple.JSONObject)33 API (org.wso2.carbon.apimgt.core.models.API)30 GenericArtifact (org.wso2.carbon.governance.api.generic.dataobjects.GenericArtifact)28 HashSet (java.util.HashSet)27 APIMgtDAOException (org.wso2.carbon.apimgt.core.exception.APIMgtDAOException)27