org.wso2.carbon.automation.test.utils.http.client.HttpRequestUtil Java Examples

The following examples show how to use org.wso2.carbon.automation.test.utils.http.client.HttpRequestUtil. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ESBJAVA3751UriTemplateReservedCharacterEncodingTest.java    From micro-integrator with Apache License 2.0 6 votes vote down vote up
@Test(groups = { "wso2.esb" }, description = "Sending http request with a query param consist of"
        + " reserved + character ")
public void testURITemplateParameterDecodingWithPercentEncodingEscapedAtExpansion() throws Exception {
    carbonLogReader.clearLogs();
    boolean isPercentEncoded = false;
    boolean isMessageContextPropertyPercentDecoded = false;
    HttpResponse response = HttpRequestUtil
            .sendGetRequest(getApiInvocationURL("services/client/escapeUrlEncoded?queryParam=ESB+WSO2"), null);
    String decodedMessageContextProperty = "decodedQueryParamValue = ESB+WSO2";
    isMessageContextPropertyPercentDecoded = carbonLogReader.checkForLog(decodedMessageContextProperty, DEFAULT_TIMEOUT);
    isPercentEncoded = carbonLogReader.checkForLog("ESB%2BWSO2", DEFAULT_TIMEOUT);
    Assert.assertTrue(isMessageContextPropertyPercentDecoded,
            "Uri-Template parameters should be percent decoded at message context property");
    Assert.assertFalse(isPercentEncoded,
            "Reserved character should not be percent encoded while uri-template expansion");
}
 
Example #2
Source File: LocationHeaderWithRelativeURLPathTestCase.java    From micro-integrator with Apache License 2.0 6 votes vote down vote up
@Test(groups = "wso2.esb", description = "Test to check whether location header value persists in the http response")
public void testForLocationHeaderInResponse() throws Exception {

    String proxyServiceUrl = getProxyServiceURLHttp("LocationHeaderTestProxy");

    String requestPayload = "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\">\n"
            + "   <soapenv:Header/>\n" + "   <soapenv:Body>\n" + "      <testBody>\n" + "      <foo/>\n"
            + "      </testBody>\n" + "   </soapenv:Body>\n" + "</soapenv:Envelope>\n";

    Map<String, String> headers = new HashMap<>();
    headers.put("SOAPAction", "urn:getQuote");

    HttpResponse response = HttpRequestUtil.doPost(new URL(proxyServiceUrl), requestPayload, headers);
    Map<String, String> responseHeaders = response.getHeaders();
    assertNotNull(responseHeaders, "Error in retrieving the response headers!");
    String locationHeaderValue = responseHeaders.get(LOCATION_HEADER_NAME);
    assertNotNull(locationHeaderValue, "Location header not set!");
    assertEquals(locationHeaderValue, EXPECTED_LOCATION_HEADER, "Incorrect location header!");
}
 
Example #3
Source File: CARBON15119DuplicateSOAPActionHeader.java    From product-ei with Apache License 2.0 6 votes vote down vote up
@Test(groups = "wso2.esb", description = "Test to check whether there are duplicate SOAPAction headers in the request to the service from callout mediator")
public void testCheckForDuplicateSOAPActionHeaders() throws Exception {

    String proxyServiceUrl = getProxyServiceURLHttp("DuplicateSOAPActionHeader");

    String requestPayload = "<soapenv:Envelope xmlns:soapenv='http://schemas.xmlsoap.org/soap/envelope/' >"
            + "<soapenv:Body xmlns:ser='http://services.samples' xmlns:xsd='http://services.samples/xsd'> "
            + "<ser:getQuote> <ser:request> <xsd:symbol>WSO2</xsd:symbol> </ser:request> </ser:getQuote> "
            + "</soapenv:Body></soapenv:Envelope> ";

    Map<String, String> headers = new HashMap<String, String>();
    headers.put("Soapaction", "urn:getQuote");

    HttpRequestUtil.doPost(new URL(proxyServiceUrl), requestPayload, headers);
    String capturedMsg = wireMonitorServer.getCapturedMessage();
 Assert.assertFalse(capturedMsg.contains("Soapaction"));
 Assert.assertTrue(capturedMsg.contains("SOAPAction"));
}
 
Example #4
Source File: MediationLibraryServiceTestCase.java    From product-ei with Apache License 2.0 6 votes vote down vote up
/**
 * Test for invoking connector service.
 *
 * @throws Exception
 */
