Search in sources :

Example 46 with Header

use of org.wso2.carbon.messaging.Header in project carbon-apimgt by wso2.

the class BasicAuthAuthenticatorTestCase method testAuthenticate.

@Test
public void testAuthenticate() throws Exception {
    final String authorizationHttpHeader = "Basic YWRtaW46YWRtaW4=";
    final String authorizationHttpHeader1 = "DummyHeader YWRtaW46YWRtaW4=";
    HTTPCarbonMessage carbonMessage = Mockito.mock(HTTPCarbonMessage.class);
    Request requestObj = new Request(carbonMessage);
    try {
        PowerMockito.whenNew(Request.class).withArguments(carbonMessage).thenReturn(requestObj);
    } catch (Exception e) {
        throw new APIMgtSecurityException("Error while mocking Request Object ", e);
    }
    try {
        BasicAuthAuthenticator basicAuthAuthenticator = new BasicAuthAuthenticator();
        basicAuthAuthenticator.authenticate(requestObj, null, null);
    } catch (APIMgtSecurityException e) {
        Assert.assertEquals(e.getMessage(), "Missing Authorization header in the request.`");
    }
    when(requestObj.getHeader(RestApiConstants.AUTHORIZATION_HTTP_HEADER)).thenReturn(authorizationHttpHeader1);
    Response responseObj = Mockito.mock(Response.class);
    ServiceMethodInfo serviceMethodInfoObj = Mockito.mock(ServiceMethodInfo.class);
    try {
        BasicAuthAuthenticator basicAuthAuthenticator = new BasicAuthAuthenticator();
        basicAuthAuthenticator.authenticate(requestObj, responseObj, serviceMethodInfoObj);
    } catch (APIMgtSecurityException e) {
        Assert.assertEquals(e.getMessage(), "Missing 'Authorization : Basic' header in the request.`");
    }
    when(requestObj.getHeader(RestApiConstants.AUTHORIZATION_HTTP_HEADER)).thenReturn(authorizationHttpHeader);
    BasicAuthAuthenticator basicAuthAuthenticator = new BasicAuthAuthenticator();
    boolean isAuthenticated = basicAuthAuthenticator.authenticate(requestObj, responseObj, serviceMethodInfoObj);
    if (isAuthenticated) {
        Assert.assertEquals(isAuthenticated, true);
    } else {
        Assert.assertEquals(isAuthenticated, false);
    }
}
Also used : Response(org.wso2.msf4j.Response) HTTPCarbonMessage(org.wso2.transport.http.netty.message.HTTPCarbonMessage) BasicAuthAuthenticator(org.wso2.carbon.apimgt.rest.api.common.impl.BasicAuthAuthenticator) APIMgtSecurityException(org.wso2.carbon.apimgt.rest.api.common.exception.APIMgtSecurityException) ServiceMethodInfo(org.wso2.msf4j.ServiceMethodInfo) Request(org.wso2.msf4j.Request) APIMgtSecurityException(org.wso2.carbon.apimgt.rest.api.common.exception.APIMgtSecurityException) Test(org.testng.annotations.Test)

Example 47 with Header

use of org.wso2.carbon.messaging.Header in project carbon-apimgt by wso2.

the class ApisApiServiceImpl method apisApiIdGatewayConfigGet.

/**
 * Retrieve API's gateway configuration
 *
 * @param apiId   UUID of the API
 * @param request msf4j request object
 * @return 200 OK if the opration was successful
 * @throws NotFoundException If failed to retrieve API gateway configuration
 */
@Override
public Response apisApiIdGatewayConfigGet(String apiId, String accept, Request request) throws NotFoundException {
    try {
        APIMgtAdminService apiMgtAdminService = APIManagerFactory.getInstance().getAPIMgtAdminService();
        String apiGatewayConfig = null;
        apiGatewayConfig = apiMgtAdminService.getAPIGatewayServiceConfig(apiId);
        if (apiGatewayConfig != null) {
            return Response.ok().entity(apiGatewayConfig).build();
        } else {
            String msg = "API is not found with apiId : " + apiId;
            ErrorDTO errorDTO = RestApiUtil.getErrorDTO(msg, 900314L, msg);
            log.error(msg);
            return Response.status(Response.Status.NOT_FOUND).header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON).entity(errorDTO).build();
        }
    } catch (APIManagementException e) {
        String errorMessage = "Error while retrieving gateway config of API : " + apiId;
        HashMap<String, String> paramList = new HashMap<String, String>();
        paramList.put(APIMgtConstants.ExceptionsConstants.API_ID, apiId);
        ErrorDTO errorDTO = RestApiUtil.getErrorDTO(e.getErrorHandler(), paramList);
        log.error(errorMessage, e);
        return Response.status(e.getErrorHandler().getHttpStatusCode()).header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON).entity(errorDTO).build();
    }
}
Also used : APIMgtAdminService(org.wso2.carbon.apimgt.core.api.APIMgtAdminService) APIManagementException(org.wso2.carbon.apimgt.core.exception.APIManagementException) HashMap(java.util.HashMap) ErrorDTO(org.wso2.carbon.apimgt.rest.api.common.dto.ErrorDTO)

