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

The following examples show how to use org.apache.axis2.transport.http.HTTPConstants. 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: Authenticator.java    From carbon-identity with 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 #2
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")
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
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 #4
Source File: ArithmeticOperationsInXMLUsingDatamapperTest.java    From micro-integrator with Apache License 2.0 6 votes vote down vote up
/**
 * 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 #5
Source File: ArithmeticOperationsInXMLUsingDatamapperTest.java    From micro-integrator with Apache License 2.0 6 votes vote down vote up
/**
 * 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
Source File: AuthenticatorClient.java    From micro-integrator with 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 #7
Source File: RemoteAuthorizationManagerClient.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
/**
 * 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 #8
Source File: ParallelRequestHelper.java    From micro-integrator with 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 #9
Source File: ArithmeticOperationsInXMLUsingDatamapperTest.java    From product-ei with Apache License 2.0 6 votes vote down vote up
/**
 * 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 #10
Source File: BasicAuthEntitlementServiceClient.java    From micro-integrator with Apache License 2.0 6 votes vote down vote up
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 #11
Source File: Inutilizar.java    From Java_CTe with 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 #12
Source File: ConsultaRecibo.java    From Java_CTe with 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 File: RemoteAuthorizationManagerClient.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
/**
 * 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 #14
Source File: MultipartFormdataMIMEBoundaryTestCase.java    From product-ei with Apache License 2.0 6 votes vote down vote up
@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 #15
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")
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 #16
Source File: ESBJAVA4469CallMediatorWithOutOnlyTestCase.java    From product-ei with Apache License 2.0 6 votes vote down vote up
@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 #17
Source File: AuthenticatorClient.java    From product-ei with 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 #18
Source File: ArithmeticOperationsInXMLUsingDatamapperTest.java    From product-ei with Apache License 2.0 6 votes vote down vote up
/**
 * 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 #19
Source File: ArithmeticOperationsInXMLUsingDatamapperTest.java    From product-ei with Apache License 2.0 6 votes vote down vote up
/**
 * 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 #20
Source File: ArithmeticOperationsInXMLUsingDatamapperTest.java    From product-ei with Apache License 2.0 6 votes vote down vote up
/**
 * 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 #21
Source File: Eventos.java    From Java_CTe with 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 #22
Source File: IdentityProviderService.java    From carbon-identity with 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 #23
Source File: APIGatewayAdminClientTest.java    From carbon-apimgt with 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 #24
Source File: ArithmeticOperationsInXMLUsingDatamapperTest.java    From micro-integrator with Apache License 2.0 5 votes vote down vote up
/**
 * This test is to verify if it can get the minimum value with given xml payload using
 *  datamapper mediator.
 */
@Test(description = "1.6.12.8")
public void getMinimumValueUsingDatamapper() throws IOException, XMLStreamException {
    String testCaseId = "1.6.12.8";
    String apiInvocationUrl = getApiInvocationURLHttp(API_NAME +"/min");
    String request =
            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
                    + "<MinValue>\n"
                    + "    <num1>5</num1>\n"
                    + "    <num2>9</num2>\n"
                    + "</MinValue>";

    String expectedResponse =
            "<ResultMinimumValue>\n"
                    + "    <result>5.0</result>\n"
                    + "</ResultMinimumValue>";

    String jdk11ExpectedResponse =
            "<ResultMinimumValue>\n"
                    + "    <result>5</result>\n"
                    + "</ResultMinimumValue>";

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

}
 
Example #25
Source File: MultipleCredentialsUserProxy.java    From carbon-identity-framework with Apache License 2.0 5 votes vote down vote up
/**
 * Gets logged in user of the server
 *
 * @return user name
 */
private String getLoggedInUser() {

    MessageContext context = MessageContext.getCurrentMessageContext();
    if (context != null) {
        HttpServletRequest request =
                (HttpServletRequest) context.getProperty(HTTPConstants.MC_HTTP_SERVLETREQUEST);
        if (request != null) {
            HttpSession httpSession = request.getSession(false);
            return (String) httpSession.getAttribute(ServerConstants.USER_LOGGED_IN);
        }
    }
    return null;
}
 