@Test(groups = "wso2.esb", description = "Test connector upload and invoke.")
public void invokeConnectorTest() throws Exception {

    String apiURI = "http://localhost:8480/library-service/get-message";
    String expectedOutput = "<message>Bob</message>";
    String expectedOutputAtDisable =
            "<message>Sequence template org.wso2.carbon.connector.hello.init cannot be found</message>";

    loadESBConfigurationFromClasspath(
            File.separator + "artifacts" + File.separator + "ESB" + File.separator + "connector" + File.separator +
                    "MediationLibraryServiceTestAPI.xml");

    HttpResponse httpResponse = HttpRequestUtil.doPost(new URL(apiURI), "");
    Assert.assertEquals(httpResponse.getData(), expectedOutput, "Invoking hello connector fails.");

    //disable the hello library and try to invoke
    updateConnectorStatus(HELLO_CONNECTOR_LIB_QNAME, HELLO_LIB_NAME, PACKAGE_NAME, DISABLED);
    HttpResponse httpResponseAtDisable = HttpRequestUtil.doPost(new URL(apiURI), "");
    Assert.assertEquals(httpResponseAtDisable.getData(), expectedOutputAtDisable,
                        "Invoking disabled hello connector test fails.");

    //enable back hello library for other tests
    updateConnectorStatus(HELLO_CONNECTOR_LIB_QNAME, HELLO_LIB_NAME, PACKAGE_NAME, ENABLED);
}
 
Example #5
Source File: ESBJAVA5135ResponseBodyWith202TestCase.java    From product-ei with Apache License 2.0 6 votes vote down vote up
/**
 * Test response with 202 and body is built by ESB and responds client
 *
 * @throws AxisFault                    in case of an axis2 level issue when sending
 * @throws MalformedURLException        in case of url is malformed
 * @throws AutomationFrameworkException in case of any other test suite level issue
 */
@Test(groups = "wso2.esb", description = "Test response with 202 and body is built by ESB and responds client "
        + "properly")
public void testResponseWith202() throws AxisFault, MalformedURLException, AutomationFrameworkException {
    Map<String, String> requestHeader = new HashMap<>();
    requestHeader.put("Content-type", "text/xml");
    requestHeader.put("SOAPAction", "urn:mediate");
    String message = "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap"
            + ".org/soap/envelope/\">\n"
            + "   <soapenv:Header/>\n"
            + "   <soapenv:Body/>\n"
            + "</soapenv:Envelope>";

    HttpResponse response = HttpRequestUtil.
            doPost(new URL(getProxyServiceURLHttp("mockProxy")), message, requestHeader);

    Assert.assertTrue(response.getData().contains("Hello World"), "Expected response was not"
            + " received. Got " + response.getData());
}
 
Example #6
Source File: ESBJAVA3290TestXWWWFormURLEncodedFormatter.java    From product-ei with Apache License 2.0 6 votes vote down vote up
@SetEnvironment(executionEnvironments = {ExecutionEnvironment.STANDALONE})
@Test(groups = "wso2.esb", description = "POST request against REST endpoint where " +
                                         "body parameter name starts with digit")
public void testPostRequest() throws Exception {

    URL endpoint = new URL(getProxyServiceURLHttp("RestProxy"));
    try {
        Map<String, String> header = new HashMap<String, String>();
        header.put("Content-Type", "application/x-www-form-urlencoded");
        HttpRequestUtil.doPost(endpoint, "paramName=abc&2paramName=def&$paramName=ghi", header);

    } catch (Exception e){
        //ignore
    }

    String response = wireServer.getCapturedMessage();
    Assert.assertNotNull(response);
    Assert.assertTrue(response.contains("2paramName"), "POST request does not contain the " +
                                                       "body " +
                                                       "parameter name starts with digit " +
                                                       "specified");
    Assert.assertTrue(response.contains("$paramName"), "POST request does not contain the " +
                                                       "body " +
                                                       "parameter name starts with $ character " +
                                                       "specified");
}
 
Example #7
Source File: CacheControlHeadersTestCase.java    From product-ei with Apache License 2.0 6 votes vote down vote up
/**
 * This test case checks whether an Age header is returned with the response.
 *
 */
@SetEnvironment(executionEnvironments = {ExecutionEnvironment.STANDALONE})
@Test(groups = {"wso2.esb"}, description = "Testing with a large cache time out value for cache mediator")
public void testAgeHeader() throws Exception {
    String apiName = "includeAge";

    Map<String, String> headers = new HashMap<>();

    headers.put("Content-Type", "text/xml;charset=UTF-8");
    headers.put("SOAPAction", "urn:getQuote");

    //will not be a cache hit
    HttpRequestUtil.doPost(new URL(getApiInvocationURL(apiName)),
            messagePayload, headers);

    //will be a cache hit
    HttpResponse response2 = HttpRequestUtil.doPost(new URL(getApiInvocationURL(apiName)),
            messagePayload, headers);

    assertNotNull(response2.getHeaders().get("Age"), "Age header is not included");
}
 
