Java Code Examples for org.apache.axis2.transport.http.HTTPConstants

The following examples show how to use org.apache.axis2.transport.http.HTTPConstants. These examples are extracted from open source projects. 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 Project: micro-integrator   Source File: ParallelRequestHelper.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * constructor for parallel request helper
 * we can use this for the initial begin boxcarring request as well.(sending sessionCookie null)
 *
 * @param sessionCookie
 * @param operation
 * @param payload
 * @param serviceEndPoint
 * @throws org.apache.axis2.AxisFault
 */
public ParallelRequestHelper(String sessionCookie, String operation, OMElement payload, String serviceEndPoint)
        throws AxisFault {
    this.payload = payload;
    sender = new ServiceClient();
    Options options = new Options();
    options.setTo(new EndpointReference(serviceEndPoint));
    options.setProperty("__CHUNKED__", Boolean.FALSE);
    options.setTimeOutInMilliSeconds(45000L);
    options.setAction("urn:" + operation);
    sender.setOptions(options);
    if (sessionCookie != null && !sessionCookie.isEmpty()) {
        Header header = new Header("Cookie", sessionCookie);
        ArrayList headers = new ArrayList();
        headers.add(header);
        sender.getOptions().setProperty(HTTPConstants.HTTP_HEADERS, headers);
    }
}
 
Example 2
@Test(groups = { "wso2.esb" }, description = "Test for charset value in the Content-Type header "
        + "in response once message is built in out out sequence")
public void charsetTestWithInComingContentType() 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("contentTypeCharsetProxy1")), 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");
    Assert.assertTrue(contentType.contains("text/xml"), "Content-Type mismatched " + contentType);
    Assert.assertEquals(StringUtils.countMatches(contentType, HTTPConstants.CHAR_SET_ENCODING), 1,
            "charset repeated in Content-Type header " + contentType);

}
 
Example 3
@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 4
Source Project: micro-integrator   Source File: AuthenticatorClient.java    License: Apache License 2.0 6 votes vote down vote up
public String login(String userName, String password, String host) throws
        Exception {
    Boolean loginStatus;
    ServiceContext serviceContext;
    String sessionCookie;
    loginStatus = authenticationAdminStub.login(userName, password, host);
    if (!loginStatus) {
        throw new Exception("Login Unsuccessful. Return false as a login status by Server");
    }
    log.info("Login Successful");
    serviceContext = authenticationAdminStub._getServiceClient().getLastOperationContext().getServiceContext();
    sessionCookie = (String) serviceContext.getProperty(HTTPConstants.COOKIE_STRING);
    if (log.isDebugEnabled()) {
        log.debug("SessionCookie :" + sessionCookie);
    }
    return sessionCookie;
}
 
Example 5
/**
 * This test is to verify if division operation can be performed with given xml payload using
 *  datamapper mediator.
 */
@Test(description = "1.6.12.4")
public void performDivisionOperationUsingDatamapper() throws IOException, XMLStreamException {
    String testCaseId = "1.6.12.4";
    String apiInvocationUrl = getApiInvocationURLHttp(API_NAME +"/divide");
    String request =
            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
                    + "<DivideNumbers>\n"
                    + "    <num1>10</num1>\n"
                    + "    <num2>5</num2>\n"
                    + "</DivideNumbers>";

    String expectedResponse =
            "<ResultDivide>\n"
                    + "    <result>2.0</result>\n"
                    + "</ResultDivide>";
    String jdk11ExpectedResponse =
            "<ResultDivide>\n"
                    + "    <result>2</result>\n"
                    + "</ResultDivide>";

    HTTPUtils.invokePoxEndpointAndAssertTwoPayloads(apiInvocationUrl, request,
            HTTPConstants.MEDIA_TYPE_APPLICATION_XML,
            testCaseId, expectedResponse, jdk11ExpectedResponse, 200, "performDivisionOperationUsingDatamapper");

}
 
Example 6
/**
 * Query the remote user manager and retrieve the list of role names in users-store
 *
 *

 * @return the list of roles
 * @throws APIManagementException If and error occurs while accessing the admin service
 */