Example 48 with Header

use of org.wso2.carbon.messaging.Header in project ballerina by ballerina-lang.

the class AbstractHTTPAction method send.

/**
 * Send outbound request through the client connector. If the Content-Type is multipart, check whether the boundary
 * exist. If not get a new boundary string and add it as a parameter to Content-Type, just before sending header
 * info through wire. If a boundary string exist at this point, serialize multipart entity body, else serialize
 * entity body which can either be a message data source or a byte channel.
 *
 * @param dataContext               holds the ballerina context and callback
 * @param outboundRequestMsg        Outbound request that needs to be sent across the wire
 * @param async                     whether a handle should be return
 * @return connector future for this particular request
 * @throws Exception When an error occurs while sending the outbound request via client connector
 */
private void send(DataContext dataContext, HTTPCarbonMessage outboundRequestMsg, boolean async) throws Exception {
    BStruct bConnector = (BStruct) dataContext.context.getRefArgument(0);
    Struct httpClient = BLangConnectorSPIUtil.toStruct(bConnector);
    HttpClientConnector clientConnector = (HttpClientConnector) httpClient.getNativeData(HttpConstants.HTTP_CLIENT);
    String contentType = HttpUtil.getContentTypeFromTransportMessage(outboundRequestMsg);
    String boundaryString = null;
    if (HeaderUtil.isMultipart(contentType)) {
        boundaryString = HttpUtil.addBoundaryIfNotExist(outboundRequestMsg, contentType);
    }
    HttpMessageDataStreamer outboundMsgDataStreamer = new HttpMessageDataStreamer(outboundRequestMsg);
    OutputStream messageOutputStream = outboundMsgDataStreamer.getOutputStream();
    RetryConfig retryConfig = getRetryConfiguration(httpClient);
    HTTPClientConnectorListener httpClientConnectorLister = new HTTPClientConnectorListener(dataContext, retryConfig, outboundRequestMsg, outboundMsgDataStreamer);
    HttpResponseFuture future = clientConnector.send(outboundRequestMsg);
    if (async) {
        future.setResponseHandleListener(httpClientConnectorLister);
    } else {
        future.setHttpConnectorListener(httpClientConnectorLister);
    }
    try {
        if (boundaryString != null) {
            serializeMultiparts(dataContext.context, messageOutputStream, boundaryString);
        } else {
            serializeDataSource(dataContext.context, messageOutputStream);
        }
    } catch (IOException | EncoderException serializerException) {
        // We don't have to do anything here as the client connector will notify
        // the error though the listener
        logger.warn("couldn't serialize the message", serializerException);
    }
}
Also used : EncoderException(io.netty.handler.codec.EncoderException) BStruct(org.ballerinalang.model.values.BStruct) HttpClientConnector(org.wso2.transport.http.netty.contract.HttpClientConnector) RetryConfig(org.ballerinalang.net.http.RetryConfig) HttpMessageDataStreamer(org.wso2.transport.http.netty.message.HttpMessageDataStreamer) OutputStream(java.io.OutputStream) HttpResponseFuture(org.wso2.transport.http.netty.contract.HttpResponseFuture) IOException(java.io.IOException) ResponseCacheControlStruct(org.ballerinalang.net.http.caching.ResponseCacheControlStruct) Struct(org.ballerinalang.connector.api.Struct) BStruct(org.ballerinalang.model.values.BStruct)

Example 49 with Header

use of org.wso2.carbon.messaging.Header in project ballerina by ballerina-lang.

the class MultipartDecoderTest method testMultiplePartsForFormData.