Example #8
Source File: DBMediatorUseTransaction.java    From micro-integrator with Apache License 2.0 6 votes vote down vote up
/**
 * Test with UseTransaction flag. The transaction mediator is used to handle transactional behaviour.
 * The rollback operation is checked.
 *
 * @throws Exception
 */
@SetEnvironment(executionEnvironments = { ExecutionEnvironment.STANDALONE })
/*JIRA issue: https://wso2.org/jira/browse/ESBJAVA-1553*/
@Test(groups = "wso2.esb", description = "Test UseTransaction option ."
        + "Use in conjunction with Transaction mediator. Fail casse")
public void testDBmediatorFailCase() throws Exception {
    String sunStringtDB1, sunStringtDB2;
    sunStringtDB1 = getDatabaseResultsForDB1FailCase();
    assertTrue(sunStringtDB1.contains("SUN"), "Fault, invalid response");
    sunStringtDB2 = getDatabaseResultsForDB2FailCase();
    assertTrue(sunStringtDB2.contains("SUN"), "Fault, invalid response");
    HttpRequestUtil.doPost(new URL(getApiInvocationURL(API_URL + COMMIT_CONTEXT + "?nameEntry=SUN")), "");
    sunStringtDB1 = getDatabaseResultsForDB1FailCase();
    assertTrue(sunStringtDB1.contains("SUN"), "Fault, invalid response. Transaction is not rollbacked.");
    sunStringtDB2 = getDatabaseResultsForDB2FailCase();
    assertTrue(sunStringtDB2.contains("SUN"), "Fault, invalid response.Transaction is not rollbacked.");

}
 
Example #9
Source File: JSONTransformJSONSchemaTestCases.java    From product-ei with Apache License 2.0 6 votes vote down vote up
@Test(groups = "wso2.esb", description = "Changing the JSON payload against a not existing registry schema")
public void testNotExistingJsonSchema() throws Exception {
    logViewer.clearLogs();
    String payload = "{\n" +
            "  \"fruit\"           : \"12345\",\n" +
            "  \"price\"           : \"7.5\",\n" +
            "  \"nestedObject\"    : {\"Lahiru\" :{\"age\":\"27\"},\"Nimal\" :{\"married\" :\"true\"}, \"Kamal\" " +
            ": {\"scores\": [\"24\",45,\"67\"]}},\n" +
            "  \"nestedArray\"     : [[12,\"23\",34],[\"true\",false],[\"Linking Park\",\"Coldplay\"]]\n" +
            "}";
    Map<String, String> httpHeaders = new HashMap<>();
    httpHeaders.put("Content-Type", "application/json");
    String expected_error = "Schema does not exist in the specified location : conf:/simpleSchemaNotexisting.json";
    HttpRequestUtil.doPost(
            new URL(getProxyServiceURLHttp("transformMediatorNotExistingSchema")), payload, httpHeaders);
    LogEvent[] logs = logViewer.getAllRemoteSystemLogs();
    boolean isErrorLogFound = false;
    for (LogEvent logEvent : logs) {
        if (logEvent.getMessage().contains(expected_error)) {
            isErrorLogFound = true;
            break;
        }
    }
    assertTrue(isErrorLogFound, "Expected error message not received when not existing schema is provided");
}
 
Example #10
Source File: ForceMessageValidationTestCase.java    From product-ei with Apache License 2.0 6 votes vote down vote up
/**
 * Test for invalid JSON message with force.json.message.validation property.
 *
 * @throws Exception
 */
@Test(groups = "wso2.esb", description = "Test for invalid JSON payload with force.json.message.validation "
        + "property.")
public void testInvalidJSONMessage() throws Exception {
    logViewerClient.clearLogs();

    String inputPayload = "{\"abc\" :\"123\" } xyz";
    String expectedOutput = "Error while building the message.\n" + "{\"abc\" :\"123\" } xyz";

    Map<String, String> requestHeader = new HashMap<>();
    requestHeader.put("Content-type", "application/json");

    HttpRequestUtil.doPost(new URL(getApiInvocationURL(API_NAME)), inputPayload, requestHeader);

    Assert.assertTrue(Utils.assertIfSystemLogContains(logViewerClient, expectedOutput), "Test fails for forcing "
            + "JSON validation with force.json.message.validation passthru-http property.");
}
 
Example #11
Source File: ESBJAVA4468ContentTypeCharsetInResponseTestCase.java    From micro-integrator with Apache License 2.0 6 votes vote down vote up
@Test(groups = { "wso2.esb" }, description = "Test for charset value in the Content-Type header "
        + "in response once message is built in out out sequence " + "with messageType")
