Search in sources :

Example 1 with HttpResponse

use of org.wso2.carbon.apimgt.core.models.HttpResponse in project carbon-apimgt by wso2.

the class RestCallUtilImpl method putRequest.

/**
 * {@inheritDoc}
 */
@Override
public HttpResponse putRequest(URI uri, MediaType acceptContentType, List<String> cookies, Entity entity, MediaType payloadContentType) throws APIManagementException {
    if (uri == null) {
        throw new IllegalArgumentException("The URI must not be null");
    }
    if (entity == null) {
        throw new IllegalArgumentException("Entity must not be null");
    }
    if (payloadContentType == null) {
        throw new IllegalArgumentException("Payload content type must not be null");
    }
    HttpURLConnection httpConnection = null;
    try {
        httpConnection = (HttpURLConnection) uri.toURL().openConnection();
        httpConnection.setRequestMethod(APIMgtConstants.FunctionsConstants.PUT);
        httpConnection.setRequestProperty(APIMgtConstants.FunctionsConstants.CONTENT_TYPE, payloadContentType.toString());
        httpConnection.setDoOutput(true);
        if (acceptContentType != null) {
            httpConnection.setRequestProperty(APIMgtConstants.FunctionsConstants.ACCEPT, acceptContentType.toString());
        }
        if (cookies != null && !cookies.isEmpty()) {
            for (String cookie : cookies) {
                httpConnection.addRequestProperty(APIMgtConstants.FunctionsConstants.COOKIE, cookie.split(";", 2)[0]);
            }
        }
        OutputStream outputStream = httpConnection.getOutputStream();
        outputStream.write(entity.toString().getBytes(StandardCharsets.UTF_8));
        outputStream.flush();
        outputStream.close();
        return getResponse(httpConnection);
    } catch (IOException e) {
        throw new APIManagementException("Connection not established properly ", e);
    } finally {
        if (httpConnection != null) {
            httpConnection.disconnect();
        }
    }
}
Also used : HttpURLConnection(java.net.HttpURLConnection) APIManagementException(org.wso2.carbon.apimgt.core.exception.APIManagementException) OutputStream(java.io.OutputStream) IOException(java.io.IOException)

Example 2 with HttpResponse

use of org.wso2.carbon.apimgt.core.models.HttpResponse in project carbon-apimgt by wso2.

the class RestCallUtilImpl method getResponse.

/**
 * To get a response from service.
 *
 * @param httpConnection Connection used to make the request
 * @return HttpResponse from service
 * @throws IOException In case of any failures, when trying to get the response from service
 */
private HttpResponse getResponse(HttpURLConnection httpConnection) throws IOException {
    HttpResponse response = new HttpResponse();
    response.setResponseCode(httpConnection.getResponseCode());
    response.setResponseMessage(httpConnection.getResponseMessage());
    if (response.getResponseCode() / 100 == 2) {
        try (BufferedReader responseBuffer = new BufferedReader(new InputStreamReader(httpConnection.getInputStream(), StandardCharsets.UTF_8))) {
            StringBuilder results = new StringBuilder();
            String line;
            while ((line = responseBuffer.readLine()) != null) {
                results.append(line).append("\n");
            }
            response.setHeaderFields(httpConnection.getHeaderFields());
            response.setResults(results.toString());
        }
    }
    return response;
}
Also used : InputStreamReader(java.io.InputStreamReader) BufferedReader(java.io.BufferedReader) HttpResponse(org.wso2.carbon.apimgt.core.models.HttpResponse)

Example 3 with HttpResponse

use of org.wso2.carbon.apimgt.core.models.HttpResponse in project carbon-apimgt by wso2.

the class RestCallUtilImpl method postRequest.

/**
 * {@inheritDoc}
 */
