Java Code Examples for org.apache.axis2.AxisFault

The following examples show how to use org.apache.axis2.AxisFault. 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
@Test(groups = {"wso2.esb"}, description = "Test email sender with BCC ")
public void testEmailTransport()
        throws ESBMailTransportIntegrationTestException, XMLStreamException, AxisFault, MessagingException {
    Date date = new Date();
    String message = "Send Mail With BCC" + new Timestamp(date.getTime());
    AxisServiceClient axisServiceClient = new AxisServiceClient();
    OMElement request = AXIOMUtil.stringToOM(
            " <soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\">\n" +
            "   <soapenv:Header/>\n" +
            "   <soapenv:Body>\n" +
            " <emailSubject> Subject :" + message + "</emailSubject>\n" +
            "   </soapenv:Body>\n" +
            " </soapenv:Envelope>");
    axisServiceClient.sendReceive(request, getProxyServiceURLHttp("MailToTransportSenderBCC"), "mediate");
    assertTrue(GreenMailServer.isMailReceived("imap", bccUser, message), "Mail not received");
}
 
Example 2
private EntitledAttributesDTO[] getEntitledAttributes(String subjectName, String resourceName, String subjectId,
                                                      String action, boolean enableChildSearch,
                                                      EntitlementServiceStub stub, Authenticator authenticator)
        throws Exception {
    EntitledResultSetDTO results;
    try {
        results = stub.getEntitledAttributes(subjectName, resourceName, subjectId, action, enableChildSearch);
    } catch (AxisFault e) {
        if (ProxyConstants.SESSION_TIME_OUT.equals(e.getFaultCode().getLocalPart())) {
            setAuthCookie(true, stub, authenticator);
            results = stub.getEntitledAttributes(subjectName, resourceName, subjectId, action, enableChildSearch);
        } else {
            throw e;
        }
    }

    return results.getEntitledAttributesDTOs();
}
 
Example 3
@Test(groups = {"wso2.esb"}, description = "Creating SOAP1.1 fault code VersionMismatched")
public void testSOAP11FaultCodeVersionMismatched() throws AxisFault {
    try {
        axis2Client.sendSimpleStockQuoteRequest(
                getMainSequenceURL(),
                null,
                "WSO2");
        fail("This query must throw an exception.");
    } catch (AxisFault expected) {
        log.info("Fault Message : " + expected.getMessage());
        assertEquals(expected.getReason(), "Soap11FaultCodeVersionMismatchedTestCase", "Fault Reason Mismatched");
        assertEquals(expected.getFaultCode().getLocalPart(), "VersionMismatch", "Fault code value mismatched");
        assertEquals(expected.getFaultCode().getPrefix(), "soap11Env", "Fault code prefix mismatched");

    }

}
 