Example #26
Source File: ArithmeticOperationsInXMLUsingDatamapperTest.java    From micro-integrator with Apache License 2.0 5 votes vote down vote up
/**
 * 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 #27
Source File: Inutilizar.java    From Java_NFe with MIT License 5 votes vote down vote up
static TRetInutNFe inutiliza(ConfiguracoesNfe config, TInutNFe inutNFe, DocumentoEnum tipoDocumento, boolean validar)
           throws NfeException {

	try {

		String xml = XmlNfeUtil.objectToXml(inutNFe);
		xml = xml.replaceAll(" xmlns:ns2=\"http://www.w3.org/2000/09/xmldsig#\"", "");
		xml = Assinar.assinaNfe(config, xml, AssinaturaEnum.INUTILIZACAO);

		LoggerUtil.log(Inutilizar.class, "[XML-ENVIO]: " + xml);

		if (validar) {
			new Validar().validaXml(config, xml, ServicosEnum.INUTILIZACAO);
		}

		OMElement ome = AXIOMUtil.stringToOM(xml);

		NFeInutilizacao4Stub.NfeDadosMsg dadosMsg = new NFeInutilizacao4Stub.NfeDadosMsg();
		dadosMsg.setExtraElement(ome);

           NFeInutilizacao4Stub stub = new NFeInutilizacao4Stub(
                   WebServiceUtil.getUrl(config, tipoDocumento, ServicosEnum.INUTILIZACAO));

			// Timeout
			if (ObjetoUtil.verifica(config.getTimeout()).isPresent()) {
				stub._getServiceClient().getOptions().setProperty(HTTPConstants.SO_TIMEOUT, config.getTimeout());
				stub._getServiceClient().getOptions().setProperty(HTTPConstants.CONNECTION_TIMEOUT, config.getTimeout());
			}
		NFeInutilizacao4Stub.NfeResultMsg result = stub.nfeInutilizacaoNF(dadosMsg);

		LoggerUtil.log(Inutilizar.class, "[XML-RETORNO]: " + result.getExtraElement().toString());
		return XmlNfeUtil.xmlToObject(result.getExtraElement().toString(), TRetInutNFe.class);
	} catch (RemoteException | XMLStreamException | JAXBException e) {
		throw new NfeException(e.getMessage());
	}

}
 
Example #28
Source File: OAuthAdminServiceClient.java    From attic-stratos with Apache License 2.0 5 votes vote down vote up
public OAuthAdminServiceClient(String epr) throws AxisFault {

        XMLConfiguration conf = ConfUtil.getInstance(null).getConfiguration();
        int autosclaerSocketTimeout = conf.getInt("autoscaler.identity.clientTimeout", 180000);

        try {
            ServerConfiguration serverConfig = CarbonUtils.getServerConfiguration();
            String trustStorePath = serverConfig.getFirstProperty("Security.TrustStore.Location");
            String trustStorePassword = serverConfig.getFirstProperty("Security.TrustStore.Password");
            String type = serverConfig.getFirstProperty("Security.TrustStore.Type");
            System.setProperty("javax.net.ssl.trustStore", trustStorePath);
            System.setProperty("javax.net.ssl.trustStorePassword", trustStorePassword);
            System.setProperty("javax.net.ssl.trustStoreType", type);

            stub = new OAuthAdminServiceStub(epr);
            stub._getServiceClient().getOptions().setProperty(HTTPConstants.SO_TIMEOUT, autosclaerSocketTimeout);
            stub._getServiceClient().getOptions().setProperty(HTTPConstants.CONNECTION_TIMEOUT, autosclaerSocketTimeout);
            //String username = CarbonContext.getThreadLocalCarbonContext().getUsername();
            //TODO StratosAuthenticationHandler does not set to carbon context, thus user name becomes null.
            // For the moment username is hardcoded since above is fixed.
            String username = conf.getString("autoscaler.identity.adminUser", "admin");
            Utility.setAuthHeaders(stub._getServiceClient(), username);

        } catch (AxisFault axisFault) {
            String msg = "Failed to initiate identity service client. " + axisFault.getMessage();
            log.error(msg, axisFault);
            throw new AxisFault(msg, axisFault);
        }
    }
 
Example #29
Source File: Eventos.java    From Java_NFe with MIT License 5 votes vote down vote up
static String enviarEvento(ConfiguracoesNfe config, String xml, ServicosEnum tipoEvento, boolean valida, DocumentoEnum tipoDocumento)
        throws NfeException {

    try {

        xml = Assinar.assinaNfe(config, xml, AssinaturaEnum.EVENTO);

        LoggerUtil.log(Eventos.class, "[XML-ENVIO-" + tipoEvento + "]: " + xml);

        if (valida) {
            new Validar().validaXml(config, xml, tipoEvento);
        }

        OMElement ome = AXIOMUtil.stringToOM(xml);

        NFeRecepcaoEvento4Stub.NfeDadosMsg dadosMsg = new NFeRecepcaoEvento4Stub.NfeDadosMsg();
        dadosMsg.setExtraElement(ome);

        String url = WebServiceUtil.getUrl(config, tipoDocumento, tipoEvento);

        NFeRecepcaoEvento4Stub stub = new NFeRecepcaoEvento4Stub(url);
        // Timeout
        if (ObjetoUtil.verifica(config.getTimeout()).isPresent()) {
            stub._getServiceClient().getOptions().setProperty(HTTPConstants.SO_TIMEOUT, config.getTimeout());
            stub._getServiceClient().getOptions().setProperty(HTTPConstants.CONNECTION_TIMEOUT, config.getTimeout());
        }

        if (ObjetoUtil.verifica(config.getRetry()).isPresent()) {
            RetryParameter.populateRetry(stub, config.getRetry());
        }

        NFeRecepcaoEvento4Stub.NfeResultMsg result = stub.nfeRecepcaoEvento(dadosMsg);

        LoggerUtil.log(Eventos.class, "[XML-RETORNO-" + tipoEvento + "]: " + result.getExtraElement().toString());
        return result.getExtraElement().toString();
    } catch (RemoteException | XMLStreamException e) {
        throw new NfeException(e.getMessage());
    }

}
 
Example #30
Source File: SubscriptionCreationWSWorkflowExecutor.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
/**
 * Retrieves configured ServiceClient for communication with external services
 *
 * @param action web service action to use
 * @return configured service client
 * @throws AxisFault
 */