@Override
public HttpResponse postRequest(URI uri, MediaType acceptContentType, List<String> cookies, Entity entity, MediaType payloadContentType, Map<String, String> headers) throws APIManagementException {
    if (uri == null) {
        throw new IllegalArgumentException("The URI must not be null");
    }
    if (entity == null) {
        throw new IllegalArgumentException("Entity must not be null");
    }
    if (payloadContentType == null) {
        throw new IllegalArgumentException("Payload content type must not be null");
    }
    HttpURLConnection httpConnection = null;
    try {
        httpConnection = (HttpURLConnection) uri.toURL().openConnection();
        httpConnection.setRequestMethod(APIMgtConstants.FunctionsConstants.POST);
        httpConnection.setRequestProperty(APIMgtConstants.FunctionsConstants.CONTENT_TYPE, payloadContentType.toString());
        httpConnection.setDoOutput(true);
        if (acceptContentType != null) {
            httpConnection.setRequestProperty(APIMgtConstants.FunctionsConstants.ACCEPT, acceptContentType.toString());
        }
        if (cookies != null && !cookies.isEmpty()) {
            for (String cookie : cookies) {
                httpConnection.addRequestProperty(APIMgtConstants.FunctionsConstants.COOKIE, cookie.split(";", 2)[0]);
            }
        }
        if (headers != null) {
            for (Map.Entry<String, String> header : headers.entrySet()) {
                httpConnection.addRequestProperty(header.getKey(), header.getValue());
            }
        }
        OutputStream outputStream = httpConnection.getOutputStream();
        outputStream.write(entity.getEntity().toString().getBytes(StandardCharsets.UTF_8));
        outputStream.flush();
        outputStream.close();
        return getResponse(httpConnection);
    } catch (IOException e) {
        throw new APIManagementException("Connection not established properly ", e);
    } finally {
        if (httpConnection != null) {
            httpConnection.disconnect();
        }
    }
}
Also used : HttpURLConnection(java.net.HttpURLConnection) APIManagementException(org.wso2.carbon.apimgt.core.exception.APIManagementException) OutputStream(java.io.OutputStream) IOException(java.io.IOException) Map(java.util.Map)

Example 4 with HttpResponse

use of org.wso2.carbon.apimgt.core.models.HttpResponse in project carbon-apimgt by wso2.

the class RestCallUtilImpl method rsaSignedFetchUserRequest.

/**
 * {@inheritDoc}
 */
@Override
public HttpResponse rsaSignedFetchUserRequest(URI uri, String username, String userTenantDomain, String rsaSignedToken, MediaType acceptContentType) throws APIManagementException {
    if (uri == null) {
        throw new IllegalArgumentException("The URI must not be null");
    }
    if (username == null) {
        throw new IllegalArgumentException("UserName must not be null");
    }
    if (userTenantDomain == null) {
        throw new IllegalArgumentException("User tenant domain must not be null");
    }
    if (rsaSignedToken == null) {
        throw new IllegalArgumentException("RSA signed token must not be null");
    }
    HttpURLConnection httpConnection = null;
    try {
        JSONObject loginInfoJsonObj = new JSONObject();
        loginInfoJsonObj.put(APIMgtConstants.FunctionsConstants.USERNAME, username);
        loginInfoJsonObj.put(APIMgtConstants.FunctionsConstants.USER_TENANT_DOMAIN, userTenantDomain);
        httpConnection = (HttpURLConnection) uri.toURL().openConnection();
        httpConnection.setRequestMethod(APIMgtConstants.FunctionsConstants.POST);
        httpConnection.setRequestProperty(APIMgtConstants.FunctionsConstants.CONTENT_TYPE, MediaType.APPLICATION_JSON);
        httpConnection.setDoOutput(true);
        httpConnection.setRequestProperty(APIMgtConstants.FunctionsConstants.RSA_SIGNED_TOKEN, rsaSignedToken);
        if (acceptContentType != null) {
            httpConnection.setRequestProperty(APIMgtConstants.FunctionsConstants.ACCEPT, acceptContentType.toString());
        }
        OutputStream outputStream = httpConnection.getOutputStream();
        outputStream.write(loginInfoJsonObj.toString().getBytes(StandardCharsets.UTF_8));
        outputStream.flush();
        outputStream.close();
        return getResponse(httpConnection);
    } catch (IOException e) {
        throw new APIManagementException("Connection not established properly ", e);
    } finally {
        if (httpConnection != null) {
            httpConnection.disconnect();
        }
    }
}
Also used : HttpURLConnection(java.net.HttpURLConnection) JSONObject(org.json.simple.JSONObject) APIManagementException(org.wso2.carbon.apimgt.core.exception.APIManagementException) OutputStream(java.io.OutputStream) IOException(java.io.IOException)

Example 5 with HttpResponse

use of org.wso2.carbon.apimgt.core.models.HttpResponse in project carbon-apimgt by wso2.

the class FunctionTrigger method captureEvent.