public String[] getRoleNames() throws APIManagementException {
    CarbonUtils.setBasicAccessSecurityHeaders(username, password, userStoreManager._getServiceClient());
    if (cookie != null) {
        userStoreManager._getServiceClient().getOptions().setProperty(HTTPConstants.COOKIE_STRING, cookie);
    }

    try {
        String[] roles = userStoreManager.getRoleNames();
        ServiceContext serviceContext = userStoreManager.
                _getServiceClient().getLastOperationContext().getServiceContext();
        cookie = (String) serviceContext.getProperty(HTTPConstants.COOKIE_STRING);
        return roles;
    } catch (Exception e) {
        throw new APIManagementException("Error while accessing backend services for " +
                                         "getting list of all the roles.", e);
    }
}
 
Example 7
/**
 * This test is to verify if it can get the ceiling value with given xml payload using
 *  datamapper mediator.
 */
@Test(description = "1.6.12.6")
public void getCeilingValueUsingDatamapper() throws IOException, XMLStreamException {
    String testCaseId = "1.6.12.6";
    String apiInvocationUrl = getApiInvocationURLHttp(API_NAME +"/ceiling");
    String request =
            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
                    + "<CeilingValue>\n"
                    + "    <num1>1.1</num1>\n"
                    + "</CeilingValue>";

    String expectedResponse =
            "<ResultCeilingValue>\n"
                    + "    <result>2.0</result>\n"
                    + "</ResultCeilingValue>";

    String jdk11ExpectedResponse =
            "<ResultCeilingValue>\n"
                    + "    <result>2</result>\n"
                    + "</ResultCeilingValue>";

    HTTPUtils.invokePoxEndpointAndAssertTwoPayloads(apiInvocationUrl, request,
            HTTPConstants.MEDIA_TYPE_APPLICATION_XML,
            testCaseId, expectedResponse, jdk11ExpectedResponse, 200, "getCeilingValueUsingDatamapper");

}
 
Example 8
/**
 * This test is to verify if it can get the floor value with given xml payload using
 *  datamapper mediator.
 */
@Test(description = "1.6.12.10")
public void getFloorValueUsingDatamapper() throws IOException, XMLStreamException {
    String testCaseId = "1.6.12.10";
    String apiInvocationUrl = getApiInvocationURLHttp(API_NAME +"/floor");
    String request =
            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
                    + "<FloorValue>\n"
                    + "    <num1>4.5</num1>\n"
                    + "</FloorValue>";

    String expectedResponse =
            "<ResultFloorValue>\n"
                    + "    <result>4.0</result>\n"
                    + "</ResultFloorValue>";

    String jdk11ExpectedResponse =
            "<ResultFloorValue>\n"
                    + "    <result>4</result>\n"
                    + "</ResultFloorValue>";

    HTTPUtils.invokePoxEndpointAndAssertTwoPayloads(apiInvocationUrl, request,
            HTTPConstants.MEDIA_TYPE_APPLICATION_XML,
            testCaseId, expectedResponse, jdk11ExpectedResponse, 200, "getFloorValueUsingDatamapper");

}
 
Example 9
private void initConfigurationContext() throws Exception {
    HttpConnectionManager multiThreadedHttpConnectionManager = new MultiThreadedHttpConnectionManager();
    HttpClient httpClient = new HttpClient(multiThreadedHttpConnectionManager);

    File configFile = new File(DEFAULT_AXIS2_XML);

    if (!configFile.exists()) {
        configurationContext = ConfigurationContextFactory.createDefaultConfigurationContext();
        configurationContext.setProperty(HTTPConstants.DEFAULT_MAX_CONNECTIONS_PER_HOST, MAX_CONNECTIONS_PER_HOST);
    } else {
        configurationContext = ConfigurationContextFactory.
                createConfigurationContextFromFileSystem(DEFAULT_CLIENT_REPO, DEFAULT_AXIS2_XML);
    }
    configurationContext.setProperty(HTTPConstants.CACHED_HTTP_CLIENT, httpClient);
    configurationContext.setProperty(HTTPConstants.REUSE_HTTP_CLIENT, Constants.VALUE_TRUE);

    Map<String, TransportOutDescription> transportsOut = configurationContext.getAxisConfiguration()
            .getTransportsOut();

    for (TransportOutDescription transportOutDescription : transportsOut.values()) {
        if (Constants.TRANSPORT_HTTP.equals(transportOutDescription.getName()) || Constants.TRANSPORT_HTTPS
                .equals(transportOutDescription.getName())) {
            transportOutDescription.getSender().init(configurationContext, transportOutDescription);
        }
    }
}
 