public void charsetTestByChangingContentType() throws Exception {

    Map<String, String> headers = new HashMap<>();

    headers.put("Content-Type", "text/xml;charset=UTF-8");
    headers.put("SOAPAction", "urn:getQuote");

    HttpResponse response = HttpRequestUtil
            .doPost(new URL(getProxyServiceURLHttp("contentTypeCharsetProxy2")), messagePayload, headers);
    Assert.assertNotNull(response, "Response is null");
    Assert.assertTrue(response.getData().contains("WSO2 Company"), "Response not as expected " + response);

    String contentType = response.getHeaders().get("Content-Type");
    //Removing since a invalid scenario after the fix for https://wso2.org/jira/browse/ESBJAVA-1994
    //Assert.assertTrue(contentType.contains("application/xml"), "Content-Type is not changed " + contentType);
    Assert.assertEquals(StringUtils.countMatches(contentType, HTTPConstants.CHAR_SET_ENCODING), 1,
            "charset repeated in Content-Type header " + contentType);
}
 
Example #12
Source File: ESBJAVA4468ContentTypeCharsetInResponseTestCase.java    From micro-integrator with Apache License 2.0 6 votes vote down vote up
@Test(groups = { "wso2.esb" }, description = "Test for charset value in the Content-Type header "
        + "in response once message is built in out out sequence " + "with messageType with charset")
public void charsetTestByChangingContentTypeWithCharset() throws Exception {

    Map<String, String> headers = new HashMap<>();

    headers.put("Content-Type", "text/xml;charset=UTF-8");
    headers.put("SOAPAction", "urn:getQuote");

    HttpResponse response = HttpRequestUtil
            .doPost(new URL(getProxyServiceURLHttp("contentTypeCharsetProxy3")), messagePayload, headers);
    Assert.assertNotNull(response, "Response is null");
    Assert.assertTrue(response.getData().contains("WSO2 Company"), "Response not as expected " + response);

    String contentType = response.getHeaders().get("Content-Type");
    //Removing Invalid scenario after the fix for https://wso2.org/jira/browse/ESBJAVA-1994
    //Assert.assertTrue(contentType.contains("application/xml"), "Content-Type is not changed " + contentType);
    Assert.assertEquals(StringUtils.countMatches(contentType, HTTPConstants.CHAR_SET_ENCODING), 1,
            "charset repeated in Content-Type header " + contentType);
}
 
Example #13
Source File: JSONTransformJSONSchemaTestCases.java    From product-ei with Apache License 2.0 6 votes vote down vote up
@Test(groups = "wso2.esb", description = "Changing XML payload to JSON payload with simple Schema " +
        "stored in Local Entry")
public void testSimpleXMLToJsonWithSchemaLocalEntry() throws Exception {
    String payload = "<jsonObject>\n" +
            "    <fruit>12345</fruit>\n" +
            "    <price>7.5</price>\n" +
            "</jsonObject>";
    Map<String, String> httpHeaders = new HashMap<>();
    httpHeaders.put("Content-Type", "application/xml");
    String expectedOutput = "{\n" +
            "    \"fruit\": \"12345\",\n" +
            "    \"price\": 7.5\n" +
            "}";
    HttpResponse response = HttpRequestUtil.doPost(
            new URL(getProxyServiceURLHttp("transformMediatorSimpleXMLtoJSONWithSchemaLocalEntry")),
            payload, httpHeaders);
    assertEqualJsonObjects(response.getData(), expectedOutput,
            "Simple XML to JSON transformation with a simple schema did not happen properly");
}
 
Example #14
Source File: XMLToJsonTestCase.java    From product-ei with Apache License 2.0 6 votes vote down vote up
@Test(groups = {"wso2.esb"}, description = "Test XML to JSON conversion")
public void testXmlToJson() throws Exception {

    String xmlPayload = "<location>\n" +
            "               <name>Bermuda Triangle</name>\n" +
            "               <n>25.0000</n>\n" +
            "               <w>71.0000</w>\n" +
            "            </location>";
    Map<String, String> requestHeader = new HashMap<>();
    requestHeader.put("Content-Type", "text/xml");
    HttpResponse response = HttpRequestUtil.
            doPost(new URL(getProxyServiceURLHttp("xmlToJsonTestProxy")), xmlPayload, requestHeader);

    Assert.assertEquals(response.getData(), "{\"location\":{\"name\":\"Bermuda Triangle\",\"n\":25.0000,\"w\":71.0000}}",
            "Invalid XML to JSON conversion. " + response.getData());
}
 
Example #15
Source File: ESBJAVA3751UriTemplateReservedCharacterEncodingTest.java    From micro-integrator with Apache License 2.0 6 votes vote down vote up
@Test(groups = { "wso2.esb" }, description = "Sending http request with a query param consist of"
        + " reserved + character ")