Example 4
/**
 * 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 5
private void storeBinaryData(String id, byte[] data) throws Exception {
	Map<String, String> params = new HashMap<String, String>();
	params.put("id", id);
	params.put("data", new String(Base64.encodeBase64(data), DBConstants.DEFAULT_CHAR_SET_TYPE));
	try {
           TestUtils.checkForService(this.epr);
		assertNotNull(TestUtils.callOperation(this.epr, "store_binary_data_op",
				params));
	} catch (AxisFault e) {
		// ignore for now
		if (!MySQLDMLServiceTest.INCOMING_MESSAGE_IS_NULL_ERROR.equals(e.getReason())) {
			e.printStackTrace();
			throw e;
		}
	}
}
 
Example 6
Source Project: micro-integrator   Source File: HL7MessageUtils.java    License: Apache License 2.0 6 votes vote down vote up
public static MessageContext createErrorMessageContext(String rawMessage, Exception errorMsg,
                                                       InboundProcessorParams params)
        throws AxisFault, HL7Exception {
    MessageContext synCtx = createSynapseMessageContext(
            params.getProperties().getProperty(MLLPConstants.HL7_INBOUND_TENANT_DOMAIN));

    if (params.getProperties().getProperty(Axis2HL7Constants.HL7_VALIDATION_PASSED) != null) {
        synCtx.setProperty(Axis2HL7Constants.HL7_VALIDATION_PASSED,
                           params.getProperties().getProperty(Axis2HL7Constants.HL7_VALIDATION_PASSED));
    }

    try {
        synCtx.setProperty(SynapseConstants.ERROR_CODE, SynapseConstants.RCV_IO_ERROR_RECEIVING);
        synCtx.setProperty(SynapseConstants.ERROR_MESSAGE, errorMsg.getMessage());
        synCtx.setProperty(SynapseConstants.ERROR_DETAIL,
                           (errorMsg.getCause() == null ? "null" : errorMsg.getCause().getMessage()));
        synCtx.setProperty(SynapseConstants.ERROR_EXCEPTION, errorMsg);
        synCtx.setEnvelope(createErrorEnvelope(synCtx, rawMessage, errorMsg.getMessage(), params));
    } catch (Exception e) {
        throw new HL7Exception(e);
    }

    return synCtx;
}
 
Example 7
Source Project: micro-integrator   Source File: ReScheduleTaskTestCase.java    License: Apache License 2.0 6 votes vote down vote up
private void IncreaseEmployeeSalary(String employeeNumber) throws AxisFault, InterruptedException {
    OMElement payload = fac.createOMElement("incrementEmployeeSalary", omNs);

    OMElement empNo = fac.createOMElement("employeeNumber", omNs);
    empNo.setText(employeeNumber);
    payload.addChild(empNo);

    OMElement salary = fac.createOMElement("increment", omNs);
    salary.setText("10000");
    payload.addChild(salary);

    new AxisServiceClient().sendRobust(payload, serviceEndPoint, "incrementEmployeeSalary");

    OMElement result = getEmployeeById(employeeNumber);
    Assert.assertTrue(result.toString().contains("<salary>60000.0</salary>"), "Expected Result Mismatched");
}
 
Example 8
Source Project: carbon-commons   Source File: FaultHandler.java    License: Apache License 2.0 6 votes vote down vote up
private void updateStatistics(MessageContext msgContext) throws AxisFault {
    // Process System Request count
    Parameter globalRequestCounter =
        msgContext.getParameter(StatisticsConstants.GLOBAL_REQUEST_COUNTER);
    ((AtomicInteger) globalRequestCounter.getValue()).incrementAndGet();

    // Increment the global fault count
    Parameter globalFaultCounter =
            msgContext.getParameter(StatisticsConstants.GLOBAL_FAULT_COUNTER);
    ((AtomicInteger) globalFaultCounter.getValue()).incrementAndGet();

    updateCurrentInvocationGlobalStatistics(msgContext);

    // Calculate response times
    ResponseTimeCalculator.calculateResponseTimes(msgContext);
}
 
Example 9
Source Project: product-ei   Source File: InvalidTargetAddressTestCase.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * This sets an invalid "To Address" in the clone target and message is mediated and see whether the service
 * can be found for the end point reference.
 */
@Test(groups = {"wso2.esb"}, description = "Tests an invalid 'To Address'' in the clone target")
public void testInvalidTargetAddress() throws Exception{

    try {
        axis2Client.sendMultipleQuoteRequest(
                getProxyServiceURLHttp("iterateInvalidTargetAddressTestProxy"), null,
                symbol, 4);
       Assert.fail("This Request must throw AxisFault"); // This will execute when the exception is not thrown as expected
    } catch (AxisFault message) {
        assertEquals(message.getReason(), ESBTestConstant.READ_TIME_OUT,
                "Iterator mediator worked even with an invalid clone target address.");
    }
}
 
Example 10
Source Project: product-ei   Source File: BpelVersioningTest.java    License: Apache License 2.0 5 votes vote down vote up
private void sendRequest() throws XMLStreamException, AxisFault {
    String payLoad = " <p:hello xmlns:p=\"http://ode/bpel/unit-test.wsdl\">\n" +
            "      <!--Exactly 1 occurrence--><TestPart>test</TestPart>\n" +
            "   </p:hello>";

    String operation = "hello";
    String serviceName = "HelloService";
    String expectedBefore = "World";
    String expectedAfter = "World-Version";
    requestSender.assertRequest(backEndUrl + serviceName, operation, payLoad,
            1, expectedBefore, true);
}
 
Example 11
Source Project: carbon-identity   Source File: IdentityPassiveSTSClient.java    License: Apache License 2.0 5 votes vote down vote up
public ClaimDTO[] getAllTrustedServices() throws AxisFault {
    try {
        return stub.getAllTrustedServices();
    } catch (Exception e) {
        handleException("Error occurred while getting all trusted services.", e);
    }
    return new ClaimDTO[0];
}
 
Example 12
/**
 * Removes publisher data
 *
 * @param id subscriber id
 * @throws AxisFault throws
 */
public void deleteSubscriber(String id) throws AxisFault {

    try {
        stub.deleteSubscriber(id);
    } catch (Exception e) {
        handleException(e);
    }
}
 