Example 10
Source Project: Java_CTe   Source File: Inutilizar.java    License: MIT License 6 votes vote down vote up
private static TRetInutCTe enviaMS(ConfiguracoesCte config, OMElement ome) throws JAXBException, CteException, RemoteException {

        CteInutilizacaoStub stub = new CteInutilizacaoStub(
                WebServiceCteUtil.getUrl(config, ServicosEnum.INUTILIZACAO));

        CteInutilizacaoStub.CteDadosMsg dadosMsg = new CteInutilizacaoStub.CteDadosMsg();
        dadosMsg.setExtraElement(ome);

        CteInutilizacaoStub.CTeCabecMsg cteCabecMsg = new CteInutilizacaoStub.CTeCabecMsg();
        cteCabecMsg.setCUF(String.valueOf(config.getEstado().getCodigoUF()));
        cteCabecMsg.setVersaoDados(ConstantesCte.VERSAO.CTE);

        CteInutilizacaoStub.CteCabecMsgE cteCabecMsgE = new CteInutilizacaoStub.CteCabecMsgE();
        cteCabecMsgE.setCteCabecMsg(cteCabecMsg);

        // Timeout
        if (ObjetoCTeUtil.verifica(config.getTimeout()).isPresent()) {
            stub._getServiceClient().getOptions().setProperty(HTTPConstants.SO_TIMEOUT, config.getTimeout());
            stub._getServiceClient().getOptions().setProperty(HTTPConstants.CONNECTION_TIMEOUT, config.getTimeout());
        }
        CteInutilizacaoStub.CteInutilizacaoCTResult result = stub.cteInutilizacaoCT(dadosMsg, cteCabecMsgE);

        LoggerUtil.log(Inutilizar.class, "[XML-RETORNO]: " + result.getExtraElement().toString());
        return XmlCteUtil.xmlToObject(result.getExtraElement().toString(), TRetInutCTe.class);
    }
 
Example 11
Source Project: carbon-identity   Source File: IdentityProviderService.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * @param username
 * @param operation
 * @throws IdentityProviderException
 */
private void checkUserAuthorization(String username, String operation) throws IdentityProviderException {
    MessageContext msgContext = MessageContext.getCurrentMessageContext();
    HttpServletRequest request = (HttpServletRequest) msgContext.getProperty(HTTPConstants.MC_HTTP_SERVLETREQUEST);
    HttpSession httpSession = request.getSession(false);

    String tenantFreeUsername = MultitenantUtils.getTenantAwareUsername(username);

    if (httpSession != null) {
        String loggedInUsername = (String) httpSession.getAttribute(ServerConstants.USER_LOGGED_IN);
        if (!tenantFreeUsername.equals(loggedInUsername)) {
            throw new IdentityProviderException("Unauthorised action by user " + username
                                                + " to access " + operation);
        }
    } else {
        throw new IdentityProviderException("Unauthorised action by user " + tenantFreeUsername
                                            + " to access " + operation);
    }
}
 
Example 12
Source Project: Java_CTe   Source File: ConsultaRecibo.java    License: MIT License 6 votes vote down vote up
private static TRetConsReciCTe envioStubMS(ConfiguracoesCte config, OMElement ome) throws CteException, RemoteException, JAXBException {

        CteRetRecepcaoStub.CteDadosMsg dadosMsg = new CteRetRecepcaoStub.CteDadosMsg();
        dadosMsg.setExtraElement(ome);

        CteRetRecepcaoStub stub = new CteRetRecepcaoStub(WebServiceCteUtil.getUrl(config, ServicosEnum.CONSULTA_RECIBO));

        CteRetRecepcaoStub.CTeCabecMsg cteCabecMsg = new CteRetRecepcaoStub.CTeCabecMsg();
        cteCabecMsg.setCUF(String.valueOf(config.getEstado().getCodigoUF()));
        cteCabecMsg.setVersaoDados(ConstantesCte.VERSAO.CTE);

        CteRetRecepcaoStub.CteCabecMsgE cteCabecMsgE = new CteRetRecepcaoStub.CteCabecMsgE();
        cteCabecMsgE.setCteCabecMsg(cteCabecMsg);

        // Timeout
        if (ObjetoCTeUtil.verifica(config.getTimeout()).isPresent()) {
            stub._getServiceClient().getOptions().setProperty(HTTPConstants.SO_TIMEOUT, config.getTimeout());
            stub._getServiceClient().getOptions().setProperty(HTTPConstants.CONNECTION_TIMEOUT,
                    config.getTimeout());
        }
        CteRetRecepcaoStub.CteRetRecepcaoResult result = stub.cteRetRecepcao(dadosMsg, cteCabecMsgE);

        LoggerUtil.log(ConsultaRecibo.class, "[XML-RETORNO]: " + result.getExtraElement().toString());
        return XmlCteUtil.xmlToObject(result.getExtraElement().toString(), TRetConsReciCTe.class);
    }
 