public void testURITemplateParameterDecodingPlusCharacterCase() throws Exception {
    carbonLogReader.clearLogs();
    boolean isPercentEncoded = false;
    boolean isMessageContextPropertyPercentDecoded = false;
    HttpResponse response = HttpRequestUtil
            .sendGetRequest(getApiInvocationURL("services/client/urlEncoded?queryParam=ESB+WSO2"), null);
    String decodedMessageContextProperty = "decodedQueryParamValue = ESB+WSO2";
    isMessageContextPropertyPercentDecoded =
            carbonLogReader.checkForLog(decodedMessageContextProperty, DEFAULT_TIMEOUT);
    isPercentEncoded = carbonLogReader.checkForLog("ESB%2BWSO2", DEFAULT_TIMEOUT);
    Assert.assertTrue(isMessageContextPropertyPercentDecoded,
            "Uri-Template parameters should be percent decoded at message context property");
    Assert.assertTrue(isPercentEncoded,
            "Reserved character should be percent encoded while uri-template expansion");
}
 
Example #16
Source File: JSONPayloadProperFormatTenantModeTestCase.java    From micro-integrator with Apache License 2.0 6 votes vote down vote up
@Test(groups = "wso2.esb", description = "Check whether JSON message formatting works properly in tenant mode")
public void testJSONFormattingInTenantMode() throws MalformedURLException, AutomationFrameworkException {
    String JSON_PAYLOAD = "{\"emails\": [{\"value\": \"[email protected]\"}]}";
    Map<String, String> headers = new HashMap<>();
    headers.put("Content-Type", "application/json");
    HttpResponse response = HttpRequestUtil
            .doPost(new URL("http://localhost:8480/json/payload"), JSON_PAYLOAD, headers);

    //checking whether JSON payload of wrong format is received
    assertFalse(response.getData().equals("{\"emails\":{\"value\":\"[email protected]\"}}"),
            "Incorrect format received!");

    //checking whether JSON payload of correct format is present
    assertTrue(response.getData().equals("{\"emails\": [{\"value\": \"[email protected]\"}]}"),
            "Expected format not received!");
}
 
Example #17
Source File: APIMANAGER1838RequestHashGeneratorTestCase.java    From micro-integrator with Apache License 2.0 6 votes vote down vote up
@Test(groups = {
        "wso2.esb" }, dependsOnMethods = "addPeople", description = "Retrieving people from PeopleRestService")
public void getPeople() throws Exception {

    if (isTomcatServerRunning(tomcatServerManager, 5000)) {
        HttpResponse response1 = HttpRequestUtil
                .sendGetRequest(getApiInvocationURL("APIM1838getPerson") + "/[email protected]", null);
        assertEquals(response1.getResponseCode(), 200, "Response code mismatch");
        assertTrue(response1.getData().contains("John"), "Response message is not as expected.");
        assertTrue(response1.getData().contains("Doe"), "Response message is not as expected");

        HttpResponse response2 = HttpRequestUtil
                .sendGetRequest(getApiInvocationURL("APIM1838getPerson") + "/[email protected]", null);
        assertEquals(response2.getResponseCode(), 200, "Response code mismatch");
        assertTrue(response2.getData().contains("Jane"), "Response message is not as expected.");
        assertTrue(response2.getData().contains("Doe"), "Response message is not as expected");
    } else {
        Assert.fail("Jaxrs Service Startup failed");
    }
}
 
Example #18
Source File: ESBJAVA4721PIWithCacheTestCase.java    From product-ei with Apache License 2.0 6 votes vote down vote up
@Test(groups = "wso2.esb",
      description = "Test cache mediator with  Json response having a single element array with PI enabled")
public void testJsonResponseWithCacheMediator() throws IOException, AutomationFrameworkException {

    Map<String, String> requestHeader = new HashMap<>();
    requestHeader.put("Content-type", "application/json");

    //will not be a cache hit
    HttpRequestUtil.doGet((getApiInvocationURL("cachingEnabledApi") + "/singleElementArrayBackend"), requestHeader);

    //will be a cache hit
    HttpResponse response = HttpRequestUtil.
            doGet((getApiInvocationURL("cachingEnabledApi") + "/singleElementArrayBackend"), requestHeader);

    //check if [] are preserved in response
    Assert.assertTrue(response.getData().contains("[ \"water\" ]"),
            "Expected response was not" + " received. Got " + response.getData());
}
 
Example #19
Source File: ESBJAVA3340QueryParamHttpEndpointTestCase.java    From micro-integrator with Apache License 2.0 6 votes vote down vote up
@Test(groups = {
        "wso2.esb"}, description = "Sending a Message Via REST to test query param works with space character")
