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);
}
}
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();
}
}
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);
}
}
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);
}
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.");
}
Aggregations