Example 13
Source Project: Java_CTe   Source File: Eventos.java    License: MIT License 6 votes vote down vote up
private static String envioMS(ConfiguracoesCte config, ServicosEnum tipoEvento, OMElement ome) throws CteException, RemoteException {
    br.com.swconsultoria.cte.wsdl.cterecepcaoeventoMS.CteRecepcaoEventoStub.CteDadosMsg dadosMsg = new br.com.swconsultoria.cte.wsdl.cterecepcaoeventoMS.CteRecepcaoEventoStub.CteDadosMsg();
    dadosMsg.setExtraElement(ome);

    br.com.swconsultoria.cte.wsdl.cterecepcaoeventoMS.CteRecepcaoEventoStub.CTeCabecMsg cteCabecMsg =
            new br.com.swconsultoria.cte.wsdl.cterecepcaoeventoMS.CteRecepcaoEventoStub.CTeCabecMsg();
    cteCabecMsg.setCUF(String.valueOf(config.getEstado().getCodigoUF()));
    cteCabecMsg.setVersaoDados(ConstantesCte.VERSAO.CTE);

    br.com.swconsultoria.cte.wsdl.cterecepcaoeventoMS.CteRecepcaoEventoStub.CteCabecMsgE cteCabecMsgE = new br.com.swconsultoria.cte.wsdl.cterecepcaoeventoMS.CteRecepcaoEventoStub.CteCabecMsgE();
    cteCabecMsgE.setCteCabecMsg(cteCabecMsg);

    String url = WebServiceCteUtil.getUrl(config, tipoEvento);

    br.com.swconsultoria.cte.wsdl.cterecepcaoeventoMS.CteRecepcaoEventoStub stub = new br.com.swconsultoria.cte.wsdl.cterecepcaoeventoMS.CteRecepcaoEventoStub(url);
    // Timeout
    if (ObjetoCTeUtil.verifica(config.getTimeout()).isPresent()) {
        stub._getServiceClient().getOptions().setProperty(HTTPConstants.SO_TIMEOUT, config.getTimeout());
        stub._getServiceClient().getOptions().setProperty(HTTPConstants.CONNECTION_TIMEOUT, config.getTimeout());
    }
    br.com.swconsultoria.cte.wsdl.cterecepcaoeventoMS.CteRecepcaoEventoStub.CteRecepcaoEventoResult result = stub.cteRecepcaoEvento(dadosMsg, cteCabecMsgE);

    LoggerUtil.log(Eventos.class, "[XML-RETORNO-" + tipoEvento + "]: " + result.getExtraElement().toString());
    return result.getExtraElement().toString();
}
 
Example 14
/**
 * Query the remote user manager to find out whether the specified user has the
 * specified permission.
 *
 * @param user Username
 * @param permission A valid Carbon permission
 * @return true if the user has the specified permission and false otherwise
 * @throws APIManagementException If and error occurs while accessing the admin service
 */
public boolean isUserAuthorized(String user, String permission) throws APIManagementException {
    CarbonUtils.setBasicAccessSecurityHeaders(username, password, authorizationManager._getServiceClient());
    if (cookie != null) {
        authorizationManager._getServiceClient().getOptions().setProperty(HTTPConstants.COOKIE_STRING, cookie);
    }

    try {
        boolean authorized = authorizationManager.isUserAuthorized(user, permission,
                CarbonConstants.UI_PERMISSION_ACTION);
        ServiceContext serviceContext = authorizationManager.
                _getServiceClient().getLastOperationContext().getServiceContext();
        cookie = (String) serviceContext.getProperty(HTTPConstants.COOKIE_STRING);
        return authorized;
    } catch (Exception e) {
        throw new APIManagementException("Error while accessing backend services for " +
                "user permission validation", e);
    }
}
 