public void testPassParamsToEndpoint() throws InterruptedException {
    String requestString = "/context?queryParam=some%20value";
    boolean isSpaceCharacterEscaped;
    try {
        HttpRequestUtil.sendGetRequest(getApiInvocationURL("passParamsToEPTest") + requestString, null);
    } catch (Exception timeout) {
        //a timeout is expected
    }
    isSpaceCharacterEscaped = carbonLogReader.checkForLog("queryParam = some%20value", DEFAULT_TIMEOUT);
    carbonLogReader.stop();

    Assert.assertTrue(isSpaceCharacterEscaped,
            "Fail to send a message via REST when query parameter consist of space character");
}
 
Example #20
Source File: JsonResponseWithCacheTestCase.java    From micro-integrator with Apache License 2.0 6 votes vote down vote up
@Test(groups = "wso2.esb", description = "Test cache mediator with  Json response having a single element array", enabled = false)
public void testJsonResponseWithCacheMediator() throws IOException, AutomationFrameworkException {

    Map<String, String> requestHeader = new HashMap<>();
    requestHeader.put("Content-type", "application/json");

    //will not be a cache hit
    HttpRequestUtil.doGet((getApiInvocationURL("cachingEnabledApi") + "/singleElementArrayBackend"), requestHeader);

    //will be a cache hit
    HttpResponse response = HttpRequestUtil.
            doGet((getApiInvocationURL("cachingEnabledApi") + "/singleElementArrayBackend"), requestHeader);

    //check if [] are preserved in response
    Assert.assertTrue(response.getData().contains("[ \"water\" ]"),
            "Expected response was not" + " received. Got " + response.getData());
}
 
Example #21
Source File: ESBJAVA4468ContentTypeCharsetInResponseTestCase.java    From product-ei with Apache License 2.0 6 votes vote down vote up
@Test(groups = {"wso2.esb"}, description = "Test for charset value in the Content-Type header " +
                                           "in response once message is built in out out sequence " +
                                           "with messageType")
public void charsetTestByChangingContentType() throws Exception {

    Map<String, String> headers = new HashMap<>();

    headers.put("Content-Type", "text/xml;charset=UTF-8");
    headers.put("SOAPAction", "urn:getQuote");

    HttpResponse response = HttpRequestUtil.doPost(new URL(getProxyServiceURLHttp("contentTypeCharsetProxy2"))
            , messagePayload, headers);
    Assert.assertNotNull(response, "Response is null");
    Assert.assertTrue(response.getData().contains("WSO2 Company"), "Response not as expected " + response);

    String contentType = response.getHeaders().get("Content-Type");
    //Removing since a invalid scenario after the fix for https://wso2.org/jira/browse/ESBJAVA-1994
    //Assert.assertTrue(contentType.contains("application/xml"), "Content-Type is not changed " + contentType);
    Assert.assertEquals(StringUtils.countMatches(contentType, HTTPConstants.CHAR_SET_ENCODING), 1
            , "charset repeated in Content-Type header " + contentType);
}
 
Example #22
Source File: ForEachManagedLifecycleTestCase.java    From micro-integrator with Apache License 2.0 6 votes vote down vote up
@Test(groups = { "wso2.esb" }, description = "testManagedLifecycle")
public void testManagedLifecycle() throws Exception {

    Map<String, String> requestHeader = new HashMap<>();
    requestHeader.put("Content-Type", "text/xml");
    requestHeader.put("SOAPAction", "urn:mediate");
    String message = "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\">\n"
            + "   <soapenv:Header/>\n" + "   <soapenv:Body>\n" + "   <stock>\n" + "   <company>IBM</company>\n"
            + "   <company>SUN</company>\n" + "   </stock>\n" + "   </soapenv:Body>\n" + "</soapenv:Envelope>";

    HttpResponse response = HttpRequestUtil.
            doPost(new URL(getProxyServiceURLHttp("forEachManagedLifeCycleTestProxy")), message, requestHeader);

    Assert.assertTrue(response.getData().contains("Message mediation successful"),
            "Invalid response received. " + response.getData());
}
 
Example #23
Source File: TransactionMediatorTestCase.java    From micro-integrator with Apache License 2.0 6 votes vote down vote up
/**
 * Test for use-existing-or-new action for using an existing transaction
 *
 * @throws Exception
 */