Example 13
@Test(groups = "wso2.esb", description = "Tests-XQuery test on empty message body")
public void testEmptyMessageBody() throws AxisFault, XMLStreamException {
    OMElement payload = null;
    response = axis2Client.sendSimpleStockQuoteRequest(
            getProxyServiceURLHttp("xQueryMediatorEmptySoapRequestTestProxy"),null, payload);
    assertNotNull(response,"Response is null");
    assertEquals(response.getFirstElement().getFirstChildWithName
            (new QName("http://services.samples/xsd", "symbol")).getText(),
                 "IBM", "Tag does not match");

}
 
Example 14
Source Project: carbon-commons   Source File: ApplicationAdminClient.java    License: Apache License 2.0 5 votes vote down vote up
public ApplicationMetadata getAppData(String appNameWithVersion) throws AxisFault {
    try {
        return stub.getAppData(appNameWithVersion);
    } catch (java.lang.Exception e) {
        handleException(bundle.getString("cannot.get.service.data"), e);
    }
    return null;
}
 
Example 15
private String getDecision(String request, EntitlementServiceStub stub, Authenticator authenticator)
        throws Exception {
    try {
        return stub.getDecision(request);
    } catch (AxisFault e) {
        if (ProxyConstants.SESSION_TIME_OUT.equals(e.getFaultCode().getLocalPart())) {
            setAuthCookie(true, stub, authenticator);
            return stub.getDecision(request);
        } else {
            throw e;
        }
    }
}
 
Example 16
Source Project: micro-integrator   Source File: Utils.java    License: Apache License 2.0 5 votes vote down vote up
public static void setJsonPayLoad(org.apache.axis2.context.MessageContext axis2MessageContext, Object jsonObject) {

        try {
            JsonUtil.getNewJsonPayload(axis2MessageContext, jsonObject.toString(), true, true);
        } catch (AxisFault axisFault) {
            axis2MessageContext.setProperty(Constants.HTTP_STATUS_CODE, Constants.INTERNAL_SERVER_ERROR);
            LOG.error("Error occurred while setting json payload", axisFault);
        }
        axis2MessageContext.setProperty("messageType", Constants.HEADER_VALUE_APPLICATION_JSON);
        axis2MessageContext.setProperty("ContentType", Constants.HEADER_VALUE_APPLICATION_JSON);
        axis2MessageContext.removeProperty(Constants.NO_ENTITY_BODY);
    }
 
Example 17
Source Project: micro-integrator   Source File: Utils.java    License: Apache License 2.0 5 votes vote down vote up
public static String[] getWsdlInformation(String serviceName,
                                          AxisConfiguration axisConfig) throws AxisFault {
    String ip;
    try {
        ip = NetworkUtils.getLocalHostname();
    } catch (SocketException e) {
        throw new AxisFault("Cannot get local host name", e);
    }

    //TODO Ideally, The transport on which wsdls are displayed, should be configurable.
    TransportInDescription transportInDescription = axisConfig.getTransportIn("http");

    if (transportInDescription == null) {
        transportInDescription = axisConfig.getTransportIn("https");
    }

    if (transportInDescription != null) {
        EndpointReference[] epr =
                transportInDescription.getReceiver().getEPRsForService(serviceName, ip);
        String wsdlUrlPrefix = epr[0].getAddress();
        if (wsdlUrlPrefix.endsWith("/")) {
            wsdlUrlPrefix = wsdlUrlPrefix.substring(0, wsdlUrlPrefix.length() - 1);
        }
        return new String[]{wsdlUrlPrefix + "?wsdl", wsdlUrlPrefix + "?wsdl2"};
    }
    return new String[]{};
}
 
Example 18
public boolean updateCredential(String userId, String userKey, String password,
                                CaptchaInfoBean captchaInfoBean) throws AxisFault {
    try {
        VerificationBean bean = stub.updateCredential(userId, userKey, password, captchaInfoBean);
        return bean.getVerified();
    } catch (Exception e) {
        handleException(e.getMessage(), e);
    }
    return false;
}
 
Example 19
public Map<String, String> countUsers(String filter) throws AxisFault {
    Map<String, String> counts = new HashMap<>();
    try {
        counts = convertArrayToMap(stub.countUsers(filter));
    } catch (Exception e) {
        handleException(e);
    }
    return counts;
}
 