Example 15
@Test(groups = { "wso2.esb" }, description = "Test for MIMEBoundary value in Content-Type header for multipart/form-data")
public void testReturnContentType() throws Exception {

    String boundary = "boundary";
    String jsonPayload = "{\"action\":\"ping\"}";

    SimpleHttpClient httpClient = new SimpleHttpClient();

    HttpResponse response = httpClient.doPost(getApiInvocationURL("testMIMEBoundary"), null, jsonPayload, HTTPConstants.MEDIA_TYPE_APPLICATION_JSON);
    String contentTypeData = response.getEntity().getContentType().getValue();

    if (contentTypeData.contains(boundary)) {
        String[] pairs = contentTypeData.split(";");
        for (String pair : pairs) {
            if (pair.contains(boundary)) {
                String[] boundaryDetails = pair.split("=");
                Assert.assertTrue(boundaryDetails[1].contains("MIMEBoundary_"), "MIMEBoundary is not set in Content-Type header");
            }
        }
    }
}
 
Example 16
@Test(groups = {"wso2.esb"}, description = "Test for charset value in the Content-Type header " +
                                           "in response once message is built in out out sequence")
public void charsetTestWithInComingContentType() 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("contentTypeCharsetProxy1"))
            , 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");
    Assert.assertTrue(contentType.contains("text/xml"), "Content-Type mismatched " + contentType);
    Assert.assertEquals(StringUtils.countMatches(contentType, HTTPConstants.CHAR_SET_ENCODING), 1
            , "charset repeated in Content-Type header " + contentType);

}
 
Example 17
@Test(groups = {"wso2.esb"})
public void outOnlyWithoutContentAwareMediatorTest() throws Exception {
    WireMonitorServer wireMonitorServer = new WireMonitorServer(3828);
    Map<String, String> headers = new HashMap<>();

    wireMonitorServer.start();

    headers.put(HttpHeaders.CONTENT_TYPE, "text/xml");
    headers.put(HTTPConstants.HEADER_SOAP_ACTION, "urn:placeOrder");

    HttpResponse response = HttpRequestUtil.doPost(new URL(getProxyServiceURLHttp("ESBJAVA4469"))
            , messageBody, headers);

    Assert.assertEquals(response.getResponseCode(), HttpStatus.SC_ACCEPTED, "Response code should be 202");
    String outGoingMessage = wireMonitorServer.getCapturedMessage();
    Assert.assertTrue(outGoingMessage.contains(">WSO2<")
            , "Outgoing message is empty or invalid content " + outGoingMessage);

}
 
Example 18
Source Project: product-ei   Source File: AuthenticatorClient.java    License: Apache License 2.0 6 votes vote down vote up
public String login(String userName, String password, String host) throws
        Exception {
    Boolean loginStatus;
    ServiceContext serviceContext;
    String sessionCookie;
    loginStatus = authenticationAdminStub.login(userName, password, host);
    if (!loginStatus) {
        throw new Exception("Login Unsuccessful. Return false as a login status by Server");
    }
    log.info("Login Successful");
    serviceContext = authenticationAdminStub._getServiceClient().getLastOperationContext().getServiceContext();
    sessionCookie = (String) serviceContext.getProperty(HTTPConstants.COOKIE_STRING);
    if (log.isDebugEnabled()) {
        log.debug("SessionCookie :" + sessionCookie);
    }
    return sessionCookie;
}
 
Example 19
/**
 * This test is to verify if division operation can be performed with given xml payload using
 *  datamapper mediator.
 */