public ServiceClient getClient(String action) throws AxisFault {
    ServiceClient client = new ServiceClient(
            ServiceReferenceHolder.getInstance().getContextService().getClientConfigContext(), null);
    Options options = new Options();
    options.setAction(action);
    options.setTo(new EndpointReference(serviceEndpoint));

    if (contentType != null) {
        options.setProperty(Constants.Configuration.MESSAGE_TYPE, contentType);
    } else {
        options.setProperty(Constants.Configuration.MESSAGE_TYPE, HTTPConstants.MEDIA_TYPE_TEXT_XML);
    }

    HttpTransportProperties.Authenticator auth = new HttpTransportProperties.Authenticator();

    // Assumes authentication is required if username and password is given
    if (username != null && !username.isEmpty() && password != null && password.length != 0) {
        auth.setUsername(username);
        auth.setPassword(String.valueOf(password));
        auth.setPreemptiveAuthentication(true);
        List<String> authSchemes = new ArrayList<String>();
        authSchemes.add(HttpTransportProperties.Authenticator.BASIC);
        auth.setAuthSchemes(authSchemes);

        if (contentType == null) {
            options.setProperty(Constants.Configuration.MESSAGE_TYPE, HTTPConstants.MEDIA_TYPE_TEXT_XML);
        }
        options.setProperty(org.apache.axis2.transport.http.HTTPConstants.AUTHENTICATE, auth);
        options.setManageSession(true);
    }
    client.setOptions(options);

    return client;
}