Example 20
@Test(groups = "wso2.esb", description = "Tests when Out_Only property is enabled",
      dependsOnMethods = "testOutOnlyPropertyEnabledFalse", expectedExceptions = AxisFault.class)
public void testOutOnlyPropertyEnabledTrue() throws Exception {
    verifyProxyServiceExistence("OUT_ONLY_TrueTestProxy");

    axis2Client.sendSimpleStockQuoteRequest
            (getProxyServiceURLHttp("OUT_ONLY_TrueTestProxy"), null, "WSO2");
}
 
Example 21
Source Project: product-es   Source File: ActivityAdminServiceClient.java    License: Apache License 2.0 5 votes vote down vote up
public ActivityAdminServiceClient(String backEndUrl, String sessionCookie) throws AxisFault {
    this.endPoint = backEndUrl + serviceName;
    try {
        activityAdminServiceStub = new ActivityAdminServiceStub(endPoint);
    } catch (AxisFault axisFault) {
        log.error("activityAdminServiceStub Initialization fail " + axisFault.getMessage());
        throw new AxisFault("activityAdminServiceStub Initialization fail ", axisFault);
    }
    AuthenticateStub.authenticateStub(sessionCookie, activityAdminServiceStub);
}
 
Example 22
@Test(groups = "wso2.esb", description = "Tests-Adding custom content as sibling")
public void testAddSibling() throws AxisFault, XMLStreamException {

    response = axis2Client
            .sendSimpleStockQuoteRequest(getProxyServiceURLHttp("enrichIntegrationSiblingsTestProxy"), null, "IBM");
    assertNotNull(response, "Response is null");
    assertEquals(response.getFirstElement().getFirstChildWithName(new QName("http://services.samples/xsd", "test"))
            .getText(), "test", "Tag does not match");
}
 
Example 23
/**
 * @param policy
 * @throws AxisFault
 */
public void updatePolicy(PolicyDTO policy) throws AxisFault {
    try {
        if (policy.getPolicy() != null && policy.getPolicy().trim().length() > 0) {
            policy.setPolicy(policy.getPolicy().trim().replaceAll(">\\s+<", "><"));
        }
        stub.updatePolicy(policy);
    } catch (Exception e) {
        handleException(e);
    }
}
 
Example 24
private void validateEmail(String emailAddress) throws XPathExpressionException {
    OMElement payload = fac.createOMElement("addEmployee", omNs);

    OMElement empNo = fac.createOMElement("employeeNumber", omNs);
    empNo.setText("124");
    payload.addChild(empNo);

    OMElement lastName = fac.createOMElement("lastName", omNs);
    lastName.setText("BBB");
    payload.addChild(lastName);

    OMElement fName = fac.createOMElement("firstName", omNs);
    fName.setText("AAA");
    payload.addChild(fName);

    OMElement email = fac.createOMElement("email", omNs);
    email.setText(emailAddress);
    payload.addChild(email);

    OMElement salary = fac.createOMElement("salary", omNs);
    salary.setText("50000");
    payload.addChild(salary);

    boolean validationStatus = false;
    try {
        new AxisServiceClient().sendRobust(payload, getServiceUrlHttp(serviceName), "addEmployee");
        Assert.fail("This Request must throws a AxisFault due to VALIDATION_ERROR");
    } catch (AxisFault e) {
        validationStatus = true;
        Assert.assertTrue(e.getMessage().contains("VALIDATION_ERROR"),
                "VALIDATION_ERROR Not Found in " + "error message");
        Assert.assertTrue(e.getMessage().contains("Field Name: email"),
                "Field Name: email Not Found in" + " error message");
        Assert.assertTrue(e.getMessage().contains("Pattern"),
                "Validation Message: Pattern " + "Not Found " + "in " + "error message");

        log.info("email length validated");
    }
    Assert.assertTrue(validationStatus, "email address Not validated");
}
 
Example 25
@Test(groups = { "wso2.dss" }, invocationCount = 5, dependsOnMethods = "testServiceDeployment")
public void selectOperation() throws AxisFault, XPathExpressionException {
    OMFactory fac = OMAbstractFactory.getOMFactory();
    OMNamespace omNs = fac.createOMNamespace("http://ws.wso2.org/dataservice", "ns1");
    OMElement payload = fac.createOMElement("getProducts", omNs);
    OMElement result = new AxisServiceClient().sendReceive(payload, getServiceUrlHttp(serviceName), "getProducts");
    log.info("Response :" + result);
    Assert.assertTrue((result.toString().indexOf("Products") == 1), "Expected Result Not found");
    Assert.assertTrue(result.toString().contains("<Product>"), "Expected Result Not found");
    Assert.assertTrue(result.toString().contains("<ID>"), "Expected Result Not found");
    Assert.assertTrue(result.toString().contains("<Name>"), "Expected Result Not found");
    log.info("Service invocation success");
}
 