@Test(description = "1.6.12.4")
public void performDivisionOperationUsingDatamapper() throws IOException, XMLStreamException {
    String testCaseId = "1.6.12.4";
    String apiInvocationUrl = getApiInvocationURLHttp(API_NAME +"/divide");
    String request =
            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
                    + "<DivideNumbers>\n"
                    + "    <num1>10</num1>\n"
                    + "    <num2>5</num2>\n"
                    + "</DivideNumbers>";

    String expectedResponse =
            "<ResultDivide>\n"
                    + "    <result>2.0</result>\n"
                    + "</ResultDivide>";
    String jdk11ExpectedResponse =
            "<ResultDivide>\n"
                    + "    <result>2</result>\n"
                    + "</ResultDivide>";

    HTTPUtils.invokePoxEndpointAndAssertTwoPayloads(apiInvocationUrl, request,
            HTTPConstants.MEDIA_TYPE_APPLICATION_XML,
            testCaseId, expectedResponse, jdk11ExpectedResponse, 200, "performDivisionOperationUsingDatamapper");

}
 
Example 20
/**
 * This test is to verify if it can get the round value with given xml payload using
 *  datamapper mediator.
 */
@Test(description = "1.6.12.5")
public void getRoundValueUsingDatamapper() throws IOException, XMLStreamException {
    String testCaseId = "1.6.12.5";
    String apiInvocationUrl = getApiInvocationURLHttp(API_NAME +"/round");
    String request =
            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
                    + "<RoundValue>\n"
                    + "    <num1>1.56</num1>\n"
                    + "</RoundValue>";

    String expectedResponse =
            "<ResultRoundValue>\n"
                    + "    <result>2.0</result>\n"
                    + "</ResultRoundValue>";

    String jdk11ExpectedResponse =
            "<ResultRoundValue>\n"
                    + "    <result>2</result>\n"
                    + "</ResultRoundValue>";

    HTTPUtils.invokePoxEndpointAndAssertTwoPayloads(apiInvocationUrl, request,
            HTTPConstants.MEDIA_TYPE_APPLICATION_XML,
            testCaseId, expectedResponse, jdk11ExpectedResponse, 200, "getRoundValueUsingDatamapper");

}
 
Example 21
/**
 * This test is to verify if it can get the ceiling value with given xml payload using
 *  datamapper mediator.
 */
@Test(description = "1.6.12.6")
public void getCeilingValueUsingDatamapper() throws IOException, XMLStreamException {
    String testCaseId = "1.6.12.6";
    String apiInvocationUrl = getApiInvocationURLHttp(API_NAME +"/ceiling");
    String request =
            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
                    + "<CeilingValue>\n"
                    + "    <num1>1.1</num1>\n"
                    + "</CeilingValue>";

    String expectedResponse =
            "<ResultCeilingValue>\n"
                    + "    <result>2.0</result>\n"
                    + "</ResultCeilingValue>";

    String jdk11ExpectedResponse =
            "<ResultCeilingValue>\n"
                    + "    <result>2</result>\n"
                    + "</ResultCeilingValue>";

    HTTPUtils.invokePoxEndpointAndAssertTwoPayloads(apiInvocationUrl, request,
            HTTPConstants.MEDIA_TYPE_APPLICATION_XML,
            testCaseId, expectedResponse, jdk11ExpectedResponse, 200, "getCeilingValueUsingDatamapper");

}
 
Example 22
Source Project: carbon-apimgt   Source File: APIGatewayAdminClientTest.java    License: Apache License 2.0 6 votes vote down vote up
@Before
public void setup() throws Exception {

    environment = new Environment();
    environment.setName(ENV_NAME);
    environment.setPassword(PASSWORD);
    environment.setUserName(USERNAME);
    environment.setServerURL(SERVER_URL);
    apiGatewayAdminStub = Mockito.mock(APIGatewayAdminStub.class);

    Options options = new Options();
    ServiceContext serviceContext = new ServiceContext();
    OperationContext operationContext = Mockito.mock(OperationContext.class);
    serviceContext.setProperty(HTTPConstants.COOKIE_STRING, "");
    ServiceClient serviceClient = Mockito.mock(ServiceClient.class);
    AuthenticationAdminStub authAdminStub = Mockito.mock(AuthenticationAdminStub.class);
    Mockito.doReturn(true).when(authAdminStub).login(Mockito.anyString(), Mockito.anyString(), Mockito.anyString());
    Mockito.when(authAdminStub._getServiceClient()).thenReturn(serviceClient);
    Mockito.when(serviceClient.getLastOperationContext()).thenReturn(operationContext);
    Mockito.when(operationContext.getServiceContext()).thenReturn(serviceContext);
    Mockito.when(apiGatewayAdminStub._getServiceClient()).thenReturn(serviceClient);
    Mockito.when(serviceClient.getOptions()).thenReturn(options);
    PowerMockito.whenNew(AuthenticationAdminStub.class)
            .withArguments(Mockito.any(ConfigurationContext.class), Mockito.anyString()).thenReturn(authAdminStub);
}
 