@Test(groups = "wso2.esb", description = "Test use-existing-or-new action for using an existing transaction")
public void useExistingTransactionTest() throws Exception {

    String expectedOutputForNick = "<response><table1>4</table1><table2>4</table2></response>";
    String expectedOutputForJohn = "<response><table1>5</table1><table2>5</table2></response>";

    HttpRequestUtil.doPost(new URL(API_URL + USE_EXISTING_NEW_CONTEXT + "?testEntry=John&entryId=5"), "");
    HttpResponse httpResponseForNick = HttpRequestUtil
            .doPost(new URL(API_URL + TEST_CONTEXT + "?testEntry=Nick"), "");
    HttpResponse httpResponseForJohn = HttpRequestUtil
            .doPost(new URL(API_URL + TEST_CONTEXT + "?testEntry=John"), "");

    boolean satisfyEntryNick = httpResponseForNick.getData().equals(expectedOutputForNick);
    boolean satisfyEntryJohn = httpResponseForJohn.getData().equals(expectedOutputForJohn);

    Assert.assertTrue(satisfyEntryJohn & satisfyEntryNick,
            "Use-existing-or-new action fails for using an existing transaction in transaction mediator");
}
 
Example #24
Source File: ESBJAVA4931PreserveContentTypeHeaderCharSetTestCase.java    From micro-integrator with Apache License 2.0 5 votes vote down vote up
@Test(groups = "wso2.esb", description =
        "Test to check whether the Content-Type header charset is preserved when sending " + "requests to back end")
public void testPreserveContentTypeHeader() throws Exception {

    String proxyServiceUrl = getProxyServiceURLHttp("PreserveContentTypeHeaderCharSetTestProxy");

    String requestPayload = "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\">\n"
            + "   <soapenv:Header/>\n" + "   <soapenv:Body>\n"
            + "   <p:getSimpleQuote xmlns:p=\"http://services.samples\">\n"
            + "      <xs:symbol xmlns:xs=\"http://services.samples\">IBM</xs:symbol>\n" + "   </p:getSimpleQuote>\n"
            + "   </soapenv:Body>\n" + "</soapenv:Envelope>";

    Map<String, String> headers = new HashMap<String, String>();
    headers.put("SOAPAction", "urn:mediate");
    headers.put("Content-type", "text/xml;charset=UTF-8");

    HttpRequestUtil.doPost(new URL(proxyServiceUrl), requestPayload, headers);

    String wireResponse = wireMonitorServer.getCapturedMessage();
    String[] wireResponseList = wireResponse.split(System.lineSeparator());

    Assert.assertTrue(wireResponse.contains("Content-Type"),
            "Request to the backend doesn't contain Content-Type header");
    boolean isCharSetPreserved = false;
    for (String line : wireResponseList) {
        if (line.contains("Content-Type")) {
            if (line.contains("text/xml; charset=UTF-8")) {
                isCharSetPreserved = true;
            }
        }
    }
    Assert.assertTrue(isCharSetPreserved, "Charset has been dropped from Content-Type header");
}
 
Example #25
Source File: TransactionMediatorTestCase.java    From product-ei with Apache License 2.0 5 votes vote down vote up
/**
 * Test for identifying no transaction with fault-if-no-tx action
 *
 * @throws Exception
 */
@Test(groups = "wso2.esb", description = "Test fault-if-no-tx transaction")
public void faultIfNoTxTransactionTest() throws Exception {

    String expectedOutput = "<response><message>No Transactions</message></response>";

    HttpResponse httpResponse = HttpRequestUtil.doPost(new URL(API_URL + FAULT_NOTX_CONTEXT), "");

    Assert.assertEquals(httpResponse.getData(), expectedOutput,
                        "Fault-if-no-tx transaction fails in transaction mediator");
}
 
Example #26
Source File: DBMediatorUseTransaction.java    From micro-integrator with Apache License 2.0 5 votes vote down vote up
/**
 * Initialize database by creating necessary tables and entries for following tests
 *
 * @throws Exception
 */
@BeforeClass(alwaysRun = true)
public void setEnvironment() throws Exception {
    super.init();
    HttpRequestUtil.doPost(new URL(getApiInvocationURL(API_URL + INIT_CONTEXT_1)), "");
    HttpRequestUtil.doPost(new URL(getApiInvocationURL(API_URL + INIT_CONTEXT_2)), "");
}
 
Example #27
Source File: FaultSeqInvokeWithAggregateTimeoutTestCase.java    From product-ei with Apache License 2.0 5 votes vote down vote up
@Test(groups = "wso2.esb", description = "Add a non-existing mediator and check if fault sequence is hit upon " +
        "onComplete of aggregate mediator with timeout condition")