Example 26
Source Project: micro-integrator   Source File: TestUtils.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * method to wait until the given service is up and running
 *
 * @param url
 * @param timeout
 * @throws AxisFault
 */
public static void checkForService(String url, int timeout) throws AxisFault {
    url = url.replaceFirst("^https", "http");
    url = url + "?wsdl";
    System.out.println("Checking availability of url " + url);
    int count = 1;
    while (true) {
        try {
            HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
            connection.setRequestMethod("GET");
            connection.setConnectTimeout(timeout);
            connection.setReadTimeout(timeout);
            int responseCode = connection.getResponseCode();
            if (200 <= responseCode && responseCode <= 399) {
                System.out.println("Url " + url + " is available");
                break;
            }
            System.out.println("Connection attempt no " + count + " unsuccessful");
            try {
                Thread.sleep(10000);
            } catch (InterruptedException e1) {
                throw new AxisFault("Thread interuptted", e1);
            }
        } catch (IOException exception) {
            System.out.println("Connection attempt no " + count + " failed due to " + exception.getMessage());
        }
        count++;
        if (count > 30) {
            int timeInMins = (count * 10000) / 60000;
            System.out.println("Connection failed to url " + url + " for " + timeInMins + " minutes");
            throw new AxisFault("Connection failed to url " + url + " for " + timeInMins + " minutes");
        }
    }

}
 
Example 27
/**
 * @param cookie
 * @param backendServerURL
 * @param configCtx
 * @throws AxisFault
 */
public WorkflowImplAdminServiceClient(String cookie, String backendServerURL,
                                      ConfigurationContext configCtx) throws AxisFault {

    String serviceURL = backendServerURL + "WorkflowImplAdminService";
    stub = new WorkflowImplAdminServiceStub(configCtx, serviceURL);

    ServiceClient client = stub._getServiceClient();
    Options option = client.getOptions();
    option.setManageSession(true);
    option.setProperty(org.apache.axis2.transport.http.HTTPConstants.COOKIE_STRING, cookie);
}
 
Example 28
public HumanTaskClientAPIAdminClient(String bpsURL, String username, char[] password) throws AxisFault {
    stub = new HumanTaskClientAPIAdminStub(bpsURL + WFImplConstant.HT_SERVICES_URL);
    ServiceClient serviceClient = stub._getServiceClient();
    Options options = serviceClient.getOptions();
    HttpTransportProperties.Authenticator auth = new HttpTransportProperties.Authenticator();
    auth.setUsername(username);
    auth.setPassword(new String(password));
    auth.setPreemptiveAuthentication(true);
    List<String> authSchemes = new ArrayList<>();
    authSchemes.add(HttpTransportProperties.Authenticator.BASIC);
    auth.setAuthSchemes(authSchemes);
    options.setProperty(org.apache.axis2.transport.http.HTTPConstants.AUTHENTICATE, auth);
    serviceClient.setOptions(options);
}
 
Example 29
Source Project: product-ei   Source File: AxisServiceClientUtils.java    License: Apache License 2.0 5 votes vote down vote up
public static OMElement sendRequest(String payloadStr, EndpointReference targetEPR)
        throws XMLStreamException, AxisFault {
    OMElement payload = AXIOMUtil.stringToOM(payloadStr);
    Options options = new Options();
    options.setTo(targetEPR);
    //options.setAction("urn:" + operation); //since soapAction = ""

    //Blocking invocation
    ServiceClient sender = new ServiceClient();
    sender.setOptions(options);
    OMElement result = sender.sendReceive(payload);

    //log.info(result.toString());
    return result;
}
 
Example 30
Source Project: carbon-apimgt   Source File: RESTAPIAdminServiceProxy.java    License: Apache License 2.0 5 votes vote down vote up
public boolean addApi(String apiConfig) throws AxisFault {

        try {
            if (MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(tenantDomain)) {
                return restApiAdmin.addApiFromString(apiConfig);
            } else {
                return restApiAdmin.addApiForTenant(apiConfig, tenantDomain);
            }
        } catch (Exception e) {
            throw new AxisFault("Error while publishing API to the Gateway. " + e.getMessage(), e);
        }
    }