Example 23
Source Project: carbon-identity   Source File: Authenticator.java    License: Apache License 2.0 6 votes vote down vote up
private boolean authenticate() throws Exception {
    ConfigurationContext configurationContext;
    configurationContext = ConfigurationContextFactory.createDefaultConfigurationContext();
    Map<String, TransportOutDescription> transportsOut =configurationContext
            .getAxisConfiguration().getTransportsOut();
    for (TransportOutDescription transportOutDescription : transportsOut.values()) {
        transportOutDescription.getSender().init(configurationContext, transportOutDescription);
    }
    AuthenticationAdminStub authAdmin = new AuthenticationAdminStub(configurationContext,
            serverUrl);
    boolean isAuthenticated = authAdmin.login(userName, password, "localhost");
    cookie = (String) authAdmin._getServiceClient().getServiceContext()
            .getProperty(HTTPConstants.COOKIE_STRING);
    authAdmin._getServiceClient().cleanupTransport();
    return isAuthenticated;

}
 
Example 24
private void updateServiceClientOptions(String trpUrl, String addUrl, String prxUrl) throws AxisFault {
    Options options = new Options();
    options.setTo(new EndpointReference(trpUrl));
    options.setAction("urn:sampleOperation");
    options.setTimeOutInMilliSeconds(10000000);

    // set addressing, transport and proxy url
    if (addUrl != null && !"null".equals(addUrl)) {
        serviceClient.engageModule("addressing");
        options.setTo(new EndpointReference(addUrl));
    }
    if (trpUrl != null && !"null".equals(trpUrl)) {
        options.setProperty(Constants.Configuration.TRANSPORT_URL, trpUrl);
    } else {
        serviceClient.engageModule("addressing");
    }
    serviceClient.engageModule("addressing");
    if (prxUrl != null && !"null".equals(prxUrl)) {
        HttpTransportProperties.ProxyProperties proxyProperties = new HttpTransportProperties.ProxyProperties();
        try {
            URL url = new URL(prxUrl);
            proxyProperties.setProxyName(url.getHost());
            proxyProperties.setProxyPort(url.getPort());
            proxyProperties.setUserName("");
            proxyProperties.setPassWord("");
            proxyProperties.setDomain("");
            options.setProperty(HTTPConstants.PROXY, proxyProperties);
        } catch (MalformedURLException e) {
            String msg = "Error while creating proxy URL";
            log.error(msg, e);
            throw new AxisFault(msg, e);
        }
    }
    serviceClient.setOptions(options);
}
 
Example 25
Source Project: attic-stratos   Source File: SignedJWTAuthenticator.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public boolean isHandle(MessageContext msgCxt) {
    HttpServletRequest request =
            (HttpServletRequest) msgCxt.getProperty(HTTPConstants.MC_HTTP_SERVLETREQUEST);
    String authorizationHeader = request.getHeader(HTTPConstants.HEADER_AUTHORIZATION);
    if (authorizationHeader != null) {
        String authType = getAuthType(authorizationHeader);
        if (authType != null && authType.equalsIgnoreCase(AUTHORIZATION_HEADER_TYPE)) {
            return true;
        }
    }
    return false;
}
 
Example 26
Source Project: carbon-apimgt   Source File: SelfSignUpUtil.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * This method is used to set the Authorization header for the request sent to consent management service
 *
 * @param httpMethod   The method which requires to add the Authorization header
 * @param tenantDomain The tenant domain
 * @throws APIManagementException APIManagement Exception
 */
private static void setAuthorizationHeader(HttpRequestBase httpMethod, String tenantDomain)
        throws APIManagementException {
    UserRegistrationConfigDTO signupConfig = SelfSignUpUtil.getSignupConfiguration(tenantDomain);
    String adminUsername = signupConfig.getAdminUserName();
    String adminPassword = signupConfig.getAdminPassword();
    String toEncode = adminUsername + ":" + adminPassword;
    byte[] encoding = Base64.encodeBase64(toEncode.getBytes());
    String authHeader = new String(encoding, Charset.defaultCharset());
    httpMethod.addHeader(HTTPConstants.HEADER_AUTHORIZATION,
            APIConstants.AUTHORIZATION_HEADER_BASIC + " " + authHeader);
}
 
Example 27
@Override
public Object makeObject() throws Exception {
    EntitlementServiceStub stub = new EntitlementServiceStub(configurationContext,
            targetEndpoint);
    ServiceClient client = stub._getServiceClient();
    Options options = client.getOptions();
    options.setManageSession(true);
    options.setProperty(HTTPConstants.AUTHENTICATE, authenticator);
    return stub;
}
 
Example 28
/**
 * This test is to verify if add operation can be performed with given xml payload using
 *  datamapper mediator.
 */
@Test(description = "1.6.12.1")
public void performAddOperationUsingDatamapper() throws IOException, XMLStreamException {
    String testCaseId = "1.6.12.1";
    String apiInvocationUrl = getApiInvocationURLHttp(API_NAME +"/add");
    String request =
            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
                    + "<AddNumbers>\n"
                    + "    <num1>51</num1>\n"
                    + "    <num2>6</num2>\n"
                    + "</AddNumbers>";

    String expectedResponse =
            "<ResultAdd>\n"
                    + "    <result>57.0</result>\n"
                    + "</ResultAdd>";

    String jdk11ExpectedResponse =
            "<ResultAdd>\n"
                    + "    <result>57</result>\n"
                    + "</ResultAdd>";

    HTTPUtils.invokePoxEndpointAndAssertTwoPayloads(apiInvocationUrl, request,
            HTTPConstants.MEDIA_TYPE_APPLICATION_XML,
            testCaseId, expectedResponse, jdk11ExpectedResponse, 200, "performAddOperationUsingDatamapper");

}
 
Example 29
/**
 * This test is to verify if substract operation can be performed with given xml payload using
 *  datamapper mediator.
 */
@Test(description = "1.6.12.2")
public void performSubstractOperationUsingDatamapper() throws IOException, XMLStreamException {
    String testCaseId = "1.6.12.2";
    String apiInvocationUrl = getApiInvocationURLHttp(API_NAME +"/substract");
    String request =
            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
                    + "<SubstractNumbers>\n"
                    + "    <num1>51</num1>\n"
                    + "    <num2>6</num2>\n"
                    + "</SubstractNumbers>";

    String expectedResponse =
            "<ResultSubstract>\n"
                    + "    <result>45.0</result>\n"
                    + "</ResultSubstract>";

    String jdk11ExpectedResponse =
            "<ResultSubstract>\n"
                    + "    <result>45</result>\n"
                    + "</ResultSubstract>";

    HTTPUtils.invokePoxEndpointAndAssertTwoPayloads(apiInvocationUrl, request,
            HTTPConstants.MEDIA_TYPE_APPLICATION_XML,
            testCaseId, expectedResponse, jdk11ExpectedResponse, 200, "performSubstractOperationUsingDatamapper");

}
 
Example 30
/**
 * This test is to verify if multiplication operation can be performed with given xml payload using
 *  datamapper mediator.
 */
@Test(description = "1.6.12.3")
public void performMultiplicationOperationUsingDatamapper() throws IOException, XMLStreamException {
    String testCaseId = "1.6.12.3";
    String apiInvocationUrl = getApiInvocationURLHttp(API_NAME +"/multiply");
    String request =
            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
                    + "<MultiplyNumbers>\n"
                    + "    <num1>5</num1>\n"
                    + "    <num2>6</num2>\n"
                    + "</MultiplyNumbers>";

    String expectedResponse =
            "<ResultMultiply>\n"
                    + "    <result>30.0</result>\n"
                    + "</ResultMultiply>";

    String jdk11ExpectedResponse =
            "<ResultMultiply>\n"
                    + "    <result>30</result>\n"
                    + "</ResultMultiply>";

    HTTPUtils.invokePoxEndpointAndAssertTwoPayloads(apiInvocationUrl,request, HTTPConstants.MEDIA_TYPE_APPLICATION_XML,
            testCaseId, expectedResponse, jdk11ExpectedResponse, 200,
            "performMultiplicationOperationUsingDatamapper");

}