@Test(description = "Test sending a multipart request as multipart/form-data with multiple body parts")
public void testMultiplePartsForFormData() {
    String path = "/test/multipleparts";
    List<Header> headers = new ArrayList<>();
    String multipartDataBoundary = MimeUtil.getNewMultipartDelimiter();
    headers.add(new Header(HttpHeaderNames.CONTENT_TYPE.toString(), "multipart/form-data; boundary=" + multipartDataBoundary));
    String multipartBody = "--" + multipartDataBoundary + "\r\n" + "Content-Disposition: form-data; name=\"foo\"" + "\r\n" + "Content-Type: text/plain; charset=UTF-8" + "\r\n" + "\r\n" + "Part1" + "\r\n" + "--" + multipartDataBoundary + "\r\n" + "Content-Disposition: form-data; name=\"filepart\"; filename=\"file-01.txt\"" + "\r\n" + "Content-Type: text/plain" + "\r\n" + "Content-Transfer-Encoding: binary" + "\r\n" + "\r\n" + "Part2" + StringUtil.NEWLINE + "\r\n" + "--" + multipartDataBoundary + "--" + "\r\n";
    HTTPTestRequest inRequestMsg = MessageUtils.generateHTTPMessage(path, HttpConstants.HTTP_METHOD_POST, headers, multipartBody);
    HTTPCarbonMessage response = Services.invokeNew(serviceResult, MOCK_ENDPOINT_NAME, inRequestMsg);
    Assert.assertNotNull(response, "Response message not found");
    Assert.assertEquals(ResponseReader.getReturnValue(response), " -- Part1 -- Part2" + StringUtil.NEWLINE);
}
Also used : HTTPCarbonMessage(org.wso2.transport.http.netty.message.HTTPCarbonMessage) Header(org.wso2.carbon.messaging.Header) ArrayList(java.util.ArrayList) HTTPTestRequest(org.ballerinalang.test.services.testutils.HTTPTestRequest) Test(org.testng.annotations.Test)

Example 50 with Header

use of org.wso2.carbon.messaging.Header in project ballerina by ballerina-lang.

the class UriTemplateDispatcherTest method testValidUrlTemplateDispatching.

@Test(description = "Test accessing the variables parsed with URL. /products/{productId}/{regId}", dataProvider = "validUrl")
public void testValidUrlTemplateDispatching(String path) {
    HTTPTestRequest cMsg = MessageUtils.generateHTTPMessage(path, "GET");
    final String xOrderIdHeadeName = "X-ORDER-ID";
    final String xOrderIdHeadeValue = "ORD12345";
    cMsg.setHeader(xOrderIdHeadeName, xOrderIdHeadeValue);
    HTTPCarbonMessage response = Services.invokeNew(application, TEST_EP, cMsg);
    Assert.assertNotNull(response, "Response message not found");
    // Expected Json message : {"X-ORDER-ID":"ORD12345","ProductID":"PID123","RegID":"RID123"}
    BJSON bJson = new BJSON(new HttpMessageDataStreamer(response).getInputStream());
    Assert.assertEquals(bJson.value().get(xOrderIdHeadeName).asText(), xOrderIdHeadeValue, "Header value mismatched");
    Assert.assertEquals(bJson.value().get("ProductID").asText(), "PID123", "ProductID variable not set properly.");
    Assert.assertEquals(bJson.value().get("RegID").asText(), "RID123", "RegID variable not set properly.");
}
Also used : HTTPCarbonMessage(org.wso2.transport.http.netty.message.HTTPCarbonMessage) HttpMessageDataStreamer(org.wso2.transport.http.netty.message.HttpMessageDataStreamer) HTTPTestRequest(org.ballerinalang.test.services.testutils.HTTPTestRequest) BJSON(org.ballerinalang.model.values.BJSON) Test(org.testng.annotations.Test)

Aggregations

APIManagementException (org.wso2.carbon.apimgt.core.exception.APIManagementException)103 HashMap (java.util.HashMap)95 ErrorDTO (org.wso2.carbon.apimgt.rest.api.common.dto.ErrorDTO)95 Test (org.testng.annotations.Test)36 APIStore (org.wso2.carbon.apimgt.core.api.APIStore)35 HTTPCarbonMessage (org.wso2.transport.http.netty.message.HTTPCarbonMessage)33 APIPublisher (org.wso2.carbon.apimgt.core.api.APIPublisher)30 HTTPTestRequest (org.ballerinalang.test.services.testutils.HTTPTestRequest)28 APIMgtAdminService (org.wso2.carbon.apimgt.core.api.APIMgtAdminService)24 ArrayList (java.util.ArrayList)23 BadRequestException (org.wso2.charon3.core.exceptions.BadRequestException)19 CharonException (org.wso2.charon3.core.exceptions.CharonException)19 SCIMResponse (org.wso2.charon3.core.protocol.SCIMResponse)19 NotFoundException (org.wso2.charon3.core.exceptions.NotFoundException)18 SCIMResourceTypeSchema (org.wso2.charon3.core.schema.SCIMResourceTypeSchema)18 Header (org.wso2.carbon.messaging.Header)17 InternalErrorException (org.wso2.charon3.core.exceptions.InternalErrorException)16 IOException (java.io.IOException)15 JSONEncoder (org.wso2.charon3.core.encoder.JSONEncoder)15 Map (java.util.Map)14