public void testFaultResponseIsReceived() throws AxisFault, MalformedURLException, AutomationFrameworkException {
    Map<String, String> requestHeader = new HashMap<>();
    requestHeader.put("Content-type", "application/xml");
    String message = "<marketDetail>\n" +
            "    <market>\n" +
            "        <id>100</id>\n" +
            "        <openTime>10.00AM</openTime>\n" +
            "        <closeTime>4.00PM</closeTime>\n" +
            "        <name>New York</name>\n" +
            "    </market>\n" +
            "    <market>\n" +
            "        <id>200</id>\n" +
            "        <openTime>9.00AM</openTime>\n" +
            "        <closeTime>5.00PM</closeTime>\n" +
            "        <name>London</name>\n" +
            "    </market>\n" +
            "    <market>\n" +
            "        <id>300</id>\n" +
            "        <openTime>8.00AM</openTime>\n" +
            "        <closeTime>3.00PM</closeTime>\n" +
            "        <name>Colombo</name>\n" +
            "    </market>\n" +
            "    <market>\n" +
            "        <id>250</id>\n" +
            "        <openTime>8.00AM</openTime>\n" +
            "        <closeTime>8.00PM</closeTime>\n" +
            "        <name>London</name>\n" +
            "    </market>\n" +
            "</marketDetail>";
    HttpResponse response = HttpRequestUtil.
            doPost(new URL(getApiInvocationURL("testApiAggregate")), message, requestHeader);

    Assert.assertTrue(response.getData().contains("SEQUENCE_ERROR_HANDLER"), "Expected response was not"
            + " received. Got " + response.getData());
}
 
Example #28
Source File: ESBJAVA3751UriTemplateReservedCharacterEncodingTest.java    From product-ei with Apache License 2.0 5 votes vote down vote up
@Test(groups = { "wso2.esb" }, description = "Sending http request with a query param consist of" +
        " reserved + character ")
public void testURITemplateParameterDecodingPlusCharacterCase() throws Exception {
    boolean isPercentEncoded = false;
    boolean isMessageContextPropertyPercentDecoded = false;
    logViewerClient.clearLogs();
    HttpResponse response = HttpRequestUtil.sendGetRequest(
            getApiInvocationURL("services/client/urlEncoded?queryParam=ESB+WSO2"),
            null);
    String decodedMessageContextProperty="decodedQueryParamValue = ESB+WSO2";
    LogEvent[] logs = logViewerClient.getAllRemoteSystemLogs();
    for (LogEvent logEvent : logs) {
        String message = logEvent.getMessage();
        if (message.contains(decodedMessageContextProperty)) {
            isMessageContextPropertyPercentDecoded = true;
            continue;
        }
        if (message.contains("ESB%2BWSO2")) {
            isPercentEncoded = true;
            continue;
        }
    }
    Assert.assertTrue(isMessageContextPropertyPercentDecoded,
            "Uri-Template parameters should be percent decoded at message context property");
    Assert.assertTrue(isPercentEncoded,
            "Reserved character should be percent encoded while uri-template expansion");
}
 
Example #29
Source File: ESBJAVA4781EscapeAutoPrimitiveTestCase.java    From product-ei with Apache License 2.0 5 votes vote down vote up
@Test(groups = "wso2.esb", description = "Check whether JSON field value auto primitive is escaped if field value starting region " +
        "is matched with replace regex after flowing through Staxon formatter in passthrough transport | matched starting region" +
        "will be replaced")
public void testJSONEmptyArrayMissingNHTTPTransport() throws Exception {
  HttpResponse response = HttpRequestUtil.sendGetRequest(getApiInvocationURL("formatterEscapePrimitiveSequenceAPI/escapePrimitive"), null);
  String expected = "{\"testEscapePrimitive\":{\"integer\":1989,\"float\":1989.9,\"null\":null,\"boolean_true\":true," +
          "\"boolean_false\":false,\"string\":\"string\",\"integer_escaped\":\"1989\",\"float_escaped\":\"1989.9\",\"null_escaped\":\"null\"," +
          "\"boolean_true_escaped\":\"true\",\"boolean_false_escaped\":\"false\",\"string_escaped\":\"string\"}}";

  Assert.assertTrue("JSON field value auto primitive has not not been escaped from formatter" +
          " when if field value starting region is matched with replace regex.", expected.equals(response.getData()));

}
 
Example #30
Source File: TransactionMediatorTestCase.java    From product-ei with Apache License 2.0 5 votes vote down vote up
/**
 * Test for creating a new transaction with new and commit actions
 *
 * @throws Exception
 */
@Test(groups = "wso2.esb", description = "Test commit transaction")
public void commitTransactionTest() throws Exception {

    String expectedOutput = "<response><table1/><table2>2</table2></response>";

    HttpRequestUtil.doPost(new URL(API_URL + COMMIT_CONTEXT), "");
    HttpResponse httpResponse = HttpRequestUtil.doPost(new URL(API_URL + TEST_CONTEXT + "?testEntry=Alice"), "");

    Assert.assertEquals(httpResponse.getData(), expectedOutput, "Commit transaction fails in transaction mediator");
}