/**
 * Used to observe all the {@link org.wso2.carbon.apimgt.core.models.Event} occurrences
 * in an {@link org.wso2.carbon.apimgt.core.api.APIMObservable} object and trigger corresponding function that is
 * mapped to the particular {@link org.wso2.carbon.apimgt.core.models.Event} occurred.
 * <p>
 * This is a specific implementation for
 * {@link org.wso2.carbon.apimgt.core.api.EventObserver#captureEvent(Event, String, ZonedDateTime, Map)} method,
 * provided by {@link org.wso2.carbon.apimgt.core.impl.FunctionTrigger} which implements
 * {@link org.wso2.carbon.apimgt.core.api.EventObserver} interface.
 * <p>
 * {@inheritDoc}
 *
 * @see org.wso2.carbon.apimgt.core.impl.EventLogger#captureEvent(Event, String, ZonedDateTime, Map)
 */
@Override
public void captureEvent(Event event, String username, ZonedDateTime eventTime, Map<String, String> metadata) {
    List<Function> functions = null;
    String jsonPayload = null;
    if (event == null) {
        throw new IllegalArgumentException("Event must not be null");
    }
    if (username == null) {
        throw new IllegalArgumentException("Username must not be null");
    }
    if (eventTime == null) {
        throw new IllegalArgumentException("Event_time must not be null");
    }
    if (metadata == null) {
        throw new IllegalArgumentException("Payload must not be null");
    }
    // Add general attributes to payload
    metadata.put(APIMgtConstants.FunctionsConstants.EVENT, event.getEventAsString());
    metadata.put(APIMgtConstants.FunctionsConstants.COMPONENT, event.getComponent().getComponentAsString());
    metadata.put(APIMgtConstants.FunctionsConstants.USERNAME, username);
    metadata.put(APIMgtConstants.FunctionsConstants.EVENT_TIME, eventTime.toString());
    try {
        functions = functionDAO.getUserFunctionsForEvent(username, event);
        jsonPayload = new Gson().toJson(metadata);
    } catch (APIMgtDAOException e) {
        String message = "Error loading functions for event from DB: -event: " + event + " -Username: " + username;
        log.error(message, new APIManagementException("Problem invoking 'getUserFunctionsForEvent' method in " + "'FunctionDAO' ", e, ExceptionCodes.APIMGT_DAO_EXCEPTION));
    }
    if (functions != null && !functions.isEmpty()) {
        for (Function function : functions) {
            HttpResponse response = null;
            try {
                response = restCallUtil.postRequest(function.getEndpointURI(), null, null, Entity.json(jsonPayload), MediaType.APPLICATION_JSON_TYPE, Collections.EMPTY_MAP);
            } catch (APIManagementException e) {
                log.error("Failed to make http request: -function: " + function.getName() + " -endpoint URI: " + function.getEndpointURI() + " -event: " + event + " -Username: " + username, e);
            }
            if (response != null) {
                int responseStatusCode = response.getResponseCode();
                // Benefit of integer division used to ensure all possible success response codes covered
                if (responseStatusCode / 100 == 2) {
                    log.info("Function successfully invoked: " + function.getName() + " -event: " + event + " -Username: " + username + " -Response code: " + responseStatusCode);
                } else {
                    log.error("Problem invoking function: " + function.getName() + " -event: " + event + " -Username: " + username + " -Response code: " + responseStatusCode);
                }
            }
        }
    }
}
Also used : Function(org.wso2.carbon.apimgt.core.models.Function) APIMgtDAOException(org.wso2.carbon.apimgt.core.exception.APIMgtDAOException) APIManagementException(org.wso2.carbon.apimgt.core.exception.APIManagementException) Gson(com.google.gson.Gson) HttpResponse(org.wso2.carbon.apimgt.core.models.HttpResponse)

Aggregations

APIManagementException (org.wso2.carbon.apimgt.core.exception.APIManagementException)7 IOException (java.io.IOException)6 HttpURLConnection (java.net.HttpURLConnection)6 OutputStream (java.io.OutputStream)4 HttpResponse (org.wso2.carbon.apimgt.core.models.HttpResponse)3 JSONObject (org.json.simple.JSONObject)2 Function (org.wso2.carbon.apimgt.core.models.Function)2 Gson (com.google.gson.Gson)1 BufferedReader (java.io.BufferedReader)1 InputStreamReader (java.io.InputStreamReader)1 URI (java.net.URI)1 ZonedDateTime (java.time.ZonedDateTime)1 ArrayList (java.util.ArrayList)1 Map (java.util.Map)1 Test (org.testng.annotations.Test)1 RestCallUtil (org.wso2.carbon.apimgt.core.api.RestCallUtil)1 FunctionDAO (org.wso2.carbon.apimgt.core.dao.FunctionDAO)1 APIMgtDAOException (org.wso2.carbon.apimgt.core.exception.APIMgtDAOException)1 Event (org.wso2.carbon.apimgt.core.